babylon.viewer.max.js 5.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492
  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 = 15);
  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__(18); } catch(e) {}
  90. try { OIMO = OIMO || __webpack_require__(19); } catch(e) {}
  91. try { earcut = earcut || __webpack_require__(20); } 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. /**
  1451. * Ray from a pointer if availible (eg. 6dof controller)
  1452. */
  1453. _this.ray = null;
  1454. _this.skipOnPointerObservable = false;
  1455. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1456. return _this;
  1457. }
  1458. return PointerInfoPre;
  1459. }(PointerInfoBase));
  1460. BABYLON.PointerInfoPre = PointerInfoPre;
  1461. /**
  1462. * This type contains all the data related to a pointer event in Babylon.js.
  1463. * 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.
  1464. */
  1465. var PointerInfo = /** @class */ (function (_super) {
  1466. __extends(PointerInfo, _super);
  1467. function PointerInfo(type, event, pickInfo) {
  1468. var _this = _super.call(this, type, event) || this;
  1469. _this.pickInfo = pickInfo;
  1470. return _this;
  1471. }
  1472. return PointerInfo;
  1473. }(PointerInfoBase));
  1474. BABYLON.PointerInfo = PointerInfo;
  1475. })(BABYLON || (BABYLON = {}));
  1476. //# sourceMappingURL=babylon.pointerEvents.js.map
  1477. var BABYLON;
  1478. (function (BABYLON) {
  1479. BABYLON.ToGammaSpace = 1 / 2.2;
  1480. BABYLON.ToLinearSpace = 2.2;
  1481. BABYLON.Epsilon = 0.001;
  1482. /**
  1483. * Class used to hold a RBG color
  1484. */
  1485. var Color3 = /** @class */ (function () {
  1486. /**
  1487. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1488. * @param r defines the red component (between 0 and 1, default is 0)
  1489. * @param g defines the green component (between 0 and 1, default is 0)
  1490. * @param b defines the blue component (between 0 and 1, default is 0)
  1491. */
  1492. function Color3(
  1493. /**
  1494. * Defines the red component (between 0 and 1, default is 0)
  1495. */
  1496. r,
  1497. /**
  1498. * Defines the green component (between 0 and 1, default is 0)
  1499. */
  1500. g,
  1501. /**
  1502. * Defines the blue component (between 0 and 1, default is 0)
  1503. */
  1504. b) {
  1505. if (r === void 0) { r = 0; }
  1506. if (g === void 0) { g = 0; }
  1507. if (b === void 0) { b = 0; }
  1508. this.r = r;
  1509. this.g = g;
  1510. this.b = b;
  1511. }
  1512. /**
  1513. * Creates a string with the Color3 current values
  1514. * @returns the string representation of the Color3 object
  1515. */
  1516. Color3.prototype.toString = function () {
  1517. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1518. };
  1519. /**
  1520. * Returns the string "Color3"
  1521. * @returns "Color3"
  1522. */
  1523. Color3.prototype.getClassName = function () {
  1524. return "Color3";
  1525. };
  1526. /**
  1527. * Compute the Color3 hash code
  1528. * @returns an unique number that can be used to hash Color3 objects
  1529. */
  1530. Color3.prototype.getHashCode = function () {
  1531. var hash = this.r || 0;
  1532. hash = (hash * 397) ^ (this.g || 0);
  1533. hash = (hash * 397) ^ (this.b || 0);
  1534. return hash;
  1535. };
  1536. // Operators
  1537. /**
  1538. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1539. * @param array defines the array where to store the r,g,b components
  1540. * @param index defines an optional index in the target array to define where to start storing values
  1541. * @returns the current Color3 object
  1542. */
  1543. Color3.prototype.toArray = function (array, index) {
  1544. if (index === undefined) {
  1545. index = 0;
  1546. }
  1547. array[index] = this.r;
  1548. array[index + 1] = this.g;
  1549. array[index + 2] = this.b;
  1550. return this;
  1551. };
  1552. /**
  1553. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1554. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1555. * @returns a new {BABYLON.Color4} object
  1556. */
  1557. Color3.prototype.toColor4 = function (alpha) {
  1558. if (alpha === void 0) { alpha = 1; }
  1559. return new Color4(this.r, this.g, this.b, alpha);
  1560. };
  1561. /**
  1562. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1563. * @returns the new array
  1564. */
  1565. Color3.prototype.asArray = function () {
  1566. var result = new Array();
  1567. this.toArray(result, 0);
  1568. return result;
  1569. };
  1570. /**
  1571. * Returns the luminance value
  1572. * @returns a float value
  1573. */
  1574. Color3.prototype.toLuminance = function () {
  1575. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1576. };
  1577. /**
  1578. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1579. * @param otherColor defines the second operand
  1580. * @returns the new Color3 object
  1581. */
  1582. Color3.prototype.multiply = function (otherColor) {
  1583. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1584. };
  1585. /**
  1586. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1587. * @param otherColor defines the second operand
  1588. * @param result defines the Color3 object where to store the result
  1589. * @returns the current Color3
  1590. */
  1591. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1592. result.r = this.r * otherColor.r;
  1593. result.g = this.g * otherColor.g;
  1594. result.b = this.b * otherColor.b;
  1595. return this;
  1596. };
  1597. /**
  1598. * Determines equality between Color3 objects
  1599. * @param otherColor defines the second operand
  1600. * @returns true if the rgb values are equal to the given ones
  1601. */
  1602. Color3.prototype.equals = function (otherColor) {
  1603. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1604. };
  1605. /**
  1606. * Determines equality between the current Color3 object and a set of r,b,g values
  1607. * @param r defines the red component to check
  1608. * @param g defines the green component to check
  1609. * @param b defines the blue component to check
  1610. * @returns true if the rgb values are equal to the given ones
  1611. */
  1612. Color3.prototype.equalsFloats = function (r, g, b) {
  1613. return this.r === r && this.g === g && this.b === b;
  1614. };
  1615. /**
  1616. * Multiplies in place each rgb value by scale
  1617. * @param scale defines the scaling factor
  1618. * @returns the updated Color3
  1619. */
  1620. Color3.prototype.scale = function (scale) {
  1621. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1622. };
  1623. /**
  1624. * Multiplies the rgb values by scale and stores the result into "result"
  1625. * @param scale defines the scaling factor
  1626. * @param result defines the Color3 object where to store the result
  1627. * @returns the unmodified current Color3
  1628. */
  1629. Color3.prototype.scaleToRef = function (scale, result) {
  1630. result.r = this.r * scale;
  1631. result.g = this.g * scale;
  1632. result.b = this.b * scale;
  1633. return this;
  1634. };
  1635. /**
  1636. * Scale the current Color3 values by a factor and add the result to a given Color3
  1637. * @param scale defines the scale factor
  1638. * @param result defines color to store the result into
  1639. * @returns the unmodified current Color3
  1640. */
  1641. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1642. result.r += this.r * scale;
  1643. result.g += this.g * scale;
  1644. result.b += this.b * scale;
  1645. return this;
  1646. };
  1647. /**
  1648. * Clamps the rgb values by the min and max values and stores the result into "result"
  1649. * @param min defines minimum clamping value (default is 0)
  1650. * @param max defines maximum clamping value (default is 1)
  1651. * @param result defines color to store the result into
  1652. * @returns the original Color3
  1653. */
  1654. Color3.prototype.clampToRef = function (min, max, result) {
  1655. if (min === void 0) { min = 0; }
  1656. if (max === void 0) { max = 1; }
  1657. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1658. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1659. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1660. return this;
  1661. };
  1662. /**
  1663. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1664. * @param otherColor defines the second operand
  1665. * @returns the new Color3
  1666. */
  1667. Color3.prototype.add = function (otherColor) {
  1668. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1669. };
  1670. /**
  1671. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1672. * @param otherColor defines the second operand
  1673. * @param result defines Color3 object to store the result into
  1674. * @returns the unmodified current Color3
  1675. */
  1676. Color3.prototype.addToRef = function (otherColor, result) {
  1677. result.r = this.r + otherColor.r;
  1678. result.g = this.g + otherColor.g;
  1679. result.b = this.b + otherColor.b;
  1680. return this;
  1681. };
  1682. /**
  1683. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1684. * @param otherColor defines the second operand
  1685. * @returns the new Color3
  1686. */
  1687. Color3.prototype.subtract = function (otherColor) {
  1688. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1689. };
  1690. /**
  1691. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1692. * @param otherColor defines the second operand
  1693. * @param result defines Color3 object to store the result into
  1694. * @returns the unmodified current Color3
  1695. */
  1696. Color3.prototype.subtractToRef = function (otherColor, result) {
  1697. result.r = this.r - otherColor.r;
  1698. result.g = this.g - otherColor.g;
  1699. result.b = this.b - otherColor.b;
  1700. return this;
  1701. };
  1702. /**
  1703. * Copy the current object
  1704. * @returns a new Color3 copied the current one
  1705. */
  1706. Color3.prototype.clone = function () {
  1707. return new Color3(this.r, this.g, this.b);
  1708. };
  1709. /**
  1710. * Copies the rgb values from the source in the current Color3
  1711. * @param source defines the source Color3 object
  1712. * @returns the updated Color3 object
  1713. */
  1714. Color3.prototype.copyFrom = function (source) {
  1715. this.r = source.r;
  1716. this.g = source.g;
  1717. this.b = source.b;
  1718. return this;
  1719. };
  1720. /**
  1721. * Updates the Color3 rgb values from the given floats
  1722. * @param r defines the red component to read from
  1723. * @param g defines the green component to read from
  1724. * @param b defines the blue component to read from
  1725. * @returns the current Color3 object
  1726. */
  1727. Color3.prototype.copyFromFloats = function (r, g, b) {
  1728. this.r = r;
  1729. this.g = g;
  1730. this.b = b;
  1731. return this;
  1732. };
  1733. /**
  1734. * Updates the Color3 rgb values from the given floats
  1735. * @param r defines the red component to read from
  1736. * @param g defines the green component to read from
  1737. * @param b defines the blue component to read from
  1738. * @returns the current Color3 object
  1739. */
  1740. Color3.prototype.set = function (r, g, b) {
  1741. return this.copyFromFloats(r, g, b);
  1742. };
  1743. /**
  1744. * Compute the Color3 hexadecimal code as a string
  1745. * @returns a string containing the hexadecimal representation of the Color3 object
  1746. */
  1747. Color3.prototype.toHexString = function () {
  1748. var intR = (this.r * 255) | 0;
  1749. var intG = (this.g * 255) | 0;
  1750. var intB = (this.b * 255) | 0;
  1751. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1752. };
  1753. /**
  1754. * Computes a new Color3 converted from the current one to linear space
  1755. * @returns a new Color3 object
  1756. */
  1757. Color3.prototype.toLinearSpace = function () {
  1758. var convertedColor = new Color3();
  1759. this.toLinearSpaceToRef(convertedColor);
  1760. return convertedColor;
  1761. };
  1762. /**
  1763. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1764. * @param convertedColor defines the Color3 object where to store the linear space version
  1765. * @returns the unmodified Color3
  1766. */
  1767. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1768. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1769. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1770. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1771. return this;
  1772. };
  1773. /**
  1774. * Computes a new Color3 converted from the current one to gamma space
  1775. * @returns a new Color3 object
  1776. */
  1777. Color3.prototype.toGammaSpace = function () {
  1778. var convertedColor = new Color3();
  1779. this.toGammaSpaceToRef(convertedColor);
  1780. return convertedColor;
  1781. };
  1782. /**
  1783. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1784. * @param convertedColor defines the Color3 object where to store the gamma space version
  1785. * @returns the unmodified Color3
  1786. */
  1787. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1788. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1789. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1790. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1791. return this;
  1792. };
  1793. // Statics
  1794. /**
  1795. * Creates a new Color3 from the string containing valid hexadecimal values
  1796. * @param hex defines a string containing valid hexadecimal values
  1797. * @returns a new Color3 object
  1798. */
  1799. Color3.FromHexString = function (hex) {
  1800. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1801. return new Color3(0, 0, 0);
  1802. }
  1803. var r = parseInt(hex.substring(1, 3), 16);
  1804. var g = parseInt(hex.substring(3, 5), 16);
  1805. var b = parseInt(hex.substring(5, 7), 16);
  1806. return Color3.FromInts(r, g, b);
  1807. };
  1808. /**
  1809. * Creates a new Vector3 from the starting index of the given array
  1810. * @param array defines the source array
  1811. * @param offset defines an offset in the source array
  1812. * @returns a new Color3 object
  1813. */
  1814. Color3.FromArray = function (array, offset) {
  1815. if (offset === void 0) { offset = 0; }
  1816. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1817. };
  1818. /**
  1819. * Creates a new Color3 from integer values (< 256)
  1820. * @param r defines the red component to read from (value between 0 and 255)
  1821. * @param g defines the green component to read from (value between 0 and 255)
  1822. * @param b defines the blue component to read from (value between 0 and 255)
  1823. * @returns a new Color3 object
  1824. */
  1825. Color3.FromInts = function (r, g, b) {
  1826. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1827. };
  1828. /**
  1829. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1830. * @param start defines the start Color3 value
  1831. * @param end defines the end Color3 value
  1832. * @param amount defines the gradient value between start and end
  1833. * @returns a new Color3 object
  1834. */
  1835. Color3.Lerp = function (start, end, amount) {
  1836. var r = start.r + ((end.r - start.r) * amount);
  1837. var g = start.g + ((end.g - start.g) * amount);
  1838. var b = start.b + ((end.b - start.b) * amount);
  1839. return new Color3(r, g, b);
  1840. };
  1841. /**
  1842. * Returns a Color3 value containing a red color
  1843. * @returns a new Color3 object
  1844. */
  1845. Color3.Red = function () { return new Color3(1, 0, 0); };
  1846. /**
  1847. * Returns a Color3 value containing a green color
  1848. * @returns a new Color3 object
  1849. */
  1850. Color3.Green = function () { return new Color3(0, 1, 0); };
  1851. /**
  1852. * Returns a Color3 value containing a blue color
  1853. * @returns a new Color3 object
  1854. */
  1855. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1856. /**
  1857. * Returns a Color3 value containing a black color
  1858. * @returns a new Color3 object
  1859. */
  1860. Color3.Black = function () { return new Color3(0, 0, 0); };
  1861. /**
  1862. * Returns a Color3 value containing a white color
  1863. * @returns a new Color3 object
  1864. */
  1865. Color3.White = function () { return new Color3(1, 1, 1); };
  1866. /**
  1867. * Returns a Color3 value containing a purple color
  1868. * @returns a new Color3 object
  1869. */
  1870. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1871. /**
  1872. * Returns a Color3 value containing a magenta color
  1873. * @returns a new Color3 object
  1874. */
  1875. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1876. /**
  1877. * Returns a Color3 value containing a yellow color
  1878. * @returns a new Color3 object
  1879. */
  1880. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1881. /**
  1882. * Returns a Color3 value containing a gray color
  1883. * @returns a new Color3 object
  1884. */
  1885. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1886. /**
  1887. * Returns a Color3 value containing a teal color
  1888. * @returns a new Color3 object
  1889. */
  1890. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1891. /**
  1892. * Returns a Color3 value containing a random color
  1893. * @returns a new Color3 object
  1894. */
  1895. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1896. return Color3;
  1897. }());
  1898. BABYLON.Color3 = Color3;
  1899. /**
  1900. * Class used to hold a RBGA color
  1901. */
  1902. var Color4 = /** @class */ (function () {
  1903. /**
  1904. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1905. * @param r defines the red component (between 0 and 1, default is 0)
  1906. * @param g defines the green component (between 0 and 1, default is 0)
  1907. * @param b defines the blue component (between 0 and 1, default is 0)
  1908. * @param a defines the alpha component (between 0 and 1, default is 1)
  1909. */
  1910. function Color4(
  1911. /**
  1912. * Defines the red component (between 0 and 1, default is 0)
  1913. */
  1914. r,
  1915. /**
  1916. * Defines the green component (between 0 and 1, default is 0)
  1917. */
  1918. g,
  1919. /**
  1920. * Defines the blue component (between 0 and 1, default is 0)
  1921. */
  1922. b,
  1923. /**
  1924. * Defines the alpha component (between 0 and 1, default is 1)
  1925. */
  1926. a) {
  1927. if (r === void 0) { r = 0; }
  1928. if (g === void 0) { g = 0; }
  1929. if (b === void 0) { b = 0; }
  1930. if (a === void 0) { a = 1; }
  1931. this.r = r;
  1932. this.g = g;
  1933. this.b = b;
  1934. this.a = a;
  1935. }
  1936. // Operators
  1937. /**
  1938. * Adds in place the given Color4 values to the current Color4 object
  1939. * @param right defines the second operand
  1940. * @returns the current updated Color4 object
  1941. */
  1942. Color4.prototype.addInPlace = function (right) {
  1943. this.r += right.r;
  1944. this.g += right.g;
  1945. this.b += right.b;
  1946. this.a += right.a;
  1947. return this;
  1948. };
  1949. /**
  1950. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1951. * @returns the new array
  1952. */
  1953. Color4.prototype.asArray = function () {
  1954. var result = new Array();
  1955. this.toArray(result, 0);
  1956. return result;
  1957. };
  1958. /**
  1959. * Stores from the starting index in the given array the Color4 successive values
  1960. * @param array defines the array where to store the r,g,b components
  1961. * @param index defines an optional index in the target array to define where to start storing values
  1962. * @returns the current Color4 object
  1963. */
  1964. Color4.prototype.toArray = function (array, index) {
  1965. if (index === undefined) {
  1966. index = 0;
  1967. }
  1968. array[index] = this.r;
  1969. array[index + 1] = this.g;
  1970. array[index + 2] = this.b;
  1971. array[index + 3] = this.a;
  1972. return this;
  1973. };
  1974. /**
  1975. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1976. * @param right defines the second operand
  1977. * @returns a new Color4 object
  1978. */
  1979. Color4.prototype.add = function (right) {
  1980. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1981. };
  1982. /**
  1983. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1984. * @param right defines the second operand
  1985. * @returns a new Color4 object
  1986. */
  1987. Color4.prototype.subtract = function (right) {
  1988. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1989. };
  1990. /**
  1991. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1992. * @param right defines the second operand
  1993. * @param result defines the Color4 object where to store the result
  1994. * @returns the current Color4 object
  1995. */
  1996. Color4.prototype.subtractToRef = function (right, result) {
  1997. result.r = this.r - right.r;
  1998. result.g = this.g - right.g;
  1999. result.b = this.b - right.b;
  2000. result.a = this.a - right.a;
  2001. return this;
  2002. };
  2003. /**
  2004. * Creates a new Color4 with the current Color4 values multiplied by scale
  2005. * @param scale defines the scaling factor to apply
  2006. * @returns a new Color4 object
  2007. */
  2008. Color4.prototype.scale = function (scale) {
  2009. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2010. };
  2011. /**
  2012. * Multiplies the current Color4 values by scale and stores the result in "result"
  2013. * @param scale defines the scaling factor to apply
  2014. * @param result defines the Color4 object where to store the result
  2015. * @returns the current unmodified Color4
  2016. */
  2017. Color4.prototype.scaleToRef = function (scale, result) {
  2018. result.r = this.r * scale;
  2019. result.g = this.g * scale;
  2020. result.b = this.b * scale;
  2021. result.a = this.a * scale;
  2022. return this;
  2023. };
  2024. /**
  2025. * Scale the current Color4 values by a factor and add the result to a given Color4
  2026. * @param scale defines the scale factor
  2027. * @param result defines the Color4 object where to store the result
  2028. * @returns the unmodified current Color4
  2029. */
  2030. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2031. result.r += this.r * scale;
  2032. result.g += this.g * scale;
  2033. result.b += this.b * scale;
  2034. result.a += this.a * scale;
  2035. return this;
  2036. };
  2037. /**
  2038. * Clamps the rgb values by the min and max values and stores the result into "result"
  2039. * @param min defines minimum clamping value (default is 0)
  2040. * @param max defines maximum clamping value (default is 1)
  2041. * @param result defines color to store the result into.
  2042. * @returns the cuurent Color4
  2043. */
  2044. Color4.prototype.clampToRef = function (min, max, result) {
  2045. if (min === void 0) { min = 0; }
  2046. if (max === void 0) { max = 1; }
  2047. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2048. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2049. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2050. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2051. return this;
  2052. };
  2053. /**
  2054. * Multipy an Color4 value by another and return a new Color4 object
  2055. * @param color defines the Color4 value to multiply by
  2056. * @returns a new Color4 object
  2057. */
  2058. Color4.prototype.multiply = function (color) {
  2059. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2060. };
  2061. /**
  2062. * Multipy a Color4 value by another and push the result in a reference value
  2063. * @param color defines the Color4 value to multiply by
  2064. * @param result defines the Color4 to fill the result in
  2065. * @returns the result Color4
  2066. */
  2067. Color4.prototype.multiplyToRef = function (color, result) {
  2068. result.r = this.r * color.r;
  2069. result.g = this.g * color.g;
  2070. result.b = this.b * color.b;
  2071. result.a = this.a * color.a;
  2072. return result;
  2073. };
  2074. /**
  2075. * Creates a string with the Color4 current values
  2076. * @returns the string representation of the Color4 object
  2077. */
  2078. Color4.prototype.toString = function () {
  2079. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2080. };
  2081. /**
  2082. * Returns the string "Color4"
  2083. * @returns "Color4"
  2084. */
  2085. Color4.prototype.getClassName = function () {
  2086. return "Color4";
  2087. };
  2088. /**
  2089. * Compute the Color4 hash code
  2090. * @returns an unique number that can be used to hash Color4 objects
  2091. */
  2092. Color4.prototype.getHashCode = function () {
  2093. var hash = this.r || 0;
  2094. hash = (hash * 397) ^ (this.g || 0);
  2095. hash = (hash * 397) ^ (this.b || 0);
  2096. hash = (hash * 397) ^ (this.a || 0);
  2097. return hash;
  2098. };
  2099. /**
  2100. * Creates a new Color4 copied from the current one
  2101. * @returns a new Color4 object
  2102. */
  2103. Color4.prototype.clone = function () {
  2104. return new Color4(this.r, this.g, this.b, this.a);
  2105. };
  2106. /**
  2107. * Copies the given Color4 values into the current one
  2108. * @param source defines the source Color4 object
  2109. * @returns the current updated Color4 object
  2110. */
  2111. Color4.prototype.copyFrom = function (source) {
  2112. this.r = source.r;
  2113. this.g = source.g;
  2114. this.b = source.b;
  2115. this.a = source.a;
  2116. return this;
  2117. };
  2118. /**
  2119. * Copies the given float values into the current one
  2120. * @param r defines the red component to read from
  2121. * @param g defines the green component to read from
  2122. * @param b defines the blue component to read from
  2123. * @param a defines the alpha component to read from
  2124. * @returns the current updated Color4 object
  2125. */
  2126. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2127. this.r = r;
  2128. this.g = g;
  2129. this.b = b;
  2130. this.a = a;
  2131. return this;
  2132. };
  2133. /**
  2134. * Copies the given float values into the current one
  2135. * @param r defines the red component to read from
  2136. * @param g defines the green component to read from
  2137. * @param b defines the blue component to read from
  2138. * @param a defines the alpha component to read from
  2139. * @returns the current updated Color4 object
  2140. */
  2141. Color4.prototype.set = function (r, g, b, a) {
  2142. return this.copyFromFloats(r, g, b, a);
  2143. };
  2144. /**
  2145. * Compute the Color4 hexadecimal code as a string
  2146. * @returns a string containing the hexadecimal representation of the Color4 object
  2147. */
  2148. Color4.prototype.toHexString = function () {
  2149. var intR = (this.r * 255) | 0;
  2150. var intG = (this.g * 255) | 0;
  2151. var intB = (this.b * 255) | 0;
  2152. var intA = (this.a * 255) | 0;
  2153. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2154. };
  2155. /**
  2156. * Computes a new Color4 converted from the current one to linear space
  2157. * @returns a new Color4 object
  2158. */
  2159. Color4.prototype.toLinearSpace = function () {
  2160. var convertedColor = new Color4();
  2161. this.toLinearSpaceToRef(convertedColor);
  2162. return convertedColor;
  2163. };
  2164. /**
  2165. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2166. * @param convertedColor defines the Color4 object where to store the linear space version
  2167. * @returns the unmodified Color4
  2168. */
  2169. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2170. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2171. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2172. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2173. convertedColor.a = this.a;
  2174. return this;
  2175. };
  2176. /**
  2177. * Computes a new Color4 converted from the current one to gamma space
  2178. * @returns a new Color4 object
  2179. */
  2180. Color4.prototype.toGammaSpace = function () {
  2181. var convertedColor = new Color4();
  2182. this.toGammaSpaceToRef(convertedColor);
  2183. return convertedColor;
  2184. };
  2185. /**
  2186. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2187. * @param convertedColor defines the Color4 object where to store the gamma space version
  2188. * @returns the unmodified Color4
  2189. */
  2190. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2191. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2192. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2193. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2194. convertedColor.a = this.a;
  2195. return this;
  2196. };
  2197. // Statics
  2198. /**
  2199. * Creates a new Color4 from the string containing valid hexadecimal values
  2200. * @param hex defines a string containing valid hexadecimal values
  2201. * @returns a new Color4 object
  2202. */
  2203. Color4.FromHexString = function (hex) {
  2204. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2205. return new Color4(0.0, 0.0, 0.0, 0.0);
  2206. }
  2207. var r = parseInt(hex.substring(1, 3), 16);
  2208. var g = parseInt(hex.substring(3, 5), 16);
  2209. var b = parseInt(hex.substring(5, 7), 16);
  2210. var a = parseInt(hex.substring(7, 9), 16);
  2211. return Color4.FromInts(r, g, b, a);
  2212. };
  2213. /**
  2214. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2215. * @param left defines the start value
  2216. * @param right defines the end value
  2217. * @param amount defines the gradient factor
  2218. * @returns a new Color4 object
  2219. */
  2220. Color4.Lerp = function (left, right, amount) {
  2221. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2222. Color4.LerpToRef(left, right, amount, result);
  2223. return result;
  2224. };
  2225. /**
  2226. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2227. * @param left defines the start value
  2228. * @param right defines the end value
  2229. * @param amount defines the gradient factor
  2230. * @param result defines the Color4 object where to store data
  2231. */
  2232. Color4.LerpToRef = function (left, right, amount, result) {
  2233. result.r = left.r + (right.r - left.r) * amount;
  2234. result.g = left.g + (right.g - left.g) * amount;
  2235. result.b = left.b + (right.b - left.b) * amount;
  2236. result.a = left.a + (right.a - left.a) * amount;
  2237. };
  2238. /**
  2239. * Creates a new Color4 from the starting index element of the given array
  2240. * @param array defines the source array to read from
  2241. * @param offset defines the offset in the source array
  2242. * @returns a new Color4 object
  2243. */
  2244. Color4.FromArray = function (array, offset) {
  2245. if (offset === void 0) { offset = 0; }
  2246. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2247. };
  2248. /**
  2249. * Creates a new Color3 from integer values (< 256)
  2250. * @param r defines the red component to read from (value between 0 and 255)
  2251. * @param g defines the green component to read from (value between 0 and 255)
  2252. * @param b defines the blue component to read from (value between 0 and 255)
  2253. * @param a defines the alpha component to read from (value between 0 and 255)
  2254. * @returns a new Color3 object
  2255. */
  2256. Color4.FromInts = function (r, g, b, a) {
  2257. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2258. };
  2259. /**
  2260. * Check the content of a given array and convert it to an array containing RGBA data
  2261. * If the original array was already containing count * 4 values then it is returned directly
  2262. * @param colors defines the array to check
  2263. * @param count defines the number of RGBA data to expect
  2264. * @returns an array containing count * 4 values (RGBA)
  2265. */
  2266. Color4.CheckColors4 = function (colors, count) {
  2267. // Check if color3 was used
  2268. if (colors.length === count * 3) {
  2269. var colors4 = [];
  2270. for (var index = 0; index < colors.length; index += 3) {
  2271. var newIndex = (index / 3) * 4;
  2272. colors4[newIndex] = colors[index];
  2273. colors4[newIndex + 1] = colors[index + 1];
  2274. colors4[newIndex + 2] = colors[index + 2];
  2275. colors4[newIndex + 3] = 1.0;
  2276. }
  2277. return colors4;
  2278. }
  2279. return colors;
  2280. };
  2281. return Color4;
  2282. }());
  2283. BABYLON.Color4 = Color4;
  2284. /**
  2285. * Class representing a vector containing 2 coordinates
  2286. */
  2287. var Vector2 = /** @class */ (function () {
  2288. /**
  2289. * Creates a new Vector2 from the given x and y coordinates
  2290. * @param x defines the first coordinate
  2291. * @param y defines the second coordinate
  2292. */
  2293. function Vector2(
  2294. /** defines the first coordinate */
  2295. x,
  2296. /** defines the second coordinate */
  2297. y) {
  2298. this.x = x;
  2299. this.y = y;
  2300. }
  2301. /**
  2302. * Gets a string with the Vector2 coordinates
  2303. * @returns a string with the Vector2 coordinates
  2304. */
  2305. Vector2.prototype.toString = function () {
  2306. return "{X: " + this.x + " Y:" + this.y + "}";
  2307. };
  2308. /**
  2309. * Gets class name
  2310. * @returns the string "Vector2"
  2311. */
  2312. Vector2.prototype.getClassName = function () {
  2313. return "Vector2";
  2314. };
  2315. /**
  2316. * Gets current vector hash code
  2317. * @returns the Vector2 hash code as a number
  2318. */
  2319. Vector2.prototype.getHashCode = function () {
  2320. var hash = this.x || 0;
  2321. hash = (hash * 397) ^ (this.y || 0);
  2322. return hash;
  2323. };
  2324. // Operators
  2325. /**
  2326. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2327. * @param array defines the source array
  2328. * @param index defines the offset in source array
  2329. * @returns the current Vector2
  2330. */
  2331. Vector2.prototype.toArray = function (array, index) {
  2332. if (index === void 0) { index = 0; }
  2333. array[index] = this.x;
  2334. array[index + 1] = this.y;
  2335. return this;
  2336. };
  2337. /**
  2338. * Copy the current vector to an array
  2339. * @returns a new array with 2 elements: the Vector2 coordinates.
  2340. */
  2341. Vector2.prototype.asArray = function () {
  2342. var result = new Array();
  2343. this.toArray(result, 0);
  2344. return result;
  2345. };
  2346. /**
  2347. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2348. * @param source defines the source Vector2
  2349. * @returns the current updated Vector2
  2350. */
  2351. Vector2.prototype.copyFrom = function (source) {
  2352. this.x = source.x;
  2353. this.y = source.y;
  2354. return this;
  2355. };
  2356. /**
  2357. * Sets the Vector2 coordinates with the given floats
  2358. * @param x defines the first coordinate
  2359. * @param y defines the second coordinate
  2360. * @returns the current updated Vector2
  2361. */
  2362. Vector2.prototype.copyFromFloats = function (x, y) {
  2363. this.x = x;
  2364. this.y = y;
  2365. return this;
  2366. };
  2367. /**
  2368. * Sets the Vector2 coordinates with the given floats
  2369. * @param x defines the first coordinate
  2370. * @param y defines the second coordinate
  2371. * @returns the current updated Vector2
  2372. */
  2373. Vector2.prototype.set = function (x, y) {
  2374. return this.copyFromFloats(x, y);
  2375. };
  2376. /**
  2377. * Add another vector with the current one
  2378. * @param otherVector defines the other vector
  2379. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2380. */
  2381. Vector2.prototype.add = function (otherVector) {
  2382. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2383. };
  2384. /**
  2385. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2386. * @param otherVector defines the other vector
  2387. * @param result defines the target vector
  2388. * @returns the unmodified current Vector2
  2389. */
  2390. Vector2.prototype.addToRef = function (otherVector, result) {
  2391. result.x = this.x + otherVector.x;
  2392. result.y = this.y + otherVector.y;
  2393. return this;
  2394. };
  2395. /**
  2396. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2397. * @param otherVector defines the other vector
  2398. * @returns the current updated Vector2
  2399. */
  2400. Vector2.prototype.addInPlace = function (otherVector) {
  2401. this.x += otherVector.x;
  2402. this.y += otherVector.y;
  2403. return this;
  2404. };
  2405. /**
  2406. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2407. * @param otherVector defines the other vector
  2408. * @returns a new Vector2
  2409. */
  2410. Vector2.prototype.addVector3 = function (otherVector) {
  2411. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2412. };
  2413. /**
  2414. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2415. * @param otherVector defines the other vector
  2416. * @returns a new Vector2
  2417. */
  2418. Vector2.prototype.subtract = function (otherVector) {
  2419. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2420. };
  2421. /**
  2422. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2423. * @param otherVector defines the other vector
  2424. * @param result defines the target vector
  2425. * @returns the unmodified current Vector2
  2426. */
  2427. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2428. result.x = this.x - otherVector.x;
  2429. result.y = this.y - otherVector.y;
  2430. return this;
  2431. };
  2432. /**
  2433. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2434. * @param otherVector defines the other vector
  2435. * @returns the current updated Vector2
  2436. */
  2437. Vector2.prototype.subtractInPlace = function (otherVector) {
  2438. this.x -= otherVector.x;
  2439. this.y -= otherVector.y;
  2440. return this;
  2441. };
  2442. /**
  2443. * Multiplies in place the current Vector2 coordinates by the given ones
  2444. * @param otherVector defines the other vector
  2445. * @returns the current updated Vector2
  2446. */
  2447. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2448. this.x *= otherVector.x;
  2449. this.y *= otherVector.y;
  2450. return this;
  2451. };
  2452. /**
  2453. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2454. * @param otherVector defines the other vector
  2455. * @returns a new Vector2
  2456. */
  2457. Vector2.prototype.multiply = function (otherVector) {
  2458. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2459. };
  2460. /**
  2461. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2462. * @param otherVector defines the other vector
  2463. * @param result defines the target vector
  2464. * @returns the unmodified current Vector2
  2465. */
  2466. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2467. result.x = this.x * otherVector.x;
  2468. result.y = this.y * otherVector.y;
  2469. return this;
  2470. };
  2471. /**
  2472. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2473. * @param x defines the first coordinate
  2474. * @param y defines the second coordinate
  2475. * @returns a new Vector2
  2476. */
  2477. Vector2.prototype.multiplyByFloats = function (x, y) {
  2478. return new Vector2(this.x * x, this.y * y);
  2479. };
  2480. /**
  2481. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2482. * @param otherVector defines the other vector
  2483. * @returns a new Vector2
  2484. */
  2485. Vector2.prototype.divide = function (otherVector) {
  2486. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2487. };
  2488. /**
  2489. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2490. * @param otherVector defines the other vector
  2491. * @param result defines the target vector
  2492. * @returns the unmodified current Vector2
  2493. */
  2494. Vector2.prototype.divideToRef = function (otherVector, result) {
  2495. result.x = this.x / otherVector.x;
  2496. result.y = this.y / otherVector.y;
  2497. return this;
  2498. };
  2499. /**
  2500. * Divides the current Vector3 coordinates by the given ones
  2501. * @param otherVector defines the other vector
  2502. * @returns the current updated Vector2
  2503. */
  2504. Vector2.prototype.divideInPlace = function (otherVector) {
  2505. return this.divideToRef(otherVector, this);
  2506. };
  2507. /**
  2508. * Gets a new Vector2 with current Vector2 negated coordinates
  2509. * @returns a new Vector2
  2510. */
  2511. Vector2.prototype.negate = function () {
  2512. return new Vector2(-this.x, -this.y);
  2513. };
  2514. /**
  2515. * Multiply the Vector2 coordinates by scale
  2516. * @param scale defines the scaling factor
  2517. * @returns the current updated Vector2
  2518. */
  2519. Vector2.prototype.scaleInPlace = function (scale) {
  2520. this.x *= scale;
  2521. this.y *= scale;
  2522. return this;
  2523. };
  2524. /**
  2525. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2526. * @param scale defines the scaling factor
  2527. * @returns a new Vector2
  2528. */
  2529. Vector2.prototype.scale = function (scale) {
  2530. var result = new Vector2(0, 0);
  2531. this.scaleToRef(scale, result);
  2532. return result;
  2533. };
  2534. /**
  2535. * Scale the current Vector2 values by a factor to a given Vector2
  2536. * @param scale defines the scale factor
  2537. * @param result defines the Vector2 object where to store the result
  2538. * @returns the unmodified current Vector2
  2539. */
  2540. Vector2.prototype.scaleToRef = function (scale, result) {
  2541. result.x = this.x * scale;
  2542. result.y = this.y * scale;
  2543. return this;
  2544. };
  2545. /**
  2546. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2547. * @param scale defines the scale factor
  2548. * @param result defines the Vector2 object where to store the result
  2549. * @returns the unmodified current Vector2
  2550. */
  2551. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2552. result.x += this.x * scale;
  2553. result.y += this.y * scale;
  2554. return this;
  2555. };
  2556. /**
  2557. * Gets a boolean if two vectors are equals
  2558. * @param otherVector defines the other vector
  2559. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2560. */
  2561. Vector2.prototype.equals = function (otherVector) {
  2562. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2563. };
  2564. /**
  2565. * Gets a boolean if two vectors are equals (using an epsilon value)
  2566. * @param otherVector defines the other vector
  2567. * @param epsilon defines the minimal distance to consider equality
  2568. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2569. */
  2570. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2571. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2572. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2573. };
  2574. // Properties
  2575. /**
  2576. * Gets the length of the vector
  2577. * @returns the vector length (float)
  2578. */
  2579. Vector2.prototype.length = function () {
  2580. return Math.sqrt(this.x * this.x + this.y * this.y);
  2581. };
  2582. /**
  2583. * Gets the vector squared length
  2584. * @returns the vector squared length (float)
  2585. */
  2586. Vector2.prototype.lengthSquared = function () {
  2587. return (this.x * this.x + this.y * this.y);
  2588. };
  2589. // Methods
  2590. /**
  2591. * Normalize the vector
  2592. * @returns the current updated Vector2
  2593. */
  2594. Vector2.prototype.normalize = function () {
  2595. var len = this.length();
  2596. if (len === 0)
  2597. return this;
  2598. var num = 1.0 / len;
  2599. this.x *= num;
  2600. this.y *= num;
  2601. return this;
  2602. };
  2603. /**
  2604. * Gets a new Vector2 copied from the Vector2
  2605. * @returns a new Vector2
  2606. */
  2607. Vector2.prototype.clone = function () {
  2608. return new Vector2(this.x, this.y);
  2609. };
  2610. // Statics
  2611. /**
  2612. * Gets a new Vector2(0, 0)
  2613. * @returns a new Vector2
  2614. */
  2615. Vector2.Zero = function () {
  2616. return new Vector2(0, 0);
  2617. };
  2618. /**
  2619. * Gets a new Vector2(1, 1)
  2620. * @returns a new Vector2
  2621. */
  2622. Vector2.One = function () {
  2623. return new Vector2(1, 1);
  2624. };
  2625. /**
  2626. * Gets a new Vector2 set from the given index element of the given array
  2627. * @param array defines the data source
  2628. * @param offset defines the offset in the data source
  2629. * @returns a new Vector2
  2630. */
  2631. Vector2.FromArray = function (array, offset) {
  2632. if (offset === void 0) { offset = 0; }
  2633. return new Vector2(array[offset], array[offset + 1]);
  2634. };
  2635. /**
  2636. * Sets "result" from the given index element of the given array
  2637. * @param array defines the data source
  2638. * @param offset defines the offset in the data source
  2639. * @param result defines the target vector
  2640. */
  2641. Vector2.FromArrayToRef = function (array, offset, result) {
  2642. result.x = array[offset];
  2643. result.y = array[offset + 1];
  2644. };
  2645. /**
  2646. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2647. * @param value1 defines 1st point of control
  2648. * @param value2 defines 2nd point of control
  2649. * @param value3 defines 3rd point of control
  2650. * @param value4 defines 4th point of control
  2651. * @param amount defines the interpolation factor
  2652. * @returns a new Vector2
  2653. */
  2654. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2655. var squared = amount * amount;
  2656. var cubed = amount * squared;
  2657. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2658. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2659. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2660. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2661. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2662. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2663. return new Vector2(x, y);
  2664. };
  2665. /**
  2666. * 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".
  2667. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2668. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2669. * @param value defines the value to clamp
  2670. * @param min defines the lower limit
  2671. * @param max defines the upper limit
  2672. * @returns a new Vector2
  2673. */
  2674. Vector2.Clamp = function (value, min, max) {
  2675. var x = value.x;
  2676. x = (x > max.x) ? max.x : x;
  2677. x = (x < min.x) ? min.x : x;
  2678. var y = value.y;
  2679. y = (y > max.y) ? max.y : y;
  2680. y = (y < min.y) ? min.y : y;
  2681. return new Vector2(x, y);
  2682. };
  2683. /**
  2684. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2685. * @param value1 defines the 1st control point
  2686. * @param tangent1 defines the outgoing tangent
  2687. * @param value2 defines the 2nd control point
  2688. * @param tangent2 defines the incoming tangent
  2689. * @param amount defines the interpolation factor
  2690. * @returns a new Vector2
  2691. */
  2692. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2693. var squared = amount * amount;
  2694. var cubed = amount * squared;
  2695. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2696. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2697. var part3 = (cubed - (2.0 * squared)) + amount;
  2698. var part4 = cubed - squared;
  2699. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2700. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2701. return new Vector2(x, y);
  2702. };
  2703. /**
  2704. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2705. * @param start defines the start vector
  2706. * @param end defines the end vector
  2707. * @param amount defines the interpolation factor
  2708. * @returns a new Vector2
  2709. */
  2710. Vector2.Lerp = function (start, end, amount) {
  2711. var x = start.x + ((end.x - start.x) * amount);
  2712. var y = start.y + ((end.y - start.y) * amount);
  2713. return new Vector2(x, y);
  2714. };
  2715. /**
  2716. * Gets the dot product of the vector "left" and the vector "right"
  2717. * @param left defines first vector
  2718. * @param right defines second vector
  2719. * @returns the dot product (float)
  2720. */
  2721. Vector2.Dot = function (left, right) {
  2722. return left.x * right.x + left.y * right.y;
  2723. };
  2724. /**
  2725. * Returns a new Vector2 equal to the normalized given vector
  2726. * @param vector defines the vector to normalize
  2727. * @returns a new Vector2
  2728. */
  2729. Vector2.Normalize = function (vector) {
  2730. var newVector = vector.clone();
  2731. newVector.normalize();
  2732. return newVector;
  2733. };
  2734. /**
  2735. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2736. * @param left defines 1st vector
  2737. * @param right defines 2nd vector
  2738. * @returns a new Vector2
  2739. */
  2740. Vector2.Minimize = function (left, right) {
  2741. var x = (left.x < right.x) ? left.x : right.x;
  2742. var y = (left.y < right.y) ? left.y : right.y;
  2743. return new Vector2(x, y);
  2744. };
  2745. /**
  2746. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2747. * @param left defines 1st vector
  2748. * @param right defines 2nd vector
  2749. * @returns a new Vector2
  2750. */
  2751. Vector2.Maximize = function (left, right) {
  2752. var x = (left.x > right.x) ? left.x : right.x;
  2753. var y = (left.y > right.y) ? left.y : right.y;
  2754. return new Vector2(x, y);
  2755. };
  2756. /**
  2757. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2758. * @param vector defines the vector to transform
  2759. * @param transformation defines the matrix to apply
  2760. * @returns a new Vector2
  2761. */
  2762. Vector2.Transform = function (vector, transformation) {
  2763. var r = Vector2.Zero();
  2764. Vector2.TransformToRef(vector, transformation, r);
  2765. return r;
  2766. };
  2767. /**
  2768. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2769. * @param vector defines the vector to transform
  2770. * @param transformation defines the matrix to apply
  2771. * @param result defines the target vector
  2772. */
  2773. Vector2.TransformToRef = function (vector, transformation, result) {
  2774. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2775. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2776. result.x = x;
  2777. result.y = y;
  2778. };
  2779. /**
  2780. * Determines if a given vector is included in a triangle
  2781. * @param p defines the vector to test
  2782. * @param p0 defines 1st triangle point
  2783. * @param p1 defines 2nd triangle point
  2784. * @param p2 defines 3rd triangle point
  2785. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2786. */
  2787. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2788. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2789. var sign = a < 0 ? -1 : 1;
  2790. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2791. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2792. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2793. };
  2794. /**
  2795. * Gets the distance between the vectors "value1" and "value2"
  2796. * @param value1 defines first vector
  2797. * @param value2 defines second vector
  2798. * @returns the distance between vectors
  2799. */
  2800. Vector2.Distance = function (value1, value2) {
  2801. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2802. };
  2803. /**
  2804. * Returns the squared distance between the vectors "value1" and "value2"
  2805. * @param value1 defines first vector
  2806. * @param value2 defines second vector
  2807. * @returns the squared distance between vectors
  2808. */
  2809. Vector2.DistanceSquared = function (value1, value2) {
  2810. var x = value1.x - value2.x;
  2811. var y = value1.y - value2.y;
  2812. return (x * x) + (y * y);
  2813. };
  2814. /**
  2815. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2816. * @param value1 defines first vector
  2817. * @param value2 defines second vector
  2818. * @returns a new Vector2
  2819. */
  2820. Vector2.Center = function (value1, value2) {
  2821. var center = value1.add(value2);
  2822. center.scaleInPlace(0.5);
  2823. return center;
  2824. };
  2825. /**
  2826. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2827. * @param p defines the middle point
  2828. * @param segA defines one point of the segment
  2829. * @param segB defines the other point of the segment
  2830. * @returns the shortest distance
  2831. */
  2832. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2833. var l2 = Vector2.DistanceSquared(segA, segB);
  2834. if (l2 === 0.0) {
  2835. return Vector2.Distance(p, segA);
  2836. }
  2837. var v = segB.subtract(segA);
  2838. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2839. var proj = segA.add(v.multiplyByFloats(t, t));
  2840. return Vector2.Distance(p, proj);
  2841. };
  2842. return Vector2;
  2843. }());
  2844. BABYLON.Vector2 = Vector2;
  2845. /**
  2846. * Classed used to store (x,y,z) vector representation
  2847. * A Vector3 is the main object used in 3D geometry
  2848. * It can represent etiher the coordinates of a point the space, either a direction
  2849. * Reminder: Babylon.js uses a left handed forward facing system
  2850. */
  2851. var Vector3 = /** @class */ (function () {
  2852. /**
  2853. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2854. * @param x defines the first coordinates (on X axis)
  2855. * @param y defines the second coordinates (on Y axis)
  2856. * @param z defines the third coordinates (on Z axis)
  2857. */
  2858. function Vector3(
  2859. /**
  2860. * Defines the first coordinates (on X axis)
  2861. */
  2862. x,
  2863. /**
  2864. * Defines the second coordinates (on Y axis)
  2865. */
  2866. y,
  2867. /**
  2868. * Defines the third coordinates (on Z axis)
  2869. */
  2870. z) {
  2871. this.x = x;
  2872. this.y = y;
  2873. this.z = z;
  2874. }
  2875. /**
  2876. * Creates a string representation of the Vector3
  2877. * @returns a string with the Vector3 coordinates.
  2878. */
  2879. Vector3.prototype.toString = function () {
  2880. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2881. };
  2882. /**
  2883. * Gets the class name
  2884. * @returns the string "Vector3"
  2885. */
  2886. Vector3.prototype.getClassName = function () {
  2887. return "Vector3";
  2888. };
  2889. /**
  2890. * Creates the Vector3 hash code
  2891. * @returns a number which tends to be unique between Vector3 instances
  2892. */
  2893. Vector3.prototype.getHashCode = function () {
  2894. var hash = this.x || 0;
  2895. hash = (hash * 397) ^ (this.y || 0);
  2896. hash = (hash * 397) ^ (this.z || 0);
  2897. return hash;
  2898. };
  2899. // Operators
  2900. /**
  2901. * Creates an array containing three elements : the coordinates of the Vector3
  2902. * @returns a new array of numbers
  2903. */
  2904. Vector3.prototype.asArray = function () {
  2905. var result = [];
  2906. this.toArray(result, 0);
  2907. return result;
  2908. };
  2909. /**
  2910. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2911. * @param array defines the destination array
  2912. * @param index defines the offset in the destination array
  2913. * @returns the current Vector3
  2914. */
  2915. Vector3.prototype.toArray = function (array, index) {
  2916. if (index === void 0) { index = 0; }
  2917. array[index] = this.x;
  2918. array[index + 1] = this.y;
  2919. array[index + 2] = this.z;
  2920. return this;
  2921. };
  2922. /**
  2923. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2924. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2925. */
  2926. Vector3.prototype.toQuaternion = function () {
  2927. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2928. };
  2929. /**
  2930. * Adds the given vector to the current Vector3
  2931. * @param otherVector defines the second operand
  2932. * @returns the current updated Vector3
  2933. */
  2934. Vector3.prototype.addInPlace = function (otherVector) {
  2935. this.x += otherVector.x;
  2936. this.y += otherVector.y;
  2937. this.z += otherVector.z;
  2938. return this;
  2939. };
  2940. /**
  2941. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2942. * @param otherVector defines the second operand
  2943. * @returns the resulting Vector3
  2944. */
  2945. Vector3.prototype.add = function (otherVector) {
  2946. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2947. };
  2948. /**
  2949. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2950. * @param otherVector defines the second operand
  2951. * @param result defines the Vector3 object where to store the result
  2952. * @returns the current Vector3
  2953. */
  2954. Vector3.prototype.addToRef = function (otherVector, result) {
  2955. result.x = this.x + otherVector.x;
  2956. result.y = this.y + otherVector.y;
  2957. result.z = this.z + otherVector.z;
  2958. return this;
  2959. };
  2960. /**
  2961. * Subtract the given vector from the current Vector3
  2962. * @param otherVector defines the second operand
  2963. * @returns the current updated Vector3
  2964. */
  2965. Vector3.prototype.subtractInPlace = function (otherVector) {
  2966. this.x -= otherVector.x;
  2967. this.y -= otherVector.y;
  2968. this.z -= otherVector.z;
  2969. return this;
  2970. };
  2971. /**
  2972. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2973. * @param otherVector defines the second operand
  2974. * @returns the resulting Vector3
  2975. */
  2976. Vector3.prototype.subtract = function (otherVector) {
  2977. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2978. };
  2979. /**
  2980. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2981. * @param otherVector defines the second operand
  2982. * @param result defines the Vector3 object where to store the result
  2983. * @returns the current Vector3
  2984. */
  2985. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2986. result.x = this.x - otherVector.x;
  2987. result.y = this.y - otherVector.y;
  2988. result.z = this.z - otherVector.z;
  2989. return this;
  2990. };
  2991. /**
  2992. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2993. * @param x defines the x coordinate of the operand
  2994. * @param y defines the y coordinate of the operand
  2995. * @param z defines the z coordinate of the operand
  2996. * @returns the resulting Vector3
  2997. */
  2998. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2999. return new Vector3(this.x - x, this.y - y, this.z - z);
  3000. };
  3001. /**
  3002. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3003. * @param x defines the x coordinate of the operand
  3004. * @param y defines the y coordinate of the operand
  3005. * @param z defines the z coordinate of the operand
  3006. * @param result defines the Vector3 object where to store the result
  3007. * @returns the current Vector3
  3008. */
  3009. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3010. result.x = this.x - x;
  3011. result.y = this.y - y;
  3012. result.z = this.z - z;
  3013. return this;
  3014. };
  3015. /**
  3016. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3017. * @returns a new Vector3
  3018. */
  3019. Vector3.prototype.negate = function () {
  3020. return new Vector3(-this.x, -this.y, -this.z);
  3021. };
  3022. /**
  3023. * Multiplies the Vector3 coordinates by the float "scale"
  3024. * @param scale defines the multiplier factor
  3025. * @returns the current updated Vector3
  3026. */
  3027. Vector3.prototype.scaleInPlace = function (scale) {
  3028. this.x *= scale;
  3029. this.y *= scale;
  3030. this.z *= scale;
  3031. return this;
  3032. };
  3033. /**
  3034. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3035. * @param scale defines the multiplier factor
  3036. * @returns a new Vector3
  3037. */
  3038. Vector3.prototype.scale = function (scale) {
  3039. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3040. };
  3041. /**
  3042. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3043. * @param scale defines the multiplier factor
  3044. * @param result defines the Vector3 object where to store the result
  3045. * @returns the current Vector3
  3046. */
  3047. Vector3.prototype.scaleToRef = function (scale, result) {
  3048. result.x = this.x * scale;
  3049. result.y = this.y * scale;
  3050. result.z = this.z * scale;
  3051. return this;
  3052. };
  3053. /**
  3054. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3055. * @param scale defines the scale factor
  3056. * @param result defines the Vector3 object where to store the result
  3057. * @returns the unmodified current Vector3
  3058. */
  3059. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3060. result.x += this.x * scale;
  3061. result.y += this.y * scale;
  3062. result.z += this.z * scale;
  3063. return this;
  3064. };
  3065. /**
  3066. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3067. * @param otherVector defines the second operand
  3068. * @returns true if both vectors are equals
  3069. */
  3070. Vector3.prototype.equals = function (otherVector) {
  3071. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3072. };
  3073. /**
  3074. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3075. * @param otherVector defines the second operand
  3076. * @param epsilon defines the minimal distance to define values as equals
  3077. * @returns true if both vectors are distant less than epsilon
  3078. */
  3079. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3080. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3081. 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);
  3082. };
  3083. /**
  3084. * Returns true if the current Vector3 coordinates equals the given floats
  3085. * @param x defines the x coordinate of the operand
  3086. * @param y defines the y coordinate of the operand
  3087. * @param z defines the z coordinate of the operand
  3088. * @returns true if both vectors are equals
  3089. */
  3090. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3091. return this.x === x && this.y === y && this.z === z;
  3092. };
  3093. /**
  3094. * Multiplies the current Vector3 coordinates by the given ones
  3095. * @param otherVector defines the second operand
  3096. * @returns the current updated Vector3
  3097. */
  3098. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3099. this.x *= otherVector.x;
  3100. this.y *= otherVector.y;
  3101. this.z *= otherVector.z;
  3102. return this;
  3103. };
  3104. /**
  3105. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3106. * @param otherVector defines the second operand
  3107. * @returns the new Vector3
  3108. */
  3109. Vector3.prototype.multiply = function (otherVector) {
  3110. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3111. };
  3112. /**
  3113. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3114. * @param otherVector defines the second operand
  3115. * @param result defines the Vector3 object where to store the result
  3116. * @returns the current Vector3
  3117. */
  3118. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3119. result.x = this.x * otherVector.x;
  3120. result.y = this.y * otherVector.y;
  3121. result.z = this.z * otherVector.z;
  3122. return this;
  3123. };
  3124. /**
  3125. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3126. * @param x defines the x coordinate of the operand
  3127. * @param y defines the y coordinate of the operand
  3128. * @param z defines the z coordinate of the operand
  3129. * @returns the new Vector3
  3130. */
  3131. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3132. return new Vector3(this.x * x, this.y * y, this.z * z);
  3133. };
  3134. /**
  3135. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3136. * @param otherVector defines the second operand
  3137. * @returns the new Vector3
  3138. */
  3139. Vector3.prototype.divide = function (otherVector) {
  3140. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3141. };
  3142. /**
  3143. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3144. * @param otherVector defines the second operand
  3145. * @param result defines the Vector3 object where to store the result
  3146. * @returns the current Vector3
  3147. */
  3148. Vector3.prototype.divideToRef = function (otherVector, result) {
  3149. result.x = this.x / otherVector.x;
  3150. result.y = this.y / otherVector.y;
  3151. result.z = this.z / otherVector.z;
  3152. return this;
  3153. };
  3154. /**
  3155. * Divides the current Vector3 coordinates by the given ones.
  3156. * @param otherVector defines the second operand
  3157. * @returns the current updated Vector3
  3158. */
  3159. Vector3.prototype.divideInPlace = function (otherVector) {
  3160. return this.divideToRef(otherVector, this);
  3161. };
  3162. /**
  3163. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3164. * @param other defines the second operand
  3165. * @returns the current updated Vector3
  3166. */
  3167. Vector3.prototype.minimizeInPlace = function (other) {
  3168. if (other.x < this.x)
  3169. this.x = other.x;
  3170. if (other.y < this.y)
  3171. this.y = other.y;
  3172. if (other.z < this.z)
  3173. this.z = other.z;
  3174. return this;
  3175. };
  3176. /**
  3177. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3178. * @param other defines the second operand
  3179. * @returns the current updated Vector3
  3180. */
  3181. Vector3.prototype.maximizeInPlace = function (other) {
  3182. if (other.x > this.x)
  3183. this.x = other.x;
  3184. if (other.y > this.y)
  3185. this.y = other.y;
  3186. if (other.z > this.z)
  3187. this.z = other.z;
  3188. return this;
  3189. };
  3190. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3191. /**
  3192. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3193. */
  3194. get: function () {
  3195. var absX = Math.abs(this.x);
  3196. var absY = Math.abs(this.y);
  3197. if (absX !== absY) {
  3198. return true;
  3199. }
  3200. var absZ = Math.abs(this.z);
  3201. if (absX !== absZ) {
  3202. return true;
  3203. }
  3204. if (absY !== absZ) {
  3205. return true;
  3206. }
  3207. return false;
  3208. },
  3209. enumerable: true,
  3210. configurable: true
  3211. });
  3212. // Properties
  3213. /**
  3214. * Gets the length of the Vector3
  3215. * @returns the length of the Vecto3
  3216. */
  3217. Vector3.prototype.length = function () {
  3218. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3219. };
  3220. /**
  3221. * Gets the squared length of the Vector3
  3222. * @returns squared length of the Vector3
  3223. */
  3224. Vector3.prototype.lengthSquared = function () {
  3225. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3226. };
  3227. /**
  3228. * Normalize the current Vector3.
  3229. * Please note that this is an in place operation.
  3230. * @returns the current updated Vector3
  3231. */
  3232. Vector3.prototype.normalize = function () {
  3233. var len = this.length();
  3234. if (len === 0 || len === 1.0)
  3235. return this;
  3236. var num = 1.0 / len;
  3237. this.x *= num;
  3238. this.y *= num;
  3239. this.z *= num;
  3240. return this;
  3241. };
  3242. /**
  3243. * Normalize the current Vector3 to a new vector
  3244. * @returns the new Vector3
  3245. */
  3246. Vector3.prototype.normalizeToNew = function () {
  3247. var normalized = new Vector3(0, 0, 0);
  3248. this.normalizeToRef(normalized);
  3249. return normalized;
  3250. };
  3251. /**
  3252. * Normalize the current Vector3 to the reference
  3253. * @param reference define the Vector3 to update
  3254. * @returns the updated Vector3
  3255. */
  3256. Vector3.prototype.normalizeToRef = function (reference) {
  3257. var len = this.length();
  3258. if (len === 0 || len === 1.0) {
  3259. reference.set(this.x, this.y, this.z);
  3260. return reference;
  3261. }
  3262. var scale = 1.0 / len;
  3263. this.scaleToRef(scale, reference);
  3264. return reference;
  3265. };
  3266. /**
  3267. * Creates a new Vector3 copied from the current Vector3
  3268. * @returns the new Vector3
  3269. */
  3270. Vector3.prototype.clone = function () {
  3271. return new Vector3(this.x, this.y, this.z);
  3272. };
  3273. /**
  3274. * Copies the given vector coordinates to the current Vector3 ones
  3275. * @param source defines the source Vector3
  3276. * @returns the current updated Vector3
  3277. */
  3278. Vector3.prototype.copyFrom = function (source) {
  3279. this.x = source.x;
  3280. this.y = source.y;
  3281. this.z = source.z;
  3282. return this;
  3283. };
  3284. /**
  3285. * Copies the given floats to the current Vector3 coordinates
  3286. * @param x defines the x coordinate of the operand
  3287. * @param y defines the y coordinate of the operand
  3288. * @param z defines the z coordinate of the operand
  3289. * @returns the current updated Vector3
  3290. */
  3291. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3292. this.x = x;
  3293. this.y = y;
  3294. this.z = z;
  3295. return this;
  3296. };
  3297. /**
  3298. * Copies the given floats to the current Vector3 coordinates
  3299. * @param x defines the x coordinate of the operand
  3300. * @param y defines the y coordinate of the operand
  3301. * @param z defines the z coordinate of the operand
  3302. * @returns the current updated Vector3
  3303. */
  3304. Vector3.prototype.set = function (x, y, z) {
  3305. return this.copyFromFloats(x, y, z);
  3306. };
  3307. // Statics
  3308. /**
  3309. * Get the clip factor between two vectors
  3310. * @param vector0 defines the first operand
  3311. * @param vector1 defines the second operand
  3312. * @param axis defines the axis to use
  3313. * @param size defines the size along the axis
  3314. * @returns the clip factor
  3315. */
  3316. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3317. var d0 = Vector3.Dot(vector0, axis) - size;
  3318. var d1 = Vector3.Dot(vector1, axis) - size;
  3319. var s = d0 / (d0 - d1);
  3320. return s;
  3321. };
  3322. /**
  3323. * Get angle between two vectors
  3324. * @param vector0 angle between vector0 and vector1
  3325. * @param vector1 angle between vector0 and vector1
  3326. * @param normal direction of the normal
  3327. * @return the angle between vector0 and vector1
  3328. */
  3329. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3330. var v0 = vector0.clone().normalize();
  3331. var v1 = vector1.clone().normalize();
  3332. var dot = Vector3.Dot(v0, v1);
  3333. var n = Vector3.Cross(v0, v1);
  3334. if (Vector3.Dot(n, normal) > 0) {
  3335. return Math.acos(dot);
  3336. }
  3337. return -Math.acos(dot);
  3338. };
  3339. /**
  3340. * Returns a new Vector3 set from the index "offset" of the given array
  3341. * @param array defines the source array
  3342. * @param offset defines the offset in the source array
  3343. * @returns the new Vector3
  3344. */
  3345. Vector3.FromArray = function (array, offset) {
  3346. if (!offset) {
  3347. offset = 0;
  3348. }
  3349. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3350. };
  3351. /**
  3352. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3353. * This function is deprecated. Use FromArray instead
  3354. * @param array defines the source array
  3355. * @param offset defines the offset in the source array
  3356. * @returns the new Vector3
  3357. */
  3358. Vector3.FromFloatArray = function (array, offset) {
  3359. return Vector3.FromArray(array, offset);
  3360. };
  3361. /**
  3362. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3363. * @param array defines the source array
  3364. * @param offset defines the offset in the source array
  3365. * @param result defines the Vector3 where to store the result
  3366. */
  3367. Vector3.FromArrayToRef = function (array, offset, result) {
  3368. result.x = array[offset];
  3369. result.y = array[offset + 1];
  3370. result.z = array[offset + 2];
  3371. };
  3372. /**
  3373. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3374. * This function is deprecated. Use FromArrayToRef instead.
  3375. * @param array defines the source array
  3376. * @param offset defines the offset in the source array
  3377. * @param result defines the Vector3 where to store the result
  3378. */
  3379. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3380. return Vector3.FromArrayToRef(array, offset, result);
  3381. };
  3382. /**
  3383. * Sets the given vector "result" with the given floats.
  3384. * @param x defines the x coordinate of the source
  3385. * @param y defines the y coordinate of the source
  3386. * @param z defines the z coordinate of the source
  3387. * @param result defines the Vector3 where to store the result
  3388. */
  3389. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3390. result.x = x;
  3391. result.y = y;
  3392. result.z = z;
  3393. };
  3394. /**
  3395. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3396. * @returns a new empty Vector3
  3397. */
  3398. Vector3.Zero = function () {
  3399. return new Vector3(0.0, 0.0, 0.0);
  3400. };
  3401. /**
  3402. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3403. * @returns a new unit Vector3
  3404. */
  3405. Vector3.One = function () {
  3406. return new Vector3(1.0, 1.0, 1.0);
  3407. };
  3408. /**
  3409. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3410. * @returns a new up Vector3
  3411. */
  3412. Vector3.Up = function () {
  3413. return new Vector3(0.0, 1.0, 0.0);
  3414. };
  3415. /**
  3416. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3417. * @returns a new forward Vector3
  3418. */
  3419. Vector3.Forward = function () {
  3420. return new Vector3(0.0, 0.0, 1.0);
  3421. };
  3422. /**
  3423. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3424. * @returns a new right Vector3
  3425. */
  3426. Vector3.Right = function () {
  3427. return new Vector3(1.0, 0.0, 0.0);
  3428. };
  3429. /**
  3430. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3431. * @returns a new left Vector3
  3432. */
  3433. Vector3.Left = function () {
  3434. return new Vector3(-1.0, 0.0, 0.0);
  3435. };
  3436. /**
  3437. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3438. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3439. * @param vector defines the Vector3 to transform
  3440. * @param transformation defines the transformation matrix
  3441. * @returns the transformed Vector3
  3442. */
  3443. Vector3.TransformCoordinates = function (vector, transformation) {
  3444. var result = Vector3.Zero();
  3445. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3446. return result;
  3447. };
  3448. /**
  3449. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3450. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3451. * @param vector defines the Vector3 to transform
  3452. * @param transformation defines the transformation matrix
  3453. * @param result defines the Vector3 where to store the result
  3454. */
  3455. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3456. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3457. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3458. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3459. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3460. result.x = x / w;
  3461. result.y = y / w;
  3462. result.z = z / w;
  3463. };
  3464. /**
  3465. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3466. * This method computes tranformed coordinates only, not transformed direction vectors
  3467. * @param x define the x coordinate of the source vector
  3468. * @param y define the y coordinate of the source vector
  3469. * @param z define the z coordinate of the source vector
  3470. * @param transformation defines the transformation matrix
  3471. * @param result defines the Vector3 where to store the result
  3472. */
  3473. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3474. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3475. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3476. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3477. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3478. result.x = rx / rw;
  3479. result.y = ry / rw;
  3480. result.z = rz / rw;
  3481. };
  3482. /**
  3483. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3484. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3485. * @param vector defines the Vector3 to transform
  3486. * @param transformation defines the transformation matrix
  3487. * @returns the new Vector3
  3488. */
  3489. Vector3.TransformNormal = function (vector, transformation) {
  3490. var result = Vector3.Zero();
  3491. Vector3.TransformNormalToRef(vector, transformation, result);
  3492. return result;
  3493. };
  3494. /**
  3495. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3496. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3497. * @param vector defines the Vector3 to transform
  3498. * @param transformation defines the transformation matrix
  3499. * @param result defines the Vector3 where to store the result
  3500. */
  3501. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3502. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3503. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3504. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3505. result.x = x;
  3506. result.y = y;
  3507. result.z = z;
  3508. };
  3509. /**
  3510. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3511. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3512. * @param x define the x coordinate of the source vector
  3513. * @param y define the y coordinate of the source vector
  3514. * @param z define the z coordinate of the source vector
  3515. * @param transformation defines the transformation matrix
  3516. * @param result defines the Vector3 where to store the result
  3517. */
  3518. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3519. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3520. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3521. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3522. };
  3523. /**
  3524. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3525. * @param value1 defines the first control point
  3526. * @param value2 defines the second control point
  3527. * @param value3 defines the third control point
  3528. * @param value4 defines the fourth control point
  3529. * @param amount defines the amount on the spline to use
  3530. * @returns the new Vector3
  3531. */
  3532. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3533. var squared = amount * amount;
  3534. var cubed = amount * squared;
  3535. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3536. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3537. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3538. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3539. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3540. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3541. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3542. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3543. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3544. return new Vector3(x, y, z);
  3545. };
  3546. /**
  3547. * 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"
  3548. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3549. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3550. * @param value defines the current value
  3551. * @param min defines the lower range value
  3552. * @param max defines the upper range value
  3553. * @returns the new Vector3
  3554. */
  3555. Vector3.Clamp = function (value, min, max) {
  3556. var x = value.x;
  3557. x = (x > max.x) ? max.x : x;
  3558. x = (x < min.x) ? min.x : x;
  3559. var y = value.y;
  3560. y = (y > max.y) ? max.y : y;
  3561. y = (y < min.y) ? min.y : y;
  3562. var z = value.z;
  3563. z = (z > max.z) ? max.z : z;
  3564. z = (z < min.z) ? min.z : z;
  3565. return new Vector3(x, y, z);
  3566. };
  3567. /**
  3568. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3569. * @param value1 defines the first control point
  3570. * @param tangent1 defines the first tangent vector
  3571. * @param value2 defines the second control point
  3572. * @param tangent2 defines the second tangent vector
  3573. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3574. * @returns the new Vector3
  3575. */
  3576. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3577. var squared = amount * amount;
  3578. var cubed = amount * squared;
  3579. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3580. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3581. var part3 = (cubed - (2.0 * squared)) + amount;
  3582. var part4 = cubed - squared;
  3583. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3584. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3585. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3586. return new Vector3(x, y, z);
  3587. };
  3588. /**
  3589. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3590. * @param start defines the start value
  3591. * @param end defines the end value
  3592. * @param amount max defines amount between both (between 0 and 1)
  3593. * @returns the new Vector3
  3594. */
  3595. Vector3.Lerp = function (start, end, amount) {
  3596. var result = new Vector3(0, 0, 0);
  3597. Vector3.LerpToRef(start, end, amount, result);
  3598. return result;
  3599. };
  3600. /**
  3601. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3602. * @param start defines the start value
  3603. * @param end defines the end value
  3604. * @param amount max defines amount between both (between 0 and 1)
  3605. * @param result defines the Vector3 where to store the result
  3606. */
  3607. Vector3.LerpToRef = function (start, end, amount, result) {
  3608. result.x = start.x + ((end.x - start.x) * amount);
  3609. result.y = start.y + ((end.y - start.y) * amount);
  3610. result.z = start.z + ((end.z - start.z) * amount);
  3611. };
  3612. /**
  3613. * Returns the dot product (float) between the vectors "left" and "right"
  3614. * @param left defines the left operand
  3615. * @param right defines the right operand
  3616. * @returns the dot product
  3617. */
  3618. Vector3.Dot = function (left, right) {
  3619. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3620. };
  3621. /**
  3622. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3623. * The cross product is then orthogonal to both "left" and "right"
  3624. * @param left defines the left operand
  3625. * @param right defines the right operand
  3626. * @returns the cross product
  3627. */
  3628. Vector3.Cross = function (left, right) {
  3629. var result = Vector3.Zero();
  3630. Vector3.CrossToRef(left, right, result);
  3631. return result;
  3632. };
  3633. /**
  3634. * Sets the given vector "result" with the cross product of "left" and "right"
  3635. * The cross product is then orthogonal to both "left" and "right"
  3636. * @param left defines the left operand
  3637. * @param right defines the right operand
  3638. * @param result defines the Vector3 where to store the result
  3639. */
  3640. Vector3.CrossToRef = function (left, right, result) {
  3641. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3642. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3643. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3644. result.copyFrom(MathTmp.Vector3[0]);
  3645. };
  3646. /**
  3647. * Returns a new Vector3 as the normalization of the given vector
  3648. * @param vector defines the Vector3 to normalize
  3649. * @returns the new Vector3
  3650. */
  3651. Vector3.Normalize = function (vector) {
  3652. var result = Vector3.Zero();
  3653. Vector3.NormalizeToRef(vector, result);
  3654. return result;
  3655. };
  3656. /**
  3657. * Sets the given vector "result" with the normalization of the given first vector
  3658. * @param vector defines the Vector3 to normalize
  3659. * @param result defines the Vector3 where to store the result
  3660. */
  3661. Vector3.NormalizeToRef = function (vector, result) {
  3662. result.copyFrom(vector);
  3663. result.normalize();
  3664. };
  3665. /**
  3666. * Project a Vector3 onto screen space
  3667. * @param vector defines the Vector3 to project
  3668. * @param world defines the world matrix to use
  3669. * @param transform defines the transform (view x projection) matrix to use
  3670. * @param viewport defines the screen viewport to use
  3671. * @returns the new Vector3
  3672. */
  3673. Vector3.Project = function (vector, world, transform, viewport) {
  3674. var cw = viewport.width;
  3675. var ch = viewport.height;
  3676. var cx = viewport.x;
  3677. var cy = viewport.y;
  3678. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3679. 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);
  3680. var matrix = MathTmp.Matrix[0];
  3681. world.multiplyToRef(transform, matrix);
  3682. matrix.multiplyToRef(viewportMatrix, matrix);
  3683. return Vector3.TransformCoordinates(vector, matrix);
  3684. };
  3685. /**
  3686. * Unproject from screen space to object space
  3687. * @param source defines the screen space Vector3 to use
  3688. * @param viewportWidth defines the current width of the viewport
  3689. * @param viewportHeight defines the current height of the viewport
  3690. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3691. * @param transform defines the transform (view x projection) matrix to use
  3692. * @returns the new Vector3
  3693. */
  3694. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3695. var matrix = MathTmp.Matrix[0];
  3696. world.multiplyToRef(transform, matrix);
  3697. matrix.invert();
  3698. source.x = source.x / viewportWidth * 2 - 1;
  3699. source.y = -(source.y / viewportHeight * 2 - 1);
  3700. var vector = Vector3.TransformCoordinates(source, matrix);
  3701. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3702. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3703. vector = vector.scale(1.0 / num);
  3704. }
  3705. return vector;
  3706. };
  3707. /**
  3708. * Unproject from screen space to object space
  3709. * @param source defines the screen space Vector3 to use
  3710. * @param viewportWidth defines the current width of the viewport
  3711. * @param viewportHeight defines the current height of the viewport
  3712. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3713. * @param view defines the view matrix to use
  3714. * @param projection defines the projection matrix to use
  3715. * @returns the new Vector3
  3716. */
  3717. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3718. var result = Vector3.Zero();
  3719. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3720. return result;
  3721. };
  3722. /**
  3723. * Unproject from screen space to object space
  3724. * @param source defines the screen space Vector3 to use
  3725. * @param viewportWidth defines the current width of the viewport
  3726. * @param viewportHeight defines the current height of the viewport
  3727. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3728. * @param view defines the view matrix to use
  3729. * @param projection defines the projection matrix to use
  3730. * @param result defines the Vector3 where to store the result
  3731. */
  3732. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3733. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3734. };
  3735. /**
  3736. * Unproject from screen space to object space
  3737. * @param sourceX defines the screen space x coordinate to use
  3738. * @param sourceY defines the screen space y coordinate to use
  3739. * @param sourceZ defines the screen space z coordinate to use
  3740. * @param viewportWidth defines the current width of the viewport
  3741. * @param viewportHeight defines the current height of the viewport
  3742. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3743. * @param view defines the view matrix to use
  3744. * @param projection defines the projection matrix to use
  3745. * @param result defines the Vector3 where to store the result
  3746. */
  3747. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3748. var matrix = MathTmp.Matrix[0];
  3749. world.multiplyToRef(view, matrix);
  3750. matrix.multiplyToRef(projection, matrix);
  3751. matrix.invert();
  3752. var screenSource = MathTmp.Vector3[0];
  3753. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3754. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3755. screenSource.z = 2 * sourceZ - 1.0;
  3756. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3757. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3758. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3759. result.scaleInPlace(1.0 / num);
  3760. }
  3761. };
  3762. /**
  3763. * Gets the minimal coordinate values between two Vector3
  3764. * @param left defines the first operand
  3765. * @param right defines the second operand
  3766. * @returns the new Vector3
  3767. */
  3768. Vector3.Minimize = function (left, right) {
  3769. var min = left.clone();
  3770. min.minimizeInPlace(right);
  3771. return min;
  3772. };
  3773. /**
  3774. * Gets the maximal coordinate values between two Vector3
  3775. * @param left defines the first operand
  3776. * @param right defines the second operand
  3777. * @returns the new Vector3
  3778. */
  3779. Vector3.Maximize = function (left, right) {
  3780. var max = left.clone();
  3781. max.maximizeInPlace(right);
  3782. return max;
  3783. };
  3784. /**
  3785. * Returns the distance between the vectors "value1" and "value2"
  3786. * @param value1 defines the first operand
  3787. * @param value2 defines the second operand
  3788. * @returns the distance
  3789. */
  3790. Vector3.Distance = function (value1, value2) {
  3791. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3792. };
  3793. /**
  3794. * Returns the squared distance between the vectors "value1" and "value2"
  3795. * @param value1 defines the first operand
  3796. * @param value2 defines the second operand
  3797. * @returns the squared distance
  3798. */
  3799. Vector3.DistanceSquared = function (value1, value2) {
  3800. var x = value1.x - value2.x;
  3801. var y = value1.y - value2.y;
  3802. var z = value1.z - value2.z;
  3803. return (x * x) + (y * y) + (z * z);
  3804. };
  3805. /**
  3806. * Returns a new Vector3 located at the center between "value1" and "value2"
  3807. * @param value1 defines the first operand
  3808. * @param value2 defines the second operand
  3809. * @returns the new Vector3
  3810. */
  3811. Vector3.Center = function (value1, value2) {
  3812. var center = value1.add(value2);
  3813. center.scaleInPlace(0.5);
  3814. return center;
  3815. };
  3816. /**
  3817. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3818. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3819. * to something in order to rotate it from its local system to the given target system
  3820. * Note: axis1, axis2 and axis3 are normalized during this operation
  3821. * @param axis1 defines the first axis
  3822. * @param axis2 defines the second axis
  3823. * @param axis3 defines the third axis
  3824. * @returns a new Vector3
  3825. */
  3826. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3827. var rotation = Vector3.Zero();
  3828. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3829. return rotation;
  3830. };
  3831. /**
  3832. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3833. * @param axis1 defines the first axis
  3834. * @param axis2 defines the second axis
  3835. * @param axis3 defines the third axis
  3836. * @param ref defines the Vector3 where to store the result
  3837. */
  3838. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3839. var quat = MathTmp.Quaternion[0];
  3840. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3841. quat.toEulerAnglesToRef(ref);
  3842. };
  3843. return Vector3;
  3844. }());
  3845. BABYLON.Vector3 = Vector3;
  3846. //Vector4 class created for EulerAngle class conversion to Quaternion
  3847. var Vector4 = /** @class */ (function () {
  3848. /**
  3849. * Creates a Vector4 object from the given floats.
  3850. */
  3851. function Vector4(x, y, z, w) {
  3852. this.x = x;
  3853. this.y = y;
  3854. this.z = z;
  3855. this.w = w;
  3856. }
  3857. /**
  3858. * Returns the string with the Vector4 coordinates.
  3859. */
  3860. Vector4.prototype.toString = function () {
  3861. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3862. };
  3863. /**
  3864. * Returns the string "Vector4".
  3865. */
  3866. Vector4.prototype.getClassName = function () {
  3867. return "Vector4";
  3868. };
  3869. /**
  3870. * Returns the Vector4 hash code.
  3871. */
  3872. Vector4.prototype.getHashCode = function () {
  3873. var hash = this.x || 0;
  3874. hash = (hash * 397) ^ (this.y || 0);
  3875. hash = (hash * 397) ^ (this.z || 0);
  3876. hash = (hash * 397) ^ (this.w || 0);
  3877. return hash;
  3878. };
  3879. // Operators
  3880. /**
  3881. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3882. */
  3883. Vector4.prototype.asArray = function () {
  3884. var result = new Array();
  3885. this.toArray(result, 0);
  3886. return result;
  3887. };
  3888. /**
  3889. * Populates the given array from the given index with the Vector4 coordinates.
  3890. * Returns the Vector4.
  3891. */
  3892. Vector4.prototype.toArray = function (array, index) {
  3893. if (index === undefined) {
  3894. index = 0;
  3895. }
  3896. array[index] = this.x;
  3897. array[index + 1] = this.y;
  3898. array[index + 2] = this.z;
  3899. array[index + 3] = this.w;
  3900. return this;
  3901. };
  3902. /**
  3903. * Adds the given vector to the current Vector4.
  3904. * Returns the updated Vector4.
  3905. */
  3906. Vector4.prototype.addInPlace = function (otherVector) {
  3907. this.x += otherVector.x;
  3908. this.y += otherVector.y;
  3909. this.z += otherVector.z;
  3910. this.w += otherVector.w;
  3911. return this;
  3912. };
  3913. /**
  3914. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3915. */
  3916. Vector4.prototype.add = function (otherVector) {
  3917. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3918. };
  3919. /**
  3920. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3921. * Returns the current Vector4.
  3922. */
  3923. Vector4.prototype.addToRef = function (otherVector, result) {
  3924. result.x = this.x + otherVector.x;
  3925. result.y = this.y + otherVector.y;
  3926. result.z = this.z + otherVector.z;
  3927. result.w = this.w + otherVector.w;
  3928. return this;
  3929. };
  3930. /**
  3931. * Subtract in place the given vector from the current Vector4.
  3932. * Returns the updated Vector4.
  3933. */
  3934. Vector4.prototype.subtractInPlace = function (otherVector) {
  3935. this.x -= otherVector.x;
  3936. this.y -= otherVector.y;
  3937. this.z -= otherVector.z;
  3938. this.w -= otherVector.w;
  3939. return this;
  3940. };
  3941. /**
  3942. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3943. */
  3944. Vector4.prototype.subtract = function (otherVector) {
  3945. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3946. };
  3947. /**
  3948. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3949. * Returns the current Vector4.
  3950. */
  3951. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3952. result.x = this.x - otherVector.x;
  3953. result.y = this.y - otherVector.y;
  3954. result.z = this.z - otherVector.z;
  3955. result.w = this.w - otherVector.w;
  3956. return this;
  3957. };
  3958. /**
  3959. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3960. */
  3961. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3962. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3963. };
  3964. /**
  3965. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3966. * Returns the current Vector4.
  3967. */
  3968. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3969. result.x = this.x - x;
  3970. result.y = this.y - y;
  3971. result.z = this.z - z;
  3972. result.w = this.w - w;
  3973. return this;
  3974. };
  3975. /**
  3976. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3977. */
  3978. Vector4.prototype.negate = function () {
  3979. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3980. };
  3981. /**
  3982. * Multiplies the current Vector4 coordinates by scale (float).
  3983. * Returns the updated Vector4.
  3984. */
  3985. Vector4.prototype.scaleInPlace = function (scale) {
  3986. this.x *= scale;
  3987. this.y *= scale;
  3988. this.z *= scale;
  3989. this.w *= scale;
  3990. return this;
  3991. };
  3992. /**
  3993. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3994. */
  3995. Vector4.prototype.scale = function (scale) {
  3996. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3997. };
  3998. /**
  3999. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4000. * Returns the current Vector4.
  4001. */
  4002. Vector4.prototype.scaleToRef = function (scale, result) {
  4003. result.x = this.x * scale;
  4004. result.y = this.y * scale;
  4005. result.z = this.z * scale;
  4006. result.w = this.w * scale;
  4007. return this;
  4008. };
  4009. /**
  4010. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4011. * @param scale defines the scale factor
  4012. * @param result defines the Vector4 object where to store the result
  4013. * @returns the unmodified current Vector4
  4014. */
  4015. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4016. result.x += this.x * scale;
  4017. result.y += this.y * scale;
  4018. result.z += this.z * scale;
  4019. result.w += this.w * scale;
  4020. return this;
  4021. };
  4022. /**
  4023. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4024. */
  4025. Vector4.prototype.equals = function (otherVector) {
  4026. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4027. };
  4028. /**
  4029. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4030. */
  4031. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4032. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4033. return otherVector
  4034. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4035. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4036. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4037. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4038. };
  4039. /**
  4040. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4041. */
  4042. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4043. return this.x === x && this.y === y && this.z === z && this.w === w;
  4044. };
  4045. /**
  4046. * Multiplies in place the current Vector4 by the given one.
  4047. * Returns the updated Vector4.
  4048. */
  4049. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4050. this.x *= otherVector.x;
  4051. this.y *= otherVector.y;
  4052. this.z *= otherVector.z;
  4053. this.w *= otherVector.w;
  4054. return this;
  4055. };
  4056. /**
  4057. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4058. */
  4059. Vector4.prototype.multiply = function (otherVector) {
  4060. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4061. };
  4062. /**
  4063. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4064. * Returns the current Vector4.
  4065. */
  4066. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4067. result.x = this.x * otherVector.x;
  4068. result.y = this.y * otherVector.y;
  4069. result.z = this.z * otherVector.z;
  4070. result.w = this.w * otherVector.w;
  4071. return this;
  4072. };
  4073. /**
  4074. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4075. */
  4076. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4077. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4078. };
  4079. /**
  4080. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4081. */
  4082. Vector4.prototype.divide = function (otherVector) {
  4083. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4084. };
  4085. /**
  4086. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4087. * Returns the current Vector4.
  4088. */
  4089. Vector4.prototype.divideToRef = function (otherVector, result) {
  4090. result.x = this.x / otherVector.x;
  4091. result.y = this.y / otherVector.y;
  4092. result.z = this.z / otherVector.z;
  4093. result.w = this.w / otherVector.w;
  4094. return this;
  4095. };
  4096. /**
  4097. * Divides the current Vector3 coordinates by the given ones.
  4098. * @returns the updated Vector3.
  4099. */
  4100. Vector4.prototype.divideInPlace = function (otherVector) {
  4101. return this.divideToRef(otherVector, this);
  4102. };
  4103. /**
  4104. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4105. * @param other defines the second operand
  4106. * @returns the current updated Vector4
  4107. */
  4108. Vector4.prototype.minimizeInPlace = function (other) {
  4109. if (other.x < this.x)
  4110. this.x = other.x;
  4111. if (other.y < this.y)
  4112. this.y = other.y;
  4113. if (other.z < this.z)
  4114. this.z = other.z;
  4115. if (other.w < this.w)
  4116. this.w = other.w;
  4117. return this;
  4118. };
  4119. /**
  4120. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4121. * @param other defines the second operand
  4122. * @returns the current updated Vector4
  4123. */
  4124. Vector4.prototype.maximizeInPlace = function (other) {
  4125. if (other.x > this.x)
  4126. this.x = other.x;
  4127. if (other.y > this.y)
  4128. this.y = other.y;
  4129. if (other.z > this.z)
  4130. this.z = other.z;
  4131. if (other.w > this.w)
  4132. this.w = other.w;
  4133. return this;
  4134. };
  4135. // Properties
  4136. /**
  4137. * Returns the Vector4 length (float).
  4138. */
  4139. Vector4.prototype.length = function () {
  4140. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4141. };
  4142. /**
  4143. * Returns the Vector4 squared length (float).
  4144. */
  4145. Vector4.prototype.lengthSquared = function () {
  4146. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4147. };
  4148. // Methods
  4149. /**
  4150. * Normalizes in place the Vector4.
  4151. * Returns the updated Vector4.
  4152. */
  4153. Vector4.prototype.normalize = function () {
  4154. var len = this.length();
  4155. if (len === 0)
  4156. return this;
  4157. var num = 1.0 / len;
  4158. this.x *= num;
  4159. this.y *= num;
  4160. this.z *= num;
  4161. this.w *= num;
  4162. return this;
  4163. };
  4164. /**
  4165. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4166. */
  4167. Vector4.prototype.toVector3 = function () {
  4168. return new Vector3(this.x, this.y, this.z);
  4169. };
  4170. /**
  4171. * Returns a new Vector4 copied from the current one.
  4172. */
  4173. Vector4.prototype.clone = function () {
  4174. return new Vector4(this.x, this.y, this.z, this.w);
  4175. };
  4176. /**
  4177. * Updates the current Vector4 with the given one coordinates.
  4178. * Returns the updated Vector4.
  4179. */
  4180. Vector4.prototype.copyFrom = function (source) {
  4181. this.x = source.x;
  4182. this.y = source.y;
  4183. this.z = source.z;
  4184. this.w = source.w;
  4185. return this;
  4186. };
  4187. /**
  4188. * Updates the current Vector4 coordinates with the given floats.
  4189. * Returns the updated Vector4.
  4190. */
  4191. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4192. this.x = x;
  4193. this.y = y;
  4194. this.z = z;
  4195. this.w = w;
  4196. return this;
  4197. };
  4198. /**
  4199. * Updates the current Vector4 coordinates with the given floats.
  4200. * Returns the updated Vector4.
  4201. */
  4202. Vector4.prototype.set = function (x, y, z, w) {
  4203. return this.copyFromFloats(x, y, z, w);
  4204. };
  4205. // Statics
  4206. /**
  4207. * Returns a new Vector4 set from the starting index of the given array.
  4208. */
  4209. Vector4.FromArray = function (array, offset) {
  4210. if (!offset) {
  4211. offset = 0;
  4212. }
  4213. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4214. };
  4215. /**
  4216. * Updates the given vector "result" from the starting index of the given array.
  4217. */
  4218. Vector4.FromArrayToRef = function (array, offset, result) {
  4219. result.x = array[offset];
  4220. result.y = array[offset + 1];
  4221. result.z = array[offset + 2];
  4222. result.w = array[offset + 3];
  4223. };
  4224. /**
  4225. * Updates the given vector "result" from the starting index of the given Float32Array.
  4226. */
  4227. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4228. Vector4.FromArrayToRef(array, offset, result);
  4229. };
  4230. /**
  4231. * Updates the given vector "result" coordinates from the given floats.
  4232. */
  4233. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4234. result.x = x;
  4235. result.y = y;
  4236. result.z = z;
  4237. result.w = w;
  4238. };
  4239. /**
  4240. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4241. */
  4242. Vector4.Zero = function () {
  4243. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4244. };
  4245. /**
  4246. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4247. */
  4248. Vector4.One = function () {
  4249. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4250. };
  4251. /**
  4252. * Returns a new normalized Vector4 from the given one.
  4253. */
  4254. Vector4.Normalize = function (vector) {
  4255. var result = Vector4.Zero();
  4256. Vector4.NormalizeToRef(vector, result);
  4257. return result;
  4258. };
  4259. /**
  4260. * Updates the given vector "result" from the normalization of the given one.
  4261. */
  4262. Vector4.NormalizeToRef = function (vector, result) {
  4263. result.copyFrom(vector);
  4264. result.normalize();
  4265. };
  4266. Vector4.Minimize = function (left, right) {
  4267. var min = left.clone();
  4268. min.minimizeInPlace(right);
  4269. return min;
  4270. };
  4271. Vector4.Maximize = function (left, right) {
  4272. var max = left.clone();
  4273. max.maximizeInPlace(right);
  4274. return max;
  4275. };
  4276. /**
  4277. * Returns the distance (float) between the vectors "value1" and "value2".
  4278. */
  4279. Vector4.Distance = function (value1, value2) {
  4280. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4281. };
  4282. /**
  4283. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4284. */
  4285. Vector4.DistanceSquared = function (value1, value2) {
  4286. var x = value1.x - value2.x;
  4287. var y = value1.y - value2.y;
  4288. var z = value1.z - value2.z;
  4289. var w = value1.w - value2.w;
  4290. return (x * x) + (y * y) + (z * z) + (w * w);
  4291. };
  4292. /**
  4293. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4294. */
  4295. Vector4.Center = function (value1, value2) {
  4296. var center = value1.add(value2);
  4297. center.scaleInPlace(0.5);
  4298. return center;
  4299. };
  4300. /**
  4301. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4302. * This methods computes transformed normalized direction vectors only.
  4303. */
  4304. Vector4.TransformNormal = function (vector, transformation) {
  4305. var result = Vector4.Zero();
  4306. Vector4.TransformNormalToRef(vector, transformation, result);
  4307. return result;
  4308. };
  4309. /**
  4310. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4311. * This methods computes transformed normalized direction vectors only.
  4312. */
  4313. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4314. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4315. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4316. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4317. result.x = x;
  4318. result.y = y;
  4319. result.z = z;
  4320. result.w = vector.w;
  4321. };
  4322. /**
  4323. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4324. * This methods computes transformed normalized direction vectors only.
  4325. */
  4326. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4327. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4328. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4329. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4330. result.w = w;
  4331. };
  4332. return Vector4;
  4333. }());
  4334. BABYLON.Vector4 = Vector4;
  4335. var Size = /** @class */ (function () {
  4336. /**
  4337. * Creates a Size object from the given width and height (floats).
  4338. */
  4339. function Size(width, height) {
  4340. this.width = width;
  4341. this.height = height;
  4342. }
  4343. // Returns a string with the Size width and height.
  4344. Size.prototype.toString = function () {
  4345. return "{W: " + this.width + ", H: " + this.height + "}";
  4346. };
  4347. /**
  4348. * Returns the string "Size"
  4349. */
  4350. Size.prototype.getClassName = function () {
  4351. return "Size";
  4352. };
  4353. /**
  4354. * Returns the Size hash code.
  4355. */
  4356. Size.prototype.getHashCode = function () {
  4357. var hash = this.width || 0;
  4358. hash = (hash * 397) ^ (this.height || 0);
  4359. return hash;
  4360. };
  4361. /**
  4362. * Updates the current size from the given one.
  4363. * Returns the updated Size.
  4364. */
  4365. Size.prototype.copyFrom = function (src) {
  4366. this.width = src.width;
  4367. this.height = src.height;
  4368. };
  4369. /**
  4370. * Updates in place the current Size from the given floats.
  4371. * Returns the updated Size.
  4372. */
  4373. Size.prototype.copyFromFloats = function (width, height) {
  4374. this.width = width;
  4375. this.height = height;
  4376. return this;
  4377. };
  4378. /**
  4379. * Updates in place the current Size from the given floats.
  4380. * Returns the updated Size.
  4381. */
  4382. Size.prototype.set = function (width, height) {
  4383. return this.copyFromFloats(width, height);
  4384. };
  4385. /**
  4386. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4387. */
  4388. Size.prototype.multiplyByFloats = function (w, h) {
  4389. return new Size(this.width * w, this.height * h);
  4390. };
  4391. /**
  4392. * Returns a new Size copied from the given one.
  4393. */
  4394. Size.prototype.clone = function () {
  4395. return new Size(this.width, this.height);
  4396. };
  4397. /**
  4398. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4399. */
  4400. Size.prototype.equals = function (other) {
  4401. if (!other) {
  4402. return false;
  4403. }
  4404. return (this.width === other.width) && (this.height === other.height);
  4405. };
  4406. Object.defineProperty(Size.prototype, "surface", {
  4407. /**
  4408. * Returns the surface of the Size : width * height (float).
  4409. */
  4410. get: function () {
  4411. return this.width * this.height;
  4412. },
  4413. enumerable: true,
  4414. configurable: true
  4415. });
  4416. /**
  4417. * Returns a new Size set to (0.0, 0.0)
  4418. */
  4419. Size.Zero = function () {
  4420. return new Size(0.0, 0.0);
  4421. };
  4422. /**
  4423. * Returns a new Size set as the addition result of the current Size and the given one.
  4424. */
  4425. Size.prototype.add = function (otherSize) {
  4426. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4427. return r;
  4428. };
  4429. /**
  4430. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4431. */
  4432. Size.prototype.subtract = function (otherSize) {
  4433. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4434. return r;
  4435. };
  4436. /**
  4437. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4438. */
  4439. Size.Lerp = function (start, end, amount) {
  4440. var w = start.width + ((end.width - start.width) * amount);
  4441. var h = start.height + ((end.height - start.height) * amount);
  4442. return new Size(w, h);
  4443. };
  4444. return Size;
  4445. }());
  4446. BABYLON.Size = Size;
  4447. /**
  4448. * Class used to store quaternion data
  4449. * @see https://en.wikipedia.org/wiki/Quaternion
  4450. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4451. */
  4452. var Quaternion = /** @class */ (function () {
  4453. /**
  4454. * Creates a new Quaternion from the given floats
  4455. * @param x defines the first component (0 by default)
  4456. * @param y defines the second component (0 by default)
  4457. * @param z defines the third component (0 by default)
  4458. * @param w defines the fourth component (1.0 by default)
  4459. */
  4460. function Quaternion(
  4461. /** defines the first component (0 by default) */
  4462. x,
  4463. /** defines the second component (0 by default) */
  4464. y,
  4465. /** defines the third component (0 by default) */
  4466. z,
  4467. /** defines the fourth component (1.0 by default) */
  4468. w) {
  4469. if (x === void 0) { x = 0.0; }
  4470. if (y === void 0) { y = 0.0; }
  4471. if (z === void 0) { z = 0.0; }
  4472. if (w === void 0) { w = 1.0; }
  4473. this.x = x;
  4474. this.y = y;
  4475. this.z = z;
  4476. this.w = w;
  4477. }
  4478. /**
  4479. * Gets a string representation for the current quaternion
  4480. * @returns a string with the Quaternion coordinates
  4481. */
  4482. Quaternion.prototype.toString = function () {
  4483. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4484. };
  4485. /**
  4486. * Gets the class name of the quaternion
  4487. * @returns the string "Quaternion"
  4488. */
  4489. Quaternion.prototype.getClassName = function () {
  4490. return "Quaternion";
  4491. };
  4492. /**
  4493. * Gets a hash code for this quaternion
  4494. * @returns the quaternion hash code
  4495. */
  4496. Quaternion.prototype.getHashCode = function () {
  4497. var hash = this.x || 0;
  4498. hash = (hash * 397) ^ (this.y || 0);
  4499. hash = (hash * 397) ^ (this.z || 0);
  4500. hash = (hash * 397) ^ (this.w || 0);
  4501. return hash;
  4502. };
  4503. /**
  4504. * Copy the quaternion to an array
  4505. * @returns a new array populated with 4 elements from the quaternion coordinates
  4506. */
  4507. Quaternion.prototype.asArray = function () {
  4508. return [this.x, this.y, this.z, this.w];
  4509. };
  4510. /**
  4511. * Check if two quaternions are equals
  4512. * @param otherQuaternion defines the second operand
  4513. * @return true if the current quaternion and the given one coordinates are strictly equals
  4514. */
  4515. Quaternion.prototype.equals = function (otherQuaternion) {
  4516. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4517. };
  4518. /**
  4519. * Clone the current quaternion
  4520. * @returns a new quaternion copied from the current one
  4521. */
  4522. Quaternion.prototype.clone = function () {
  4523. return new Quaternion(this.x, this.y, this.z, this.w);
  4524. };
  4525. /**
  4526. * Copy a quaternion to the current one
  4527. * @param other defines the other quaternion
  4528. * @returns the updated current quaternion
  4529. */
  4530. Quaternion.prototype.copyFrom = function (other) {
  4531. this.x = other.x;
  4532. this.y = other.y;
  4533. this.z = other.z;
  4534. this.w = other.w;
  4535. return this;
  4536. };
  4537. /**
  4538. * Updates the current quaternion with the given float coordinates
  4539. * @param x defines the x coordinate
  4540. * @param y defines the y coordinate
  4541. * @param z defines the z coordinate
  4542. * @param w defines the w coordinate
  4543. * @returns the updated current quaternion
  4544. */
  4545. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4546. this.x = x;
  4547. this.y = y;
  4548. this.z = z;
  4549. this.w = w;
  4550. return this;
  4551. };
  4552. /**
  4553. * Updates the current quaternion from the given float coordinates
  4554. * @param x defines the x coordinate
  4555. * @param y defines the y coordinate
  4556. * @param z defines the z coordinate
  4557. * @param w defines the w coordinate
  4558. * @returns the updated current quaternion
  4559. */
  4560. Quaternion.prototype.set = function (x, y, z, w) {
  4561. return this.copyFromFloats(x, y, z, w);
  4562. };
  4563. /**
  4564. * Adds two quaternions
  4565. * @param other defines the second operand
  4566. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4567. */
  4568. Quaternion.prototype.add = function (other) {
  4569. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4570. };
  4571. /**
  4572. * Add a quaternion to the current one
  4573. * @param other defines the quaternion to add
  4574. * @returns the current quaternion
  4575. */
  4576. Quaternion.prototype.addInPlace = function (other) {
  4577. this.x += other.x;
  4578. this.y += other.y;
  4579. this.z += other.z;
  4580. this.w += other.w;
  4581. return this;
  4582. };
  4583. /**
  4584. * Subtract two quaternions
  4585. * @param other defines the second operand
  4586. * @returns a new quaternion as the subtraction result of the given one from the current one
  4587. */
  4588. Quaternion.prototype.subtract = function (other) {
  4589. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4590. };
  4591. /**
  4592. * Multiplies the current quaternion by a scale factor
  4593. * @param value defines the scale factor
  4594. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4595. */
  4596. Quaternion.prototype.scale = function (value) {
  4597. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4598. };
  4599. /**
  4600. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4601. * @param scale defines the scale factor
  4602. * @param result defines the Quaternion object where to store the result
  4603. * @returns the unmodified current quaternion
  4604. */
  4605. Quaternion.prototype.scaleToRef = function (scale, result) {
  4606. result.x = this.x * scale;
  4607. result.y = this.y * scale;
  4608. result.z = this.z * scale;
  4609. result.w = this.w * scale;
  4610. return this;
  4611. };
  4612. /**
  4613. * Multiplies in place the current quaternion by a scale factor
  4614. * @param value defines the scale factor
  4615. * @returns the current modified quaternion
  4616. */
  4617. Quaternion.prototype.scaleInPlace = function (value) {
  4618. this.x *= value;
  4619. this.y *= value;
  4620. this.z *= value;
  4621. this.w *= value;
  4622. return this;
  4623. };
  4624. /**
  4625. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4626. * @param scale defines the scale factor
  4627. * @param result defines the Quaternion object where to store the result
  4628. * @returns the unmodified current quaternion
  4629. */
  4630. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4631. result.x += this.x * scale;
  4632. result.y += this.y * scale;
  4633. result.z += this.z * scale;
  4634. result.w += this.w * scale;
  4635. return this;
  4636. };
  4637. /**
  4638. * Multiplies two quaternions
  4639. * @param q1 defines the second operand
  4640. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4641. */
  4642. Quaternion.prototype.multiply = function (q1) {
  4643. var result = new Quaternion(0, 0, 0, 1.0);
  4644. this.multiplyToRef(q1, result);
  4645. return result;
  4646. };
  4647. /**
  4648. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4649. * @param q1 defines the second operand
  4650. * @param result defines the target quaternion
  4651. * @returns the current quaternion
  4652. */
  4653. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4654. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4655. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4656. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4657. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4658. result.copyFromFloats(x, y, z, w);
  4659. return this;
  4660. };
  4661. /**
  4662. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4663. * @param q1 defines the second operand
  4664. * @returns the currentupdated quaternion
  4665. */
  4666. Quaternion.prototype.multiplyInPlace = function (q1) {
  4667. this.multiplyToRef(q1, this);
  4668. return this;
  4669. };
  4670. /**
  4671. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4672. * @param ref defines the target quaternion
  4673. * @returns the current quaternion
  4674. */
  4675. Quaternion.prototype.conjugateToRef = function (ref) {
  4676. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4677. return this;
  4678. };
  4679. /**
  4680. * Conjugates in place (1-q) the current quaternion
  4681. * @returns the current updated quaternion
  4682. */
  4683. Quaternion.prototype.conjugateInPlace = function () {
  4684. this.x *= -1;
  4685. this.y *= -1;
  4686. this.z *= -1;
  4687. return this;
  4688. };
  4689. /**
  4690. * Conjugates in place (1-q) the current quaternion
  4691. * @returns a new quaternion
  4692. */
  4693. Quaternion.prototype.conjugate = function () {
  4694. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4695. return result;
  4696. };
  4697. /**
  4698. * Gets length of current quaternion
  4699. * @returns the quaternion length (float)
  4700. */
  4701. Quaternion.prototype.length = function () {
  4702. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4703. };
  4704. /**
  4705. * Normalize in place the current quaternion
  4706. * @returns the current updated quaternion
  4707. */
  4708. Quaternion.prototype.normalize = function () {
  4709. var length = 1.0 / this.length();
  4710. this.x *= length;
  4711. this.y *= length;
  4712. this.z *= length;
  4713. this.w *= length;
  4714. return this;
  4715. };
  4716. /**
  4717. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4718. * @param order is a reserved parameter and is ignore for now
  4719. * @returns a new Vector3 containing the Euler angles
  4720. */
  4721. Quaternion.prototype.toEulerAngles = function (order) {
  4722. if (order === void 0) { order = "YZX"; }
  4723. var result = Vector3.Zero();
  4724. this.toEulerAnglesToRef(result, order);
  4725. return result;
  4726. };
  4727. /**
  4728. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4729. * @param result defines the vector which will be filled with the Euler angles
  4730. * @param order is a reserved parameter and is ignore for now
  4731. * @returns the current unchanged quaternion
  4732. */
  4733. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4734. if (order === void 0) { order = "YZX"; }
  4735. var qz = this.z;
  4736. var qx = this.x;
  4737. var qy = this.y;
  4738. var qw = this.w;
  4739. var sqw = qw * qw;
  4740. var sqz = qz * qz;
  4741. var sqx = qx * qx;
  4742. var sqy = qy * qy;
  4743. var zAxisY = qy * qz - qx * qw;
  4744. var limit = .4999999;
  4745. if (zAxisY < -limit) {
  4746. result.y = 2 * Math.atan2(qy, qw);
  4747. result.x = Math.PI / 2;
  4748. result.z = 0;
  4749. }
  4750. else if (zAxisY > limit) {
  4751. result.y = 2 * Math.atan2(qy, qw);
  4752. result.x = -Math.PI / 2;
  4753. result.z = 0;
  4754. }
  4755. else {
  4756. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4757. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4758. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4759. }
  4760. return this;
  4761. };
  4762. /**
  4763. * Updates the given rotation matrix with the current quaternion values
  4764. * @param result defines the target matrix
  4765. * @returns the current unchanged quaternion
  4766. */
  4767. Quaternion.prototype.toRotationMatrix = function (result) {
  4768. var xx = this.x * this.x;
  4769. var yy = this.y * this.y;
  4770. var zz = this.z * this.z;
  4771. var xy = this.x * this.y;
  4772. var zw = this.z * this.w;
  4773. var zx = this.z * this.x;
  4774. var yw = this.y * this.w;
  4775. var yz = this.y * this.z;
  4776. var xw = this.x * this.w;
  4777. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4778. result.m[1] = 2.0 * (xy + zw);
  4779. result.m[2] = 2.0 * (zx - yw);
  4780. result.m[3] = 0;
  4781. result.m[4] = 2.0 * (xy - zw);
  4782. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4783. result.m[6] = 2.0 * (yz + xw);
  4784. result.m[7] = 0;
  4785. result.m[8] = 2.0 * (zx + yw);
  4786. result.m[9] = 2.0 * (yz - xw);
  4787. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4788. result.m[11] = 0;
  4789. result.m[12] = 0;
  4790. result.m[13] = 0;
  4791. result.m[14] = 0;
  4792. result.m[15] = 1.0;
  4793. result._markAsUpdated();
  4794. return this;
  4795. };
  4796. /**
  4797. * Updates the current quaternion from the given rotation matrix values
  4798. * @param matrix defines the source matrix
  4799. * @returns the current updated quaternion
  4800. */
  4801. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4802. Quaternion.FromRotationMatrixToRef(matrix, this);
  4803. return this;
  4804. };
  4805. // Statics
  4806. /**
  4807. * Creates a new quaternion from a rotation matrix
  4808. * @param matrix defines the source matrix
  4809. * @returns a new quaternion created from the given rotation matrix values
  4810. */
  4811. Quaternion.FromRotationMatrix = function (matrix) {
  4812. var result = new Quaternion();
  4813. Quaternion.FromRotationMatrixToRef(matrix, result);
  4814. return result;
  4815. };
  4816. /**
  4817. * Updates the given quaternion with the given rotation matrix values
  4818. * @param matrix defines the source matrix
  4819. * @param result defines the target quaternion
  4820. */
  4821. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4822. var data = matrix.m;
  4823. var m11 = data[0], m12 = data[4], m13 = data[8];
  4824. var m21 = data[1], m22 = data[5], m23 = data[9];
  4825. var m31 = data[2], m32 = data[6], m33 = data[10];
  4826. var trace = m11 + m22 + m33;
  4827. var s;
  4828. if (trace > 0) {
  4829. s = 0.5 / Math.sqrt(trace + 1.0);
  4830. result.w = 0.25 / s;
  4831. result.x = (m32 - m23) * s;
  4832. result.y = (m13 - m31) * s;
  4833. result.z = (m21 - m12) * s;
  4834. }
  4835. else if (m11 > m22 && m11 > m33) {
  4836. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4837. result.w = (m32 - m23) / s;
  4838. result.x = 0.25 * s;
  4839. result.y = (m12 + m21) / s;
  4840. result.z = (m13 + m31) / s;
  4841. }
  4842. else if (m22 > m33) {
  4843. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4844. result.w = (m13 - m31) / s;
  4845. result.x = (m12 + m21) / s;
  4846. result.y = 0.25 * s;
  4847. result.z = (m23 + m32) / s;
  4848. }
  4849. else {
  4850. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4851. result.w = (m21 - m12) / s;
  4852. result.x = (m13 + m31) / s;
  4853. result.y = (m23 + m32) / s;
  4854. result.z = 0.25 * s;
  4855. }
  4856. };
  4857. /**
  4858. * Returns the dot product (float) between the quaternions "left" and "right"
  4859. * @param left defines the left operand
  4860. * @param right defines the right operand
  4861. * @returns the dot product
  4862. */
  4863. Quaternion.Dot = function (left, right) {
  4864. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4865. };
  4866. /**
  4867. * Checks if the two quaternions are close to each other
  4868. * @param quat0 defines the first quaternion to check
  4869. * @param quat1 defines the second quaternion to check
  4870. * @returns true if the two quaternions are close to each other
  4871. */
  4872. Quaternion.AreClose = function (quat0, quat1) {
  4873. var dot = Quaternion.Dot(quat0, quat1);
  4874. return dot >= 0;
  4875. };
  4876. /**
  4877. * Creates an empty quaternion
  4878. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4879. */
  4880. Quaternion.Zero = function () {
  4881. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4882. };
  4883. /**
  4884. * Inverse a given quaternion
  4885. * @param q defines the source quaternion
  4886. * @returns a new quaternion as the inverted current quaternion
  4887. */
  4888. Quaternion.Inverse = function (q) {
  4889. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4890. };
  4891. /**
  4892. * Creates an identity quaternion
  4893. * @returns the identity quaternion
  4894. */
  4895. Quaternion.Identity = function () {
  4896. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4897. };
  4898. /**
  4899. * Gets a boolean indicating if the given quaternion is identity
  4900. * @param quaternion defines the quaternion to check
  4901. * @returns true if the quaternion is identity
  4902. */
  4903. Quaternion.IsIdentity = function (quaternion) {
  4904. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4905. };
  4906. /**
  4907. * Creates a quaternion from a rotation around an axis
  4908. * @param axis defines the axis to use
  4909. * @param angle defines the angle to use
  4910. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4911. */
  4912. Quaternion.RotationAxis = function (axis, angle) {
  4913. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4914. };
  4915. /**
  4916. * Creates a rotation around an axis and stores it into the given quaternion
  4917. * @param axis defines the axis to use
  4918. * @param angle defines the angle to use
  4919. * @param result defines the target quaternion
  4920. * @returns the target quaternion
  4921. */
  4922. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4923. var sin = Math.sin(angle / 2);
  4924. axis.normalize();
  4925. result.w = Math.cos(angle / 2);
  4926. result.x = axis.x * sin;
  4927. result.y = axis.y * sin;
  4928. result.z = axis.z * sin;
  4929. return result;
  4930. };
  4931. /**
  4932. * Creates a new quaternion from data stored into an array
  4933. * @param array defines the data source
  4934. * @param offset defines the offset in the source array where the data starts
  4935. * @returns a new quaternion
  4936. */
  4937. Quaternion.FromArray = function (array, offset) {
  4938. if (!offset) {
  4939. offset = 0;
  4940. }
  4941. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4942. };
  4943. /**
  4944. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4945. * @param yaw defines the rotation around Y axis
  4946. * @param pitch defines the rotation around X axis
  4947. * @param roll defines the rotation around Z axis
  4948. * @returns the new quaternion
  4949. */
  4950. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4951. var q = new Quaternion();
  4952. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4953. return q;
  4954. };
  4955. /**
  4956. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4957. * @param yaw defines the rotation around Y axis
  4958. * @param pitch defines the rotation around X axis
  4959. * @param roll defines the rotation around Z axis
  4960. * @param result defines the target quaternion
  4961. */
  4962. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4963. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4964. var halfRoll = roll * 0.5;
  4965. var halfPitch = pitch * 0.5;
  4966. var halfYaw = yaw * 0.5;
  4967. var sinRoll = Math.sin(halfRoll);
  4968. var cosRoll = Math.cos(halfRoll);
  4969. var sinPitch = Math.sin(halfPitch);
  4970. var cosPitch = Math.cos(halfPitch);
  4971. var sinYaw = Math.sin(halfYaw);
  4972. var cosYaw = Math.cos(halfYaw);
  4973. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4974. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4975. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4976. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4977. };
  4978. /**
  4979. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4980. * @param alpha defines the rotation around first axis
  4981. * @param beta defines the rotation around second axis
  4982. * @param gamma defines the rotation around third axis
  4983. * @returns the new quaternion
  4984. */
  4985. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4986. var result = new Quaternion();
  4987. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4988. return result;
  4989. };
  4990. /**
  4991. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4992. * @param alpha defines the rotation around first axis
  4993. * @param beta defines the rotation around second axis
  4994. * @param gamma defines the rotation around third axis
  4995. * @param result defines the target quaternion
  4996. */
  4997. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4998. // Produces a quaternion from Euler angles in the z-x-z orientation
  4999. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5000. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5001. var halfBeta = beta * 0.5;
  5002. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5003. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5004. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5005. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5006. };
  5007. /**
  5008. * 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)
  5009. * @param axis1 defines the first axis
  5010. * @param axis2 defines the second axis
  5011. * @param axis3 defines the third axis
  5012. * @returns the new quaternion
  5013. */
  5014. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5015. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5016. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5017. return quat;
  5018. };
  5019. /**
  5020. * 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
  5021. * @param axis1 defines the first axis
  5022. * @param axis2 defines the second axis
  5023. * @param axis3 defines the third axis
  5024. * @param ref defines the target quaternion
  5025. */
  5026. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5027. var rotMat = MathTmp.Matrix[0];
  5028. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5029. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5030. };
  5031. /**
  5032. * Interpolates between two quaternions
  5033. * @param left defines first quaternion
  5034. * @param right defines second quaternion
  5035. * @param amount defines the gradient to use
  5036. * @returns the new interpolated quaternion
  5037. */
  5038. Quaternion.Slerp = function (left, right, amount) {
  5039. var result = Quaternion.Identity();
  5040. Quaternion.SlerpToRef(left, right, amount, result);
  5041. return result;
  5042. };
  5043. /**
  5044. * Interpolates between two quaternions and stores it into a target quaternion
  5045. * @param left defines first quaternion
  5046. * @param right defines second quaternion
  5047. * @param amount defines the gradient to use
  5048. * @param result defines the target quaternion
  5049. */
  5050. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5051. var num2;
  5052. var num3;
  5053. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5054. var flag = false;
  5055. if (num4 < 0) {
  5056. flag = true;
  5057. num4 = -num4;
  5058. }
  5059. if (num4 > 0.999999) {
  5060. num3 = 1 - amount;
  5061. num2 = flag ? -amount : amount;
  5062. }
  5063. else {
  5064. var num5 = Math.acos(num4);
  5065. var num6 = (1.0 / Math.sin(num5));
  5066. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5067. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5068. }
  5069. result.x = (num3 * left.x) + (num2 * right.x);
  5070. result.y = (num3 * left.y) + (num2 * right.y);
  5071. result.z = (num3 * left.z) + (num2 * right.z);
  5072. result.w = (num3 * left.w) + (num2 * right.w);
  5073. };
  5074. /**
  5075. * Interpolate between two quaternions using Hermite interpolation
  5076. * @param value1 defines first quaternion
  5077. * @param tangent1 defines the incoming tangent
  5078. * @param value2 defines second quaternion
  5079. * @param tangent2 defines the outgoing tangent
  5080. * @param amount defines the target quaternion
  5081. * @returns the new interpolated quaternion
  5082. */
  5083. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5084. var squared = amount * amount;
  5085. var cubed = amount * squared;
  5086. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5087. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5088. var part3 = (cubed - (2.0 * squared)) + amount;
  5089. var part4 = cubed - squared;
  5090. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5091. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5092. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5093. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5094. return new Quaternion(x, y, z, w);
  5095. };
  5096. return Quaternion;
  5097. }());
  5098. BABYLON.Quaternion = Quaternion;
  5099. /**
  5100. * Class used to store matrix data (4x4)
  5101. */
  5102. var Matrix = /** @class */ (function () {
  5103. /**
  5104. * Creates an empty matrix (filled with zeros)
  5105. */
  5106. function Matrix() {
  5107. this._isIdentity = false;
  5108. this._isIdentityDirty = true;
  5109. /**
  5110. * Gets or sets the internal data of the matrix
  5111. */
  5112. this.m = new Float32Array(16);
  5113. this._markAsUpdated();
  5114. }
  5115. /** @hidden */
  5116. Matrix.prototype._markAsUpdated = function () {
  5117. this.updateFlag = Matrix._updateFlagSeed++;
  5118. this._isIdentityDirty = true;
  5119. };
  5120. // Properties
  5121. /**
  5122. * Check if the current matrix is indentity
  5123. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5124. * @returns true is the matrix is the identity matrix
  5125. */
  5126. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5127. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5128. if (this._isIdentityDirty) {
  5129. this._isIdentityDirty = false;
  5130. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5131. this._isIdentity = false;
  5132. }
  5133. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5134. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5135. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5136. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5137. this._isIdentity = false;
  5138. }
  5139. else {
  5140. this._isIdentity = true;
  5141. }
  5142. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5143. this._isIdentity = false;
  5144. }
  5145. }
  5146. return this._isIdentity;
  5147. };
  5148. /**
  5149. * Gets the determinant of the matrix
  5150. * @returns the matrix determinant
  5151. */
  5152. Matrix.prototype.determinant = function () {
  5153. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5154. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5155. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5156. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5157. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5158. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5159. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5160. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5161. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5162. };
  5163. // Methods
  5164. /**
  5165. * Returns the matrix as a Float32Array
  5166. * @returns the matrix underlying array
  5167. */
  5168. Matrix.prototype.toArray = function () {
  5169. return this.m;
  5170. };
  5171. /**
  5172. * Returns the matrix as a Float32Array
  5173. * @returns the matrix underlying array.
  5174. */
  5175. Matrix.prototype.asArray = function () {
  5176. return this.toArray();
  5177. };
  5178. /**
  5179. * Inverts the current matrix in place
  5180. * @returns the current inverted matrix
  5181. */
  5182. Matrix.prototype.invert = function () {
  5183. this.invertToRef(this);
  5184. return this;
  5185. };
  5186. /**
  5187. * Sets all the matrix elements to zero
  5188. * @returns the current matrix
  5189. */
  5190. Matrix.prototype.reset = function () {
  5191. for (var index = 0; index < 16; index++) {
  5192. this.m[index] = 0.0;
  5193. }
  5194. this._markAsUpdated();
  5195. return this;
  5196. };
  5197. /**
  5198. * Adds the current matrix with a second one
  5199. * @param other defines the matrix to add
  5200. * @returns a new matrix as the addition of the current matrix and the given one
  5201. */
  5202. Matrix.prototype.add = function (other) {
  5203. var result = new Matrix();
  5204. this.addToRef(other, result);
  5205. return result;
  5206. };
  5207. /**
  5208. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5209. * @param other defines the matrix to add
  5210. * @param result defines the target matrix
  5211. * @returns the current matrix
  5212. */
  5213. Matrix.prototype.addToRef = function (other, result) {
  5214. for (var index = 0; index < 16; index++) {
  5215. result.m[index] = this.m[index] + other.m[index];
  5216. }
  5217. result._markAsUpdated();
  5218. return this;
  5219. };
  5220. /**
  5221. * Adds in place the given matrix to the current matrix
  5222. * @param other defines the second operand
  5223. * @returns the current updated matrix
  5224. */
  5225. Matrix.prototype.addToSelf = function (other) {
  5226. for (var index = 0; index < 16; index++) {
  5227. this.m[index] += other.m[index];
  5228. }
  5229. this._markAsUpdated();
  5230. return this;
  5231. };
  5232. /**
  5233. * Sets the given matrix to the current inverted Matrix
  5234. * @param other defines the target matrix
  5235. * @returns the unmodified current matrix
  5236. */
  5237. Matrix.prototype.invertToRef = function (other) {
  5238. var l1 = this.m[0];
  5239. var l2 = this.m[1];
  5240. var l3 = this.m[2];
  5241. var l4 = this.m[3];
  5242. var l5 = this.m[4];
  5243. var l6 = this.m[5];
  5244. var l7 = this.m[6];
  5245. var l8 = this.m[7];
  5246. var l9 = this.m[8];
  5247. var l10 = this.m[9];
  5248. var l11 = this.m[10];
  5249. var l12 = this.m[11];
  5250. var l13 = this.m[12];
  5251. var l14 = this.m[13];
  5252. var l15 = this.m[14];
  5253. var l16 = this.m[15];
  5254. var l17 = (l11 * l16) - (l12 * l15);
  5255. var l18 = (l10 * l16) - (l12 * l14);
  5256. var l19 = (l10 * l15) - (l11 * l14);
  5257. var l20 = (l9 * l16) - (l12 * l13);
  5258. var l21 = (l9 * l15) - (l11 * l13);
  5259. var l22 = (l9 * l14) - (l10 * l13);
  5260. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5261. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5262. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5263. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5264. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5265. var l28 = (l7 * l16) - (l8 * l15);
  5266. var l29 = (l6 * l16) - (l8 * l14);
  5267. var l30 = (l6 * l15) - (l7 * l14);
  5268. var l31 = (l5 * l16) - (l8 * l13);
  5269. var l32 = (l5 * l15) - (l7 * l13);
  5270. var l33 = (l5 * l14) - (l6 * l13);
  5271. var l34 = (l7 * l12) - (l8 * l11);
  5272. var l35 = (l6 * l12) - (l8 * l10);
  5273. var l36 = (l6 * l11) - (l7 * l10);
  5274. var l37 = (l5 * l12) - (l8 * l9);
  5275. var l38 = (l5 * l11) - (l7 * l9);
  5276. var l39 = (l5 * l10) - (l6 * l9);
  5277. other.m[0] = l23 * l27;
  5278. other.m[4] = l24 * l27;
  5279. other.m[8] = l25 * l27;
  5280. other.m[12] = l26 * l27;
  5281. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5282. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5283. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5284. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5285. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5286. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5287. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5288. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5289. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5290. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5291. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5292. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5293. other._markAsUpdated();
  5294. return this;
  5295. };
  5296. /**
  5297. * Inserts the translation vector (using 3 floats) in the current matrix
  5298. * @param x defines the 1st component of the translation
  5299. * @param y defines the 2nd component of the translation
  5300. * @param z defines the 3rd component of the translation
  5301. * @returns the current updated matrix
  5302. */
  5303. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5304. this.m[12] = x;
  5305. this.m[13] = y;
  5306. this.m[14] = z;
  5307. this._markAsUpdated();
  5308. return this;
  5309. };
  5310. /**
  5311. * Inserts the translation vector in the current matrix
  5312. * @param vector3 defines the translation to insert
  5313. * @returns the current updated matrix
  5314. */
  5315. Matrix.prototype.setTranslation = function (vector3) {
  5316. this.m[12] = vector3.x;
  5317. this.m[13] = vector3.y;
  5318. this.m[14] = vector3.z;
  5319. this._markAsUpdated();
  5320. return this;
  5321. };
  5322. /**
  5323. * Gets the translation value of the current matrix
  5324. * @returns a new Vector3 as the extracted translation from the matrix
  5325. */
  5326. Matrix.prototype.getTranslation = function () {
  5327. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5328. };
  5329. /**
  5330. * Fill a Vector3 with the extracted translation from the matrix
  5331. * @param result defines the Vector3 where to store the translation
  5332. * @returns the current matrix
  5333. */
  5334. Matrix.prototype.getTranslationToRef = function (result) {
  5335. result.x = this.m[12];
  5336. result.y = this.m[13];
  5337. result.z = this.m[14];
  5338. return this;
  5339. };
  5340. /**
  5341. * Remove rotation and scaling part from the matrix
  5342. * @returns the updated matrix
  5343. */
  5344. Matrix.prototype.removeRotationAndScaling = function () {
  5345. this.setRowFromFloats(0, 1, 0, 0, 0);
  5346. this.setRowFromFloats(1, 0, 1, 0, 0);
  5347. this.setRowFromFloats(2, 0, 0, 1, 0);
  5348. return this;
  5349. };
  5350. /**
  5351. * Multiply two matrices
  5352. * @param other defines the second operand
  5353. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5354. */
  5355. Matrix.prototype.multiply = function (other) {
  5356. var result = new Matrix();
  5357. this.multiplyToRef(other, result);
  5358. return result;
  5359. };
  5360. /**
  5361. * Copy the current matrix from the given one
  5362. * @param other defines the source matrix
  5363. * @returns the current updated matrix
  5364. */
  5365. Matrix.prototype.copyFrom = function (other) {
  5366. for (var index = 0; index < 16; index++) {
  5367. this.m[index] = other.m[index];
  5368. }
  5369. this._markAsUpdated();
  5370. return this;
  5371. };
  5372. /**
  5373. * Populates the given array from the starting index with the current matrix values
  5374. * @param array defines the target array
  5375. * @param offset defines the offset in the target array where to start storing values
  5376. * @returns the current matrix
  5377. */
  5378. Matrix.prototype.copyToArray = function (array, offset) {
  5379. if (offset === void 0) { offset = 0; }
  5380. for (var index = 0; index < 16; index++) {
  5381. array[offset + index] = this.m[index];
  5382. }
  5383. return this;
  5384. };
  5385. /**
  5386. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5387. * @param other defines the second operand
  5388. * @param result defines the matrix where to store the multiplication
  5389. * @returns the current matrix
  5390. */
  5391. Matrix.prototype.multiplyToRef = function (other, result) {
  5392. this.multiplyToArray(other, result.m, 0);
  5393. result._markAsUpdated();
  5394. return this;
  5395. };
  5396. /**
  5397. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5398. * @param other defines the second operand
  5399. * @param result defines the array where to store the multiplication
  5400. * @param offset defines the offset in the target array where to start storing values
  5401. * @returns the current matrix
  5402. */
  5403. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5404. var tm0 = this.m[0];
  5405. var tm1 = this.m[1];
  5406. var tm2 = this.m[2];
  5407. var tm3 = this.m[3];
  5408. var tm4 = this.m[4];
  5409. var tm5 = this.m[5];
  5410. var tm6 = this.m[6];
  5411. var tm7 = this.m[7];
  5412. var tm8 = this.m[8];
  5413. var tm9 = this.m[9];
  5414. var tm10 = this.m[10];
  5415. var tm11 = this.m[11];
  5416. var tm12 = this.m[12];
  5417. var tm13 = this.m[13];
  5418. var tm14 = this.m[14];
  5419. var tm15 = this.m[15];
  5420. var om0 = other.m[0];
  5421. var om1 = other.m[1];
  5422. var om2 = other.m[2];
  5423. var om3 = other.m[3];
  5424. var om4 = other.m[4];
  5425. var om5 = other.m[5];
  5426. var om6 = other.m[6];
  5427. var om7 = other.m[7];
  5428. var om8 = other.m[8];
  5429. var om9 = other.m[9];
  5430. var om10 = other.m[10];
  5431. var om11 = other.m[11];
  5432. var om12 = other.m[12];
  5433. var om13 = other.m[13];
  5434. var om14 = other.m[14];
  5435. var om15 = other.m[15];
  5436. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5437. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5438. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5439. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5440. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5441. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5442. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5443. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5444. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5445. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5446. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5447. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5448. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5449. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5450. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5451. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5452. return this;
  5453. };
  5454. /**
  5455. * Check equality between this matrix and a second one
  5456. * @param value defines the second matrix to compare
  5457. * @returns true is the current matrix and the given one values are strictly equal
  5458. */
  5459. Matrix.prototype.equals = function (value) {
  5460. return value &&
  5461. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5462. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5463. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5464. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5465. };
  5466. /**
  5467. * Clone the current matrix
  5468. * @returns a new matrix from the current matrix
  5469. */
  5470. Matrix.prototype.clone = function () {
  5471. 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]);
  5472. };
  5473. /**
  5474. * Returns the name of the current matrix class
  5475. * @returns the string "Matrix"
  5476. */
  5477. Matrix.prototype.getClassName = function () {
  5478. return "Matrix";
  5479. };
  5480. /**
  5481. * Gets the hash code of the current matrix
  5482. * @returns the hash code
  5483. */
  5484. Matrix.prototype.getHashCode = function () {
  5485. var hash = this.m[0] || 0;
  5486. for (var i = 1; i < 16; i++) {
  5487. hash = (hash * 397) ^ (this.m[i] || 0);
  5488. }
  5489. return hash;
  5490. };
  5491. /**
  5492. * Decomposes the current Matrix into a translation, rotation and scaling components
  5493. * @param scale defines the scale vector3 given as a reference to update
  5494. * @param rotation defines the rotation quaternion given as a reference to update
  5495. * @param translation defines the translation vector3 given as a reference to update
  5496. * @returns true if operation was successful
  5497. */
  5498. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5499. if (translation) {
  5500. translation.x = this.m[12];
  5501. translation.y = this.m[13];
  5502. translation.z = this.m[14];
  5503. }
  5504. scale = scale || MathTmp.Vector3[0];
  5505. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5506. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5507. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5508. if (this.determinant() <= 0) {
  5509. scale.y *= -1;
  5510. }
  5511. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5512. if (rotation) {
  5513. rotation.x = 0;
  5514. rotation.y = 0;
  5515. rotation.z = 0;
  5516. rotation.w = 1;
  5517. }
  5518. return false;
  5519. }
  5520. if (rotation) {
  5521. 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]);
  5522. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5523. }
  5524. return true;
  5525. };
  5526. /**
  5527. * Gets specific row of the matrix
  5528. * @param index defines the number of the row to get
  5529. * @returns the index-th row of the current matrix as a new Vector4
  5530. */
  5531. Matrix.prototype.getRow = function (index) {
  5532. if (index < 0 || index > 3) {
  5533. return null;
  5534. }
  5535. var i = index * 4;
  5536. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5537. };
  5538. /**
  5539. * Sets the index-th row of the current matrix to the vector4 values
  5540. * @param index defines the number of the row to set
  5541. * @param row defines the target vector4
  5542. * @returns the updated current matrix
  5543. */
  5544. Matrix.prototype.setRow = function (index, row) {
  5545. if (index < 0 || index > 3) {
  5546. return this;
  5547. }
  5548. var i = index * 4;
  5549. this.m[i + 0] = row.x;
  5550. this.m[i + 1] = row.y;
  5551. this.m[i + 2] = row.z;
  5552. this.m[i + 3] = row.w;
  5553. this._markAsUpdated();
  5554. return this;
  5555. };
  5556. /**
  5557. * Compute the transpose of the matrix
  5558. * @returns the new transposed matrix
  5559. */
  5560. Matrix.prototype.transpose = function () {
  5561. return Matrix.Transpose(this);
  5562. };
  5563. /**
  5564. * Compute the transpose of the matrix and store it in a given matrix
  5565. * @param result defines the target matrix
  5566. * @returns the current matrix
  5567. */
  5568. Matrix.prototype.transposeToRef = function (result) {
  5569. Matrix.TransposeToRef(this, result);
  5570. return this;
  5571. };
  5572. /**
  5573. * Sets the index-th row of the current matrix with the given 4 x float values
  5574. * @param index defines the row index
  5575. * @param x defines the x component to set
  5576. * @param y defines the y component to set
  5577. * @param z defines the z component to set
  5578. * @param w defines the w component to set
  5579. * @returns the updated current matrix
  5580. */
  5581. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5582. if (index < 0 || index > 3) {
  5583. return this;
  5584. }
  5585. var i = index * 4;
  5586. this.m[i + 0] = x;
  5587. this.m[i + 1] = y;
  5588. this.m[i + 2] = z;
  5589. this.m[i + 3] = w;
  5590. this._markAsUpdated();
  5591. return this;
  5592. };
  5593. /**
  5594. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5595. * @param scale defines the scale factor
  5596. * @returns a new matrix
  5597. */
  5598. Matrix.prototype.scale = function (scale) {
  5599. var result = new Matrix();
  5600. this.scaleToRef(scale, result);
  5601. return result;
  5602. };
  5603. /**
  5604. * Scale the current matrix values by a factor to a given result matrix
  5605. * @param scale defines the scale factor
  5606. * @param result defines the matrix to store the result
  5607. * @returns the current matrix
  5608. */
  5609. Matrix.prototype.scaleToRef = function (scale, result) {
  5610. for (var index = 0; index < 16; index++) {
  5611. result.m[index] = this.m[index] * scale;
  5612. }
  5613. result._markAsUpdated();
  5614. return this;
  5615. };
  5616. /**
  5617. * Scale the current matrix values by a factor and add the result to a given matrix
  5618. * @param scale defines the scale factor
  5619. * @param result defines the Matrix to store the result
  5620. * @returns the current matrix
  5621. */
  5622. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5623. for (var index = 0; index < 16; index++) {
  5624. result.m[index] += this.m[index] * scale;
  5625. }
  5626. result._markAsUpdated();
  5627. return this;
  5628. };
  5629. /**
  5630. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5631. * @param ref matrix to store the result
  5632. */
  5633. Matrix.prototype.toNormalMatrix = function (ref) {
  5634. this.invertToRef(ref);
  5635. ref.transpose();
  5636. var m = ref.m;
  5637. 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);
  5638. };
  5639. /**
  5640. * Gets only rotation part of the current matrix
  5641. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5642. */
  5643. Matrix.prototype.getRotationMatrix = function () {
  5644. var result = Matrix.Identity();
  5645. this.getRotationMatrixToRef(result);
  5646. return result;
  5647. };
  5648. /**
  5649. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5650. * @param result defines the target matrix to store data to
  5651. * @returns the current matrix
  5652. */
  5653. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5654. var m = this.m;
  5655. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5656. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5657. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5658. if (this.determinant() <= 0) {
  5659. sy *= -1;
  5660. }
  5661. if (sx === 0 || sy === 0 || sz === 0) {
  5662. Matrix.IdentityToRef(result);
  5663. }
  5664. else {
  5665. 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);
  5666. }
  5667. return this;
  5668. };
  5669. // Statics
  5670. /**
  5671. * Creates a matrix from an array
  5672. * @param array defines the source array
  5673. * @param offset defines an offset in the source array
  5674. * @returns a new Matrix set from the starting index of the given array
  5675. */
  5676. Matrix.FromArray = function (array, offset) {
  5677. var result = new Matrix();
  5678. if (!offset) {
  5679. offset = 0;
  5680. }
  5681. Matrix.FromArrayToRef(array, offset, result);
  5682. return result;
  5683. };
  5684. /**
  5685. * Copy the content of an array into a given matrix
  5686. * @param array defines the source array
  5687. * @param offset defines an offset in the source array
  5688. * @param result defines the target matrix
  5689. */
  5690. Matrix.FromArrayToRef = function (array, offset, result) {
  5691. for (var index = 0; index < 16; index++) {
  5692. result.m[index] = array[index + offset];
  5693. }
  5694. result._markAsUpdated();
  5695. };
  5696. /**
  5697. * Stores an array into a matrix after having multiplied each component by a given factor
  5698. * @param array defines the source array
  5699. * @param offset defines the offset in the source array
  5700. * @param scale defines the scaling factor
  5701. * @param result defines the target matrix
  5702. */
  5703. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5704. for (var index = 0; index < 16; index++) {
  5705. result.m[index] = array[index + offset] * scale;
  5706. }
  5707. result._markAsUpdated();
  5708. };
  5709. /**
  5710. * Stores a list of values (16) inside a given matrix
  5711. * @param initialM11 defines 1st value of 1st row
  5712. * @param initialM12 defines 2nd value of 1st row
  5713. * @param initialM13 defines 3rd value of 1st row
  5714. * @param initialM14 defines 4th value of 1st row
  5715. * @param initialM21 defines 1st value of 2nd row
  5716. * @param initialM22 defines 2nd value of 2nd row
  5717. * @param initialM23 defines 3rd value of 2nd row
  5718. * @param initialM24 defines 4th value of 2nd row
  5719. * @param initialM31 defines 1st value of 3rd row
  5720. * @param initialM32 defines 2nd value of 3rd row
  5721. * @param initialM33 defines 3rd value of 3rd row
  5722. * @param initialM34 defines 4th value of 3rd row
  5723. * @param initialM41 defines 1st value of 4th row
  5724. * @param initialM42 defines 2nd value of 4th row
  5725. * @param initialM43 defines 3rd value of 4th row
  5726. * @param initialM44 defines 4th value of 4th row
  5727. * @param result defines the target matrix
  5728. */
  5729. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5730. result.m[0] = initialM11;
  5731. result.m[1] = initialM12;
  5732. result.m[2] = initialM13;
  5733. result.m[3] = initialM14;
  5734. result.m[4] = initialM21;
  5735. result.m[5] = initialM22;
  5736. result.m[6] = initialM23;
  5737. result.m[7] = initialM24;
  5738. result.m[8] = initialM31;
  5739. result.m[9] = initialM32;
  5740. result.m[10] = initialM33;
  5741. result.m[11] = initialM34;
  5742. result.m[12] = initialM41;
  5743. result.m[13] = initialM42;
  5744. result.m[14] = initialM43;
  5745. result.m[15] = initialM44;
  5746. result._markAsUpdated();
  5747. };
  5748. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5749. /**
  5750. * Gets an identity matrix that must not be updated
  5751. */
  5752. get: function () {
  5753. return Matrix._identityReadOnly;
  5754. },
  5755. enumerable: true,
  5756. configurable: true
  5757. });
  5758. /**
  5759. * Creates new matrix from a list of values (16)
  5760. * @param initialM11 defines 1st value of 1st row
  5761. * @param initialM12 defines 2nd value of 1st row
  5762. * @param initialM13 defines 3rd value of 1st row
  5763. * @param initialM14 defines 4th value of 1st row
  5764. * @param initialM21 defines 1st value of 2nd row
  5765. * @param initialM22 defines 2nd value of 2nd row
  5766. * @param initialM23 defines 3rd value of 2nd row
  5767. * @param initialM24 defines 4th value of 2nd row
  5768. * @param initialM31 defines 1st value of 3rd row
  5769. * @param initialM32 defines 2nd value of 3rd row
  5770. * @param initialM33 defines 3rd value of 3rd row
  5771. * @param initialM34 defines 4th value of 3rd row
  5772. * @param initialM41 defines 1st value of 4th row
  5773. * @param initialM42 defines 2nd value of 4th row
  5774. * @param initialM43 defines 3rd value of 4th row
  5775. * @param initialM44 defines 4th value of 4th row
  5776. * @returns the new matrix
  5777. */
  5778. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5779. var result = new Matrix();
  5780. result.m[0] = initialM11;
  5781. result.m[1] = initialM12;
  5782. result.m[2] = initialM13;
  5783. result.m[3] = initialM14;
  5784. result.m[4] = initialM21;
  5785. result.m[5] = initialM22;
  5786. result.m[6] = initialM23;
  5787. result.m[7] = initialM24;
  5788. result.m[8] = initialM31;
  5789. result.m[9] = initialM32;
  5790. result.m[10] = initialM33;
  5791. result.m[11] = initialM34;
  5792. result.m[12] = initialM41;
  5793. result.m[13] = initialM42;
  5794. result.m[14] = initialM43;
  5795. result.m[15] = initialM44;
  5796. return result;
  5797. };
  5798. /**
  5799. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5800. * @param scale defines the scale vector3
  5801. * @param rotation defines the rotation quaternion
  5802. * @param translation defines the translation vector3
  5803. * @returns a new matrix
  5804. */
  5805. Matrix.Compose = function (scale, rotation, translation) {
  5806. var result = Matrix.Identity();
  5807. Matrix.ComposeToRef(scale, rotation, translation, result);
  5808. return result;
  5809. };
  5810. /**
  5811. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5812. * @param scale defines the scale vector3
  5813. * @param rotation defines the rotation quaternion
  5814. * @param translation defines the translation vector3
  5815. * @param result defines the target matrix
  5816. */
  5817. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5818. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5819. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5820. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5821. result.setTranslation(translation);
  5822. };
  5823. /**
  5824. * Creates a new identity matrix
  5825. * @returns a new identity matrix
  5826. */
  5827. Matrix.Identity = function () {
  5828. 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);
  5829. };
  5830. /**
  5831. * Creates a new identity matrix and stores the result in a given matrix
  5832. * @param result defines the target matrix
  5833. */
  5834. Matrix.IdentityToRef = function (result) {
  5835. 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);
  5836. };
  5837. /**
  5838. * Creates a new zero matrix
  5839. * @returns a new zero matrix
  5840. */
  5841. Matrix.Zero = function () {
  5842. 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);
  5843. };
  5844. /**
  5845. * Creates a new rotation matrix for "angle" radians around the X axis
  5846. * @param angle defines the angle (in radians) to use
  5847. * @return the new matrix
  5848. */
  5849. Matrix.RotationX = function (angle) {
  5850. var result = new Matrix();
  5851. Matrix.RotationXToRef(angle, result);
  5852. return result;
  5853. };
  5854. /**
  5855. * Creates a new matrix as the invert of a given matrix
  5856. * @param source defines the source matrix
  5857. * @returns the new matrix
  5858. */
  5859. Matrix.Invert = function (source) {
  5860. var result = new Matrix();
  5861. source.invertToRef(result);
  5862. return result;
  5863. };
  5864. /**
  5865. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5866. * @param angle defines the angle (in radians) to use
  5867. * @param result defines the target matrix
  5868. */
  5869. Matrix.RotationXToRef = function (angle, result) {
  5870. var s = Math.sin(angle);
  5871. var c = Math.cos(angle);
  5872. result.m[0] = 1.0;
  5873. result.m[15] = 1.0;
  5874. result.m[5] = c;
  5875. result.m[10] = c;
  5876. result.m[9] = -s;
  5877. result.m[6] = s;
  5878. result.m[1] = 0.0;
  5879. result.m[2] = 0.0;
  5880. result.m[3] = 0.0;
  5881. result.m[4] = 0.0;
  5882. result.m[7] = 0.0;
  5883. result.m[8] = 0.0;
  5884. result.m[11] = 0.0;
  5885. result.m[12] = 0.0;
  5886. result.m[13] = 0.0;
  5887. result.m[14] = 0.0;
  5888. result._markAsUpdated();
  5889. };
  5890. /**
  5891. * Creates a new rotation matrix for "angle" radians around the Y axis
  5892. * @param angle defines the angle (in radians) to use
  5893. * @return the new matrix
  5894. */
  5895. Matrix.RotationY = function (angle) {
  5896. var result = new Matrix();
  5897. Matrix.RotationYToRef(angle, result);
  5898. return result;
  5899. };
  5900. /**
  5901. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5902. * @param angle defines the angle (in radians) to use
  5903. * @param result defines the target matrix
  5904. */
  5905. Matrix.RotationYToRef = function (angle, result) {
  5906. var s = Math.sin(angle);
  5907. var c = Math.cos(angle);
  5908. result.m[5] = 1.0;
  5909. result.m[15] = 1.0;
  5910. result.m[0] = c;
  5911. result.m[2] = -s;
  5912. result.m[8] = s;
  5913. result.m[10] = c;
  5914. result.m[1] = 0.0;
  5915. result.m[3] = 0.0;
  5916. result.m[4] = 0.0;
  5917. result.m[6] = 0.0;
  5918. result.m[7] = 0.0;
  5919. result.m[9] = 0.0;
  5920. result.m[11] = 0.0;
  5921. result.m[12] = 0.0;
  5922. result.m[13] = 0.0;
  5923. result.m[14] = 0.0;
  5924. result._markAsUpdated();
  5925. };
  5926. /**
  5927. * Creates a new rotation matrix for "angle" radians around the Z axis
  5928. * @param angle defines the angle (in radians) to use
  5929. * @return the new matrix
  5930. */
  5931. Matrix.RotationZ = function (angle) {
  5932. var result = new Matrix();
  5933. Matrix.RotationZToRef(angle, result);
  5934. return result;
  5935. };
  5936. /**
  5937. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5938. * @param angle defines the angle (in radians) to use
  5939. * @param result defines the target matrix
  5940. */
  5941. Matrix.RotationZToRef = function (angle, result) {
  5942. var s = Math.sin(angle);
  5943. var c = Math.cos(angle);
  5944. result.m[10] = 1.0;
  5945. result.m[15] = 1.0;
  5946. result.m[0] = c;
  5947. result.m[1] = s;
  5948. result.m[4] = -s;
  5949. result.m[5] = c;
  5950. result.m[2] = 0.0;
  5951. result.m[3] = 0.0;
  5952. result.m[6] = 0.0;
  5953. result.m[7] = 0.0;
  5954. result.m[8] = 0.0;
  5955. result.m[9] = 0.0;
  5956. result.m[11] = 0.0;
  5957. result.m[12] = 0.0;
  5958. result.m[13] = 0.0;
  5959. result.m[14] = 0.0;
  5960. result._markAsUpdated();
  5961. };
  5962. /**
  5963. * Creates a new rotation matrix for "angle" radians around the given axis
  5964. * @param axis defines the axis to use
  5965. * @param angle defines the angle (in radians) to use
  5966. * @return the new matrix
  5967. */
  5968. Matrix.RotationAxis = function (axis, angle) {
  5969. var result = Matrix.Zero();
  5970. Matrix.RotationAxisToRef(axis, angle, result);
  5971. return result;
  5972. };
  5973. /**
  5974. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5975. * @param axis defines the axis to use
  5976. * @param angle defines the angle (in radians) to use
  5977. * @param result defines the target matrix
  5978. */
  5979. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5980. var s = Math.sin(-angle);
  5981. var c = Math.cos(-angle);
  5982. var c1 = 1 - c;
  5983. axis.normalize();
  5984. result.m[0] = (axis.x * axis.x) * c1 + c;
  5985. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5986. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5987. result.m[3] = 0.0;
  5988. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5989. result.m[5] = (axis.y * axis.y) * c1 + c;
  5990. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5991. result.m[7] = 0.0;
  5992. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5993. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5994. result.m[10] = (axis.z * axis.z) * c1 + c;
  5995. result.m[11] = 0.0;
  5996. result.m[15] = 1.0;
  5997. result._markAsUpdated();
  5998. };
  5999. /**
  6000. * Creates a rotation matrix
  6001. * @param yaw defines the yaw angle in radians (Y axis)
  6002. * @param pitch defines the pitch angle in radians (X axis)
  6003. * @param roll defines the roll angle in radians (X axis)
  6004. * @returns the new rotation matrix
  6005. */
  6006. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6007. var result = new Matrix();
  6008. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6009. return result;
  6010. };
  6011. /**
  6012. * Creates a rotation matrix and stores it in a given matrix
  6013. * @param yaw defines the yaw angle in radians (Y axis)
  6014. * @param pitch defines the pitch angle in radians (X axis)
  6015. * @param roll defines the roll angle in radians (X axis)
  6016. * @param result defines the target matrix
  6017. */
  6018. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6019. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6020. this._tempQuaternion.toRotationMatrix(result);
  6021. };
  6022. /**
  6023. * Creates a scaling matrix
  6024. * @param x defines the scale factor on X axis
  6025. * @param y defines the scale factor on Y axis
  6026. * @param z defines the scale factor on Z axis
  6027. * @returns the new matrix
  6028. */
  6029. Matrix.Scaling = function (x, y, z) {
  6030. var result = Matrix.Zero();
  6031. Matrix.ScalingToRef(x, y, z, result);
  6032. return result;
  6033. };
  6034. /**
  6035. * Creates a scaling matrix and stores it in a given matrix
  6036. * @param x defines the scale factor on X axis
  6037. * @param y defines the scale factor on Y axis
  6038. * @param z defines the scale factor on Z axis
  6039. * @param result defines the target matrix
  6040. */
  6041. Matrix.ScalingToRef = function (x, y, z, result) {
  6042. result.m[0] = x;
  6043. result.m[1] = 0.0;
  6044. result.m[2] = 0.0;
  6045. result.m[3] = 0.0;
  6046. result.m[4] = 0.0;
  6047. result.m[5] = y;
  6048. result.m[6] = 0.0;
  6049. result.m[7] = 0.0;
  6050. result.m[8] = 0.0;
  6051. result.m[9] = 0.0;
  6052. result.m[10] = z;
  6053. result.m[11] = 0.0;
  6054. result.m[12] = 0.0;
  6055. result.m[13] = 0.0;
  6056. result.m[14] = 0.0;
  6057. result.m[15] = 1.0;
  6058. result._markAsUpdated();
  6059. };
  6060. /**
  6061. * Creates a translation matrix
  6062. * @param x defines the translation on X axis
  6063. * @param y defines the translation on Y axis
  6064. * @param z defines the translationon Z axis
  6065. * @returns the new matrix
  6066. */
  6067. Matrix.Translation = function (x, y, z) {
  6068. var result = Matrix.Identity();
  6069. Matrix.TranslationToRef(x, y, z, result);
  6070. return result;
  6071. };
  6072. /**
  6073. * Creates a translation matrix and stores it in a given matrix
  6074. * @param x defines the translation on X axis
  6075. * @param y defines the translation on Y axis
  6076. * @param z defines the translationon Z axis
  6077. * @param result defines the target matrix
  6078. */
  6079. Matrix.TranslationToRef = function (x, y, z, result) {
  6080. 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);
  6081. };
  6082. /**
  6083. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6084. * @param startValue defines the start value
  6085. * @param endValue defines the end value
  6086. * @param gradient defines the gradient factor
  6087. * @returns the new matrix
  6088. */
  6089. Matrix.Lerp = function (startValue, endValue, gradient) {
  6090. var result = Matrix.Zero();
  6091. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6092. return result;
  6093. };
  6094. /**
  6095. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6096. * @param startValue defines the start value
  6097. * @param endValue defines the end value
  6098. * @param gradient defines the gradient factor
  6099. * @param result defines the Matrix object where to store data
  6100. */
  6101. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6102. for (var index = 0; index < 16; index++) {
  6103. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6104. }
  6105. result._markAsUpdated();
  6106. };
  6107. /**
  6108. * Builds a new matrix whose values are computed by:
  6109. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6110. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6111. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6112. * @param startValue defines the first matrix
  6113. * @param endValue defines the second matrix
  6114. * @param gradient defines the gradient between the two matrices
  6115. * @returns the new matrix
  6116. */
  6117. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6118. var result = Matrix.Zero();
  6119. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6120. return result;
  6121. };
  6122. /**
  6123. * Update a matrix to values which are computed by:
  6124. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6125. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6126. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6127. * @param startValue defines the first matrix
  6128. * @param endValue defines the second matrix
  6129. * @param gradient defines the gradient between the two matrices
  6130. * @param result defines the target matrix
  6131. */
  6132. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6133. var startScale = MathTmp.Vector3[0];
  6134. var startRotation = MathTmp.Quaternion[0];
  6135. var startTranslation = MathTmp.Vector3[1];
  6136. startValue.decompose(startScale, startRotation, startTranslation);
  6137. var endScale = MathTmp.Vector3[2];
  6138. var endRotation = MathTmp.Quaternion[1];
  6139. var endTranslation = MathTmp.Vector3[3];
  6140. endValue.decompose(endScale, endRotation, endTranslation);
  6141. var resultScale = MathTmp.Vector3[4];
  6142. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6143. var resultRotation = MathTmp.Quaternion[2];
  6144. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6145. var resultTranslation = MathTmp.Vector3[5];
  6146. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6147. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6148. };
  6149. /**
  6150. * 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"
  6151. * This function works in left handed mode
  6152. * @param eye defines the final position of the entity
  6153. * @param target defines where the entity should look at
  6154. * @param up defines the up vector for the entity
  6155. * @returns the new matrix
  6156. */
  6157. Matrix.LookAtLH = function (eye, target, up) {
  6158. var result = Matrix.Zero();
  6159. Matrix.LookAtLHToRef(eye, target, up, result);
  6160. return result;
  6161. };
  6162. /**
  6163. * 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".
  6164. * This function works in left handed mode
  6165. * @param eye defines the final position of the entity
  6166. * @param target defines where the entity should look at
  6167. * @param up defines the up vector for the entity
  6168. * @param result defines the target matrix
  6169. */
  6170. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6171. // Z axis
  6172. target.subtractToRef(eye, this._zAxis);
  6173. this._zAxis.normalize();
  6174. // X axis
  6175. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6176. if (this._xAxis.lengthSquared() === 0) {
  6177. this._xAxis.x = 1.0;
  6178. }
  6179. else {
  6180. this._xAxis.normalize();
  6181. }
  6182. // Y axis
  6183. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6184. this._yAxis.normalize();
  6185. // Eye angles
  6186. var ex = -Vector3.Dot(this._xAxis, eye);
  6187. var ey = -Vector3.Dot(this._yAxis, eye);
  6188. var ez = -Vector3.Dot(this._zAxis, eye);
  6189. 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);
  6190. };
  6191. /**
  6192. * 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"
  6193. * This function works in right handed mode
  6194. * @param eye defines the final position of the entity
  6195. * @param target defines where the entity should look at
  6196. * @param up defines the up vector for the entity
  6197. * @returns the new matrix
  6198. */
  6199. Matrix.LookAtRH = function (eye, target, up) {
  6200. var result = Matrix.Zero();
  6201. Matrix.LookAtRHToRef(eye, target, up, result);
  6202. return result;
  6203. };
  6204. /**
  6205. * 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".
  6206. * This function works in right handed mode
  6207. * @param eye defines the final position of the entity
  6208. * @param target defines where the entity should look at
  6209. * @param up defines the up vector for the entity
  6210. * @param result defines the target matrix
  6211. */
  6212. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6213. // Z axis
  6214. eye.subtractToRef(target, this._zAxis);
  6215. this._zAxis.normalize();
  6216. // X axis
  6217. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6218. if (this._xAxis.lengthSquared() === 0) {
  6219. this._xAxis.x = 1.0;
  6220. }
  6221. else {
  6222. this._xAxis.normalize();
  6223. }
  6224. // Y axis
  6225. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6226. this._yAxis.normalize();
  6227. // Eye angles
  6228. var ex = -Vector3.Dot(this._xAxis, eye);
  6229. var ey = -Vector3.Dot(this._yAxis, eye);
  6230. var ez = -Vector3.Dot(this._zAxis, eye);
  6231. 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);
  6232. };
  6233. /**
  6234. * Create a left-handed orthographic projection matrix
  6235. * @param width defines the viewport width
  6236. * @param height defines the viewport height
  6237. * @param znear defines the near clip plane
  6238. * @param zfar defines the far clip plane
  6239. * @returns a new matrix as a left-handed orthographic projection matrix
  6240. */
  6241. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6242. var matrix = Matrix.Zero();
  6243. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6244. return matrix;
  6245. };
  6246. /**
  6247. * Store a left-handed orthographic projection to a given matrix
  6248. * @param width defines the viewport width
  6249. * @param height defines the viewport height
  6250. * @param znear defines the near clip plane
  6251. * @param zfar defines the far clip plane
  6252. * @param result defines the target matrix
  6253. */
  6254. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6255. var n = znear;
  6256. var f = zfar;
  6257. var a = 2.0 / width;
  6258. var b = 2.0 / height;
  6259. var c = 2.0 / (f - n);
  6260. var d = -(f + n) / (f - n);
  6261. 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);
  6262. };
  6263. /**
  6264. * Create a left-handed orthographic projection matrix
  6265. * @param left defines the viewport left coordinate
  6266. * @param right defines the viewport right coordinate
  6267. * @param bottom defines the viewport bottom coordinate
  6268. * @param top defines the viewport top coordinate
  6269. * @param znear defines the near clip plane
  6270. * @param zfar defines the far clip plane
  6271. * @returns a new matrix as a left-handed orthographic projection matrix
  6272. */
  6273. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6274. var matrix = Matrix.Zero();
  6275. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6276. return matrix;
  6277. };
  6278. /**
  6279. * Stores a left-handed orthographic projection into a given matrix
  6280. * @param left defines the viewport left coordinate
  6281. * @param right defines the viewport right coordinate
  6282. * @param bottom defines the viewport bottom coordinate
  6283. * @param top defines the viewport top coordinate
  6284. * @param znear defines the near clip plane
  6285. * @param zfar defines the far clip plane
  6286. * @param result defines the target matrix
  6287. */
  6288. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6289. var n = znear;
  6290. var f = zfar;
  6291. var a = 2.0 / (right - left);
  6292. var b = 2.0 / (top - bottom);
  6293. var c = 2.0 / (f - n);
  6294. var d = -(f + n) / (f - n);
  6295. var i0 = (left + right) / (left - right);
  6296. var i1 = (top + bottom) / (bottom - top);
  6297. 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);
  6298. };
  6299. /**
  6300. * Creates a right-handed orthographic projection matrix
  6301. * @param left defines the viewport left coordinate
  6302. * @param right defines the viewport right coordinate
  6303. * @param bottom defines the viewport bottom coordinate
  6304. * @param top defines the viewport top coordinate
  6305. * @param znear defines the near clip plane
  6306. * @param zfar defines the far clip plane
  6307. * @returns a new matrix as a right-handed orthographic projection matrix
  6308. */
  6309. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6310. var matrix = Matrix.Zero();
  6311. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6312. return matrix;
  6313. };
  6314. /**
  6315. * Stores a right-handed orthographic projection into a given matrix
  6316. * @param left defines the viewport left coordinate
  6317. * @param right defines the viewport right coordinate
  6318. * @param bottom defines the viewport bottom coordinate
  6319. * @param top defines the viewport top coordinate
  6320. * @param znear defines the near clip plane
  6321. * @param zfar defines the far clip plane
  6322. * @param result defines the target matrix
  6323. */
  6324. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6325. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6326. result.m[10] *= -1.0;
  6327. };
  6328. /**
  6329. * Creates a left-handed perspective projection matrix
  6330. * @param width defines the viewport width
  6331. * @param height defines the viewport height
  6332. * @param znear defines the near clip plane
  6333. * @param zfar defines the far clip plane
  6334. * @returns a new matrix as a left-handed perspective projection matrix
  6335. */
  6336. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6337. var matrix = Matrix.Zero();
  6338. var n = znear;
  6339. var f = zfar;
  6340. var a = 2.0 * n / width;
  6341. var b = 2.0 * n / height;
  6342. var c = (f + n) / (f - n);
  6343. var d = -2.0 * f * n / (f - n);
  6344. 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);
  6345. return matrix;
  6346. };
  6347. /**
  6348. * Creates a left-handed perspective projection matrix
  6349. * @param fov defines the horizontal field of view
  6350. * @param aspect defines the aspect ratio
  6351. * @param znear defines the near clip plane
  6352. * @param zfar defines the far clip plane
  6353. * @returns a new matrix as a left-handed perspective projection matrix
  6354. */
  6355. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6356. var matrix = Matrix.Zero();
  6357. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6358. return matrix;
  6359. };
  6360. /**
  6361. * Stores a left-handed perspective projection into a given matrix
  6362. * @param fov defines the horizontal field of view
  6363. * @param aspect defines the aspect ratio
  6364. * @param znear defines the near clip plane
  6365. * @param zfar defines the far clip plane
  6366. * @param result defines the target matrix
  6367. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6368. */
  6369. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6370. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6371. var n = znear;
  6372. var f = zfar;
  6373. var t = 1.0 / (Math.tan(fov * 0.5));
  6374. var a = isVerticalFovFixed ? (t / aspect) : t;
  6375. var b = isVerticalFovFixed ? t : (t * aspect);
  6376. var c = (f + n) / (f - n);
  6377. var d = -2.0 * f * n / (f - n);
  6378. 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);
  6379. };
  6380. /**
  6381. * Creates a right-handed perspective projection matrix
  6382. * @param fov defines the horizontal field of view
  6383. * @param aspect defines the aspect ratio
  6384. * @param znear defines the near clip plane
  6385. * @param zfar defines the far clip plane
  6386. * @returns a new matrix as a right-handed perspective projection matrix
  6387. */
  6388. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6389. var matrix = Matrix.Zero();
  6390. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6391. return matrix;
  6392. };
  6393. /**
  6394. * Stores a right-handed perspective projection into a given matrix
  6395. * @param fov defines the horizontal field of view
  6396. * @param aspect defines the aspect ratio
  6397. * @param znear defines the near clip plane
  6398. * @param zfar defines the far clip plane
  6399. * @param result defines the target matrix
  6400. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6401. */
  6402. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6403. //alternatively this could be expressed as:
  6404. // m = PerspectiveFovLHToRef
  6405. // m[10] *= -1.0;
  6406. // m[11] *= -1.0;
  6407. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6408. var n = znear;
  6409. var f = zfar;
  6410. var t = 1.0 / (Math.tan(fov * 0.5));
  6411. var a = isVerticalFovFixed ? (t / aspect) : t;
  6412. var b = isVerticalFovFixed ? t : (t * aspect);
  6413. var c = -(f + n) / (f - n);
  6414. var d = -2 * f * n / (f - n);
  6415. 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);
  6416. };
  6417. /**
  6418. * Stores a perspective projection for WebVR info a given matrix
  6419. * @param fov defines the field of view
  6420. * @param znear defines the near clip plane
  6421. * @param zfar defines the far clip plane
  6422. * @param result defines the target matrix
  6423. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6424. */
  6425. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6426. if (rightHanded === void 0) { rightHanded = false; }
  6427. var rightHandedFactor = rightHanded ? -1 : 1;
  6428. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6429. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6430. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6431. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6432. var xScale = 2.0 / (leftTan + rightTan);
  6433. var yScale = 2.0 / (upTan + downTan);
  6434. result.m[0] = xScale;
  6435. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6436. result.m[5] = yScale;
  6437. result.m[6] = result.m[7] = 0.0;
  6438. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6439. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6440. result.m[10] = -zfar / (znear - zfar);
  6441. result.m[11] = 1.0 * rightHandedFactor;
  6442. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6443. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6444. result._markAsUpdated();
  6445. };
  6446. /**
  6447. * Computes a complete transformation matrix
  6448. * @param viewport defines the viewport to use
  6449. * @param world defines the world matrix
  6450. * @param view defines the view matrix
  6451. * @param projection defines the projection matrix
  6452. * @param zmin defines the near clip plane
  6453. * @param zmax defines the far clip plane
  6454. * @returns the transformation matrix
  6455. */
  6456. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6457. var cw = viewport.width;
  6458. var ch = viewport.height;
  6459. var cx = viewport.x;
  6460. var cy = viewport.y;
  6461. 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);
  6462. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6463. };
  6464. /**
  6465. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6466. * @param matrix defines the matrix to use
  6467. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6468. */
  6469. Matrix.GetAsMatrix2x2 = function (matrix) {
  6470. return new Float32Array([
  6471. matrix.m[0], matrix.m[1],
  6472. matrix.m[4], matrix.m[5]
  6473. ]);
  6474. };
  6475. /**
  6476. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6477. * @param matrix defines the matrix to use
  6478. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6479. */
  6480. Matrix.GetAsMatrix3x3 = function (matrix) {
  6481. return new Float32Array([
  6482. matrix.m[0], matrix.m[1], matrix.m[2],
  6483. matrix.m[4], matrix.m[5], matrix.m[6],
  6484. matrix.m[8], matrix.m[9], matrix.m[10]
  6485. ]);
  6486. };
  6487. /**
  6488. * Compute the transpose of a given matrix
  6489. * @param matrix defines the matrix to transpose
  6490. * @returns the new matrix
  6491. */
  6492. Matrix.Transpose = function (matrix) {
  6493. var result = new Matrix();
  6494. Matrix.TransposeToRef(matrix, result);
  6495. return result;
  6496. };
  6497. /**
  6498. * Compute the transpose of a matrix and store it in a target matrix
  6499. * @param matrix defines the matrix to transpose
  6500. * @param result defines the target matrix
  6501. */
  6502. Matrix.TransposeToRef = function (matrix, result) {
  6503. result.m[0] = matrix.m[0];
  6504. result.m[1] = matrix.m[4];
  6505. result.m[2] = matrix.m[8];
  6506. result.m[3] = matrix.m[12];
  6507. result.m[4] = matrix.m[1];
  6508. result.m[5] = matrix.m[5];
  6509. result.m[6] = matrix.m[9];
  6510. result.m[7] = matrix.m[13];
  6511. result.m[8] = matrix.m[2];
  6512. result.m[9] = matrix.m[6];
  6513. result.m[10] = matrix.m[10];
  6514. result.m[11] = matrix.m[14];
  6515. result.m[12] = matrix.m[3];
  6516. result.m[13] = matrix.m[7];
  6517. result.m[14] = matrix.m[11];
  6518. result.m[15] = matrix.m[15];
  6519. };
  6520. /**
  6521. * Computes a reflection matrix from a plane
  6522. * @param plane defines the reflection plane
  6523. * @returns a new matrix
  6524. */
  6525. Matrix.Reflection = function (plane) {
  6526. var matrix = new Matrix();
  6527. Matrix.ReflectionToRef(plane, matrix);
  6528. return matrix;
  6529. };
  6530. /**
  6531. * Computes a reflection matrix from a plane
  6532. * @param plane defines the reflection plane
  6533. * @param result defines the target matrix
  6534. */
  6535. Matrix.ReflectionToRef = function (plane, result) {
  6536. plane.normalize();
  6537. var x = plane.normal.x;
  6538. var y = plane.normal.y;
  6539. var z = plane.normal.z;
  6540. var temp = -2 * x;
  6541. var temp2 = -2 * y;
  6542. var temp3 = -2 * z;
  6543. result.m[0] = (temp * x) + 1;
  6544. result.m[1] = temp2 * x;
  6545. result.m[2] = temp3 * x;
  6546. result.m[3] = 0.0;
  6547. result.m[4] = temp * y;
  6548. result.m[5] = (temp2 * y) + 1;
  6549. result.m[6] = temp3 * y;
  6550. result.m[7] = 0.0;
  6551. result.m[8] = temp * z;
  6552. result.m[9] = temp2 * z;
  6553. result.m[10] = (temp3 * z) + 1;
  6554. result.m[11] = 0.0;
  6555. result.m[12] = temp * plane.d;
  6556. result.m[13] = temp2 * plane.d;
  6557. result.m[14] = temp3 * plane.d;
  6558. result.m[15] = 1.0;
  6559. result._markAsUpdated();
  6560. };
  6561. /**
  6562. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6563. * @param xaxis defines the value of the 1st axis
  6564. * @param yaxis defines the value of the 2nd axis
  6565. * @param zaxis defines the value of the 3rd axis
  6566. * @param result defines the target matrix
  6567. */
  6568. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6569. result.m[0] = xaxis.x;
  6570. result.m[1] = xaxis.y;
  6571. result.m[2] = xaxis.z;
  6572. result.m[3] = 0.0;
  6573. result.m[4] = yaxis.x;
  6574. result.m[5] = yaxis.y;
  6575. result.m[6] = yaxis.z;
  6576. result.m[7] = 0.0;
  6577. result.m[8] = zaxis.x;
  6578. result.m[9] = zaxis.y;
  6579. result.m[10] = zaxis.z;
  6580. result.m[11] = 0.0;
  6581. result.m[12] = 0.0;
  6582. result.m[13] = 0.0;
  6583. result.m[14] = 0.0;
  6584. result.m[15] = 1.0;
  6585. result._markAsUpdated();
  6586. };
  6587. /**
  6588. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6589. * @param quat defines the quaternion to use
  6590. * @param result defines the target matrix
  6591. */
  6592. Matrix.FromQuaternionToRef = function (quat, result) {
  6593. var xx = quat.x * quat.x;
  6594. var yy = quat.y * quat.y;
  6595. var zz = quat.z * quat.z;
  6596. var xy = quat.x * quat.y;
  6597. var zw = quat.z * quat.w;
  6598. var zx = quat.z * quat.x;
  6599. var yw = quat.y * quat.w;
  6600. var yz = quat.y * quat.z;
  6601. var xw = quat.x * quat.w;
  6602. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6603. result.m[1] = 2.0 * (xy + zw);
  6604. result.m[2] = 2.0 * (zx - yw);
  6605. result.m[3] = 0.0;
  6606. result.m[4] = 2.0 * (xy - zw);
  6607. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6608. result.m[6] = 2.0 * (yz + xw);
  6609. result.m[7] = 0.0;
  6610. result.m[8] = 2.0 * (zx + yw);
  6611. result.m[9] = 2.0 * (yz - xw);
  6612. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6613. result.m[11] = 0.0;
  6614. result.m[12] = 0.0;
  6615. result.m[13] = 0.0;
  6616. result.m[14] = 0.0;
  6617. result.m[15] = 1.0;
  6618. result._markAsUpdated();
  6619. };
  6620. Matrix._tempQuaternion = new Quaternion();
  6621. Matrix._xAxis = Vector3.Zero();
  6622. Matrix._yAxis = Vector3.Zero();
  6623. Matrix._zAxis = Vector3.Zero();
  6624. Matrix._updateFlagSeed = 0;
  6625. Matrix._identityReadOnly = Matrix.Identity();
  6626. return Matrix;
  6627. }());
  6628. BABYLON.Matrix = Matrix;
  6629. var Plane = /** @class */ (function () {
  6630. /**
  6631. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6632. */
  6633. function Plane(a, b, c, d) {
  6634. this.normal = new Vector3(a, b, c);
  6635. this.d = d;
  6636. }
  6637. /**
  6638. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6639. */
  6640. Plane.prototype.asArray = function () {
  6641. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6642. };
  6643. // Methods
  6644. /**
  6645. * Returns a new plane copied from the current Plane.
  6646. */
  6647. Plane.prototype.clone = function () {
  6648. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6649. };
  6650. /**
  6651. * Returns the string "Plane".
  6652. */
  6653. Plane.prototype.getClassName = function () {
  6654. return "Plane";
  6655. };
  6656. /**
  6657. * Returns the Plane hash code.
  6658. */
  6659. Plane.prototype.getHashCode = function () {
  6660. var hash = this.normal.getHashCode();
  6661. hash = (hash * 397) ^ (this.d || 0);
  6662. return hash;
  6663. };
  6664. /**
  6665. * Normalize the current Plane in place.
  6666. * Returns the updated Plane.
  6667. */
  6668. Plane.prototype.normalize = function () {
  6669. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6670. var magnitude = 0.0;
  6671. if (norm !== 0) {
  6672. magnitude = 1.0 / norm;
  6673. }
  6674. this.normal.x *= magnitude;
  6675. this.normal.y *= magnitude;
  6676. this.normal.z *= magnitude;
  6677. this.d *= magnitude;
  6678. return this;
  6679. };
  6680. /**
  6681. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6682. */
  6683. Plane.prototype.transform = function (transformation) {
  6684. var transposedMatrix = Matrix.Transpose(transformation);
  6685. var x = this.normal.x;
  6686. var y = this.normal.y;
  6687. var z = this.normal.z;
  6688. var d = this.d;
  6689. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6690. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6691. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6692. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6693. return new Plane(normalX, normalY, normalZ, finalD);
  6694. };
  6695. /**
  6696. * Returns the dot product (float) of the point coordinates and the plane normal.
  6697. */
  6698. Plane.prototype.dotCoordinate = function (point) {
  6699. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6700. };
  6701. /**
  6702. * Updates the current Plane from the plane defined by the three given points.
  6703. * Returns the updated Plane.
  6704. */
  6705. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6706. var x1 = point2.x - point1.x;
  6707. var y1 = point2.y - point1.y;
  6708. var z1 = point2.z - point1.z;
  6709. var x2 = point3.x - point1.x;
  6710. var y2 = point3.y - point1.y;
  6711. var z2 = point3.z - point1.z;
  6712. var yz = (y1 * z2) - (z1 * y2);
  6713. var xz = (z1 * x2) - (x1 * z2);
  6714. var xy = (x1 * y2) - (y1 * x2);
  6715. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6716. var invPyth;
  6717. if (pyth !== 0) {
  6718. invPyth = 1.0 / pyth;
  6719. }
  6720. else {
  6721. invPyth = 0.0;
  6722. }
  6723. this.normal.x = yz * invPyth;
  6724. this.normal.y = xz * invPyth;
  6725. this.normal.z = xy * invPyth;
  6726. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6727. return this;
  6728. };
  6729. /**
  6730. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6731. */
  6732. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6733. var dot = Vector3.Dot(this.normal, direction);
  6734. return (dot <= epsilon);
  6735. };
  6736. /**
  6737. * Returns the signed distance (float) from the given point to the Plane.
  6738. */
  6739. Plane.prototype.signedDistanceTo = function (point) {
  6740. return Vector3.Dot(point, this.normal) + this.d;
  6741. };
  6742. // Statics
  6743. /**
  6744. * Returns a new Plane from the given array.
  6745. */
  6746. Plane.FromArray = function (array) {
  6747. return new Plane(array[0], array[1], array[2], array[3]);
  6748. };
  6749. /**
  6750. * Returns a new Plane defined by the three given points.
  6751. */
  6752. Plane.FromPoints = function (point1, point2, point3) {
  6753. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6754. result.copyFromPoints(point1, point2, point3);
  6755. return result;
  6756. };
  6757. /**
  6758. * Returns a new Plane the normal vector to this plane at the given origin point.
  6759. * Note : the vector "normal" is updated because normalized.
  6760. */
  6761. Plane.FromPositionAndNormal = function (origin, normal) {
  6762. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6763. normal.normalize();
  6764. result.normal = normal;
  6765. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6766. return result;
  6767. };
  6768. /**
  6769. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6770. */
  6771. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6772. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6773. return Vector3.Dot(point, normal) + d;
  6774. };
  6775. return Plane;
  6776. }());
  6777. BABYLON.Plane = Plane;
  6778. var Viewport = /** @class */ (function () {
  6779. /**
  6780. * Creates a Viewport object located at (x, y) and sized (width, height).
  6781. */
  6782. function Viewport(x, y, width, height) {
  6783. this.x = x;
  6784. this.y = y;
  6785. this.width = width;
  6786. this.height = height;
  6787. }
  6788. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6789. if (renderWidthOrEngine.getRenderWidth) {
  6790. var engine = renderWidthOrEngine;
  6791. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6792. }
  6793. var renderWidth = renderWidthOrEngine;
  6794. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6795. };
  6796. /**
  6797. * Returns a new Viewport copied from the current one.
  6798. */
  6799. Viewport.prototype.clone = function () {
  6800. return new Viewport(this.x, this.y, this.width, this.height);
  6801. };
  6802. return Viewport;
  6803. }());
  6804. BABYLON.Viewport = Viewport;
  6805. var Frustum = /** @class */ (function () {
  6806. function Frustum() {
  6807. }
  6808. /**
  6809. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6810. */
  6811. Frustum.GetPlanes = function (transform) {
  6812. var frustumPlanes = [];
  6813. for (var index = 0; index < 6; index++) {
  6814. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6815. }
  6816. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6817. return frustumPlanes;
  6818. };
  6819. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6820. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6821. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6822. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6823. frustumPlane.d = transform.m[15] + transform.m[14];
  6824. frustumPlane.normalize();
  6825. };
  6826. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6827. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6828. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6829. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6830. frustumPlane.d = transform.m[15] - transform.m[14];
  6831. frustumPlane.normalize();
  6832. };
  6833. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6834. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6835. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6836. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6837. frustumPlane.d = transform.m[15] + transform.m[12];
  6838. frustumPlane.normalize();
  6839. };
  6840. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6841. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6842. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6843. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6844. frustumPlane.d = transform.m[15] - transform.m[12];
  6845. frustumPlane.normalize();
  6846. };
  6847. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6848. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6849. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6850. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6851. frustumPlane.d = transform.m[15] - transform.m[13];
  6852. frustumPlane.normalize();
  6853. };
  6854. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6855. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6856. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6857. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6858. frustumPlane.d = transform.m[15] + transform.m[13];
  6859. frustumPlane.normalize();
  6860. };
  6861. /**
  6862. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6863. */
  6864. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6865. // Near
  6866. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6867. // Far
  6868. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6869. // Left
  6870. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6871. // Right
  6872. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6873. // Top
  6874. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6875. // Bottom
  6876. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6877. };
  6878. return Frustum;
  6879. }());
  6880. BABYLON.Frustum = Frustum;
  6881. /** Defines supported spaces */
  6882. var Space;
  6883. (function (Space) {
  6884. /** Local (object) space */
  6885. Space[Space["LOCAL"] = 0] = "LOCAL";
  6886. /** World space */
  6887. Space[Space["WORLD"] = 1] = "WORLD";
  6888. /** Bone space */
  6889. Space[Space["BONE"] = 2] = "BONE";
  6890. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6891. /** Defines the 3 main axes */
  6892. var Axis = /** @class */ (function () {
  6893. function Axis() {
  6894. }
  6895. /** X axis */
  6896. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6897. /** Y axis */
  6898. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6899. /** Z axis */
  6900. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6901. return Axis;
  6902. }());
  6903. BABYLON.Axis = Axis;
  6904. ;
  6905. var BezierCurve = /** @class */ (function () {
  6906. function BezierCurve() {
  6907. }
  6908. /**
  6909. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6910. */
  6911. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6912. // Extract X (which is equal to time here)
  6913. var f0 = 1 - 3 * x2 + 3 * x1;
  6914. var f1 = 3 * x2 - 6 * x1;
  6915. var f2 = 3 * x1;
  6916. var refinedT = t;
  6917. for (var i = 0; i < 5; i++) {
  6918. var refinedT2 = refinedT * refinedT;
  6919. var refinedT3 = refinedT2 * refinedT;
  6920. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6921. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6922. refinedT -= (x - t) * slope;
  6923. refinedT = Math.min(1, Math.max(0, refinedT));
  6924. }
  6925. // Resolve cubic bezier for the given x
  6926. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6927. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6928. Math.pow(refinedT, 3);
  6929. };
  6930. return BezierCurve;
  6931. }());
  6932. BABYLON.BezierCurve = BezierCurve;
  6933. /**
  6934. * Defines potential orientation for back face culling
  6935. */
  6936. var Orientation;
  6937. (function (Orientation) {
  6938. /**
  6939. * Clockwise
  6940. */
  6941. Orientation[Orientation["CW"] = 0] = "CW";
  6942. /** Counter clockwise */
  6943. Orientation[Orientation["CCW"] = 1] = "CCW";
  6944. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6945. /**
  6946. * Defines angle representation
  6947. */
  6948. var Angle = /** @class */ (function () {
  6949. /**
  6950. * Creates an Angle object of "radians" radians (float).
  6951. */
  6952. function Angle(radians) {
  6953. this._radians = radians;
  6954. if (this._radians < 0.0)
  6955. this._radians += (2.0 * Math.PI);
  6956. }
  6957. /**
  6958. * Get value in degrees
  6959. * @returns the Angle value in degrees (float)
  6960. */
  6961. Angle.prototype.degrees = function () {
  6962. return this._radians * 180.0 / Math.PI;
  6963. };
  6964. /**
  6965. * Get value in radians
  6966. * @returns the Angle value in radians (float)
  6967. */
  6968. Angle.prototype.radians = function () {
  6969. return this._radians;
  6970. };
  6971. /**
  6972. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6973. * @param a defines first vector
  6974. * @param b defines second vector
  6975. * @returns a new Angle
  6976. */
  6977. Angle.BetweenTwoPoints = function (a, b) {
  6978. var delta = b.subtract(a);
  6979. var theta = Math.atan2(delta.y, delta.x);
  6980. return new Angle(theta);
  6981. };
  6982. /**
  6983. * Gets a new Angle object from the given float in radians
  6984. * @param radians defines the angle value in radians
  6985. * @returns a new Angle
  6986. */
  6987. Angle.FromRadians = function (radians) {
  6988. return new Angle(radians);
  6989. };
  6990. /**
  6991. * Gets a new Angle object from the given float in degrees
  6992. * @param degrees defines the angle value in degrees
  6993. * @returns a new Angle
  6994. */
  6995. Angle.FromDegrees = function (degrees) {
  6996. return new Angle(degrees * Math.PI / 180.0);
  6997. };
  6998. return Angle;
  6999. }());
  7000. BABYLON.Angle = Angle;
  7001. var Arc2 = /** @class */ (function () {
  7002. /**
  7003. * Creates an Arc object from the three given points : start, middle and end.
  7004. */
  7005. function Arc2(startPoint, midPoint, endPoint) {
  7006. this.startPoint = startPoint;
  7007. this.midPoint = midPoint;
  7008. this.endPoint = endPoint;
  7009. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7010. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7011. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7012. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7013. 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);
  7014. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7015. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7016. var a1 = this.startAngle.degrees();
  7017. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7018. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7019. // angles correction
  7020. if (a2 - a1 > +180.0)
  7021. a2 -= 360.0;
  7022. if (a2 - a1 < -180.0)
  7023. a2 += 360.0;
  7024. if (a3 - a2 > +180.0)
  7025. a3 -= 360.0;
  7026. if (a3 - a2 < -180.0)
  7027. a3 += 360.0;
  7028. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7029. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7030. }
  7031. return Arc2;
  7032. }());
  7033. BABYLON.Arc2 = Arc2;
  7034. var Path2 = /** @class */ (function () {
  7035. /**
  7036. * Creates a Path2 object from the starting 2D coordinates x and y.
  7037. */
  7038. function Path2(x, y) {
  7039. this._points = new Array();
  7040. this._length = 0.0;
  7041. this.closed = false;
  7042. this._points.push(new Vector2(x, y));
  7043. }
  7044. /**
  7045. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7046. * Returns the updated Path2.
  7047. */
  7048. Path2.prototype.addLineTo = function (x, y) {
  7049. if (this.closed) {
  7050. return this;
  7051. }
  7052. var newPoint = new Vector2(x, y);
  7053. var previousPoint = this._points[this._points.length - 1];
  7054. this._points.push(newPoint);
  7055. this._length += newPoint.subtract(previousPoint).length();
  7056. return this;
  7057. };
  7058. /**
  7059. * 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.
  7060. * Returns the updated Path2.
  7061. */
  7062. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7063. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7064. if (this.closed) {
  7065. return this;
  7066. }
  7067. var startPoint = this._points[this._points.length - 1];
  7068. var midPoint = new Vector2(midX, midY);
  7069. var endPoint = new Vector2(endX, endY);
  7070. var arc = new Arc2(startPoint, midPoint, endPoint);
  7071. var increment = arc.angle.radians() / numberOfSegments;
  7072. if (arc.orientation === Orientation.CW)
  7073. increment *= -1;
  7074. var currentAngle = arc.startAngle.radians() + increment;
  7075. for (var i = 0; i < numberOfSegments; i++) {
  7076. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7077. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7078. this.addLineTo(x, y);
  7079. currentAngle += increment;
  7080. }
  7081. return this;
  7082. };
  7083. /**
  7084. * Closes the Path2.
  7085. * Returns the Path2.
  7086. */
  7087. Path2.prototype.close = function () {
  7088. this.closed = true;
  7089. return this;
  7090. };
  7091. /**
  7092. * Returns the Path2 total length (float).
  7093. */
  7094. Path2.prototype.length = function () {
  7095. var result = this._length;
  7096. if (!this.closed) {
  7097. var lastPoint = this._points[this._points.length - 1];
  7098. var firstPoint = this._points[0];
  7099. result += (firstPoint.subtract(lastPoint).length());
  7100. }
  7101. return result;
  7102. };
  7103. /**
  7104. * Returns the Path2 internal array of points.
  7105. */
  7106. Path2.prototype.getPoints = function () {
  7107. return this._points;
  7108. };
  7109. /**
  7110. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7111. */
  7112. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7113. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7114. return Vector2.Zero();
  7115. }
  7116. var lengthPosition = normalizedLengthPosition * this.length();
  7117. var previousOffset = 0;
  7118. for (var i = 0; i < this._points.length; i++) {
  7119. var j = (i + 1) % this._points.length;
  7120. var a = this._points[i];
  7121. var b = this._points[j];
  7122. var bToA = b.subtract(a);
  7123. var nextOffset = (bToA.length() + previousOffset);
  7124. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7125. var dir = bToA.normalize();
  7126. var localOffset = lengthPosition - previousOffset;
  7127. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7128. }
  7129. previousOffset = nextOffset;
  7130. }
  7131. return Vector2.Zero();
  7132. };
  7133. /**
  7134. * Returns a new Path2 starting at the coordinates (x, y).
  7135. */
  7136. Path2.StartingAt = function (x, y) {
  7137. return new Path2(x, y);
  7138. };
  7139. return Path2;
  7140. }());
  7141. BABYLON.Path2 = Path2;
  7142. var Path3D = /** @class */ (function () {
  7143. /**
  7144. * new Path3D(path, normal, raw)
  7145. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7146. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7147. * path : an array of Vector3, the curve axis of the Path3D
  7148. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7149. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7150. */
  7151. function Path3D(path, firstNormal, raw) {
  7152. if (firstNormal === void 0) { firstNormal = null; }
  7153. this.path = path;
  7154. this._curve = new Array();
  7155. this._distances = new Array();
  7156. this._tangents = new Array();
  7157. this._normals = new Array();
  7158. this._binormals = new Array();
  7159. for (var p = 0; p < path.length; p++) {
  7160. this._curve[p] = path[p].clone(); // hard copy
  7161. }
  7162. this._raw = raw || false;
  7163. this._compute(firstNormal);
  7164. }
  7165. /**
  7166. * Returns the Path3D array of successive Vector3 designing its curve.
  7167. */
  7168. Path3D.prototype.getCurve = function () {
  7169. return this._curve;
  7170. };
  7171. /**
  7172. * Returns an array populated with tangent vectors on each Path3D curve point.
  7173. */
  7174. Path3D.prototype.getTangents = function () {
  7175. return this._tangents;
  7176. };
  7177. /**
  7178. * Returns an array populated with normal vectors on each Path3D curve point.
  7179. */
  7180. Path3D.prototype.getNormals = function () {
  7181. return this._normals;
  7182. };
  7183. /**
  7184. * Returns an array populated with binormal vectors on each Path3D curve point.
  7185. */
  7186. Path3D.prototype.getBinormals = function () {
  7187. return this._binormals;
  7188. };
  7189. /**
  7190. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7191. */
  7192. Path3D.prototype.getDistances = function () {
  7193. return this._distances;
  7194. };
  7195. /**
  7196. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7197. * Returns the same object updated.
  7198. */
  7199. Path3D.prototype.update = function (path, firstNormal) {
  7200. if (firstNormal === void 0) { firstNormal = null; }
  7201. for (var p = 0; p < path.length; p++) {
  7202. this._curve[p].x = path[p].x;
  7203. this._curve[p].y = path[p].y;
  7204. this._curve[p].z = path[p].z;
  7205. }
  7206. this._compute(firstNormal);
  7207. return this;
  7208. };
  7209. // private function compute() : computes tangents, normals and binormals
  7210. Path3D.prototype._compute = function (firstNormal) {
  7211. var l = this._curve.length;
  7212. // first and last tangents
  7213. this._tangents[0] = this._getFirstNonNullVector(0);
  7214. if (!this._raw) {
  7215. this._tangents[0].normalize();
  7216. }
  7217. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7218. if (!this._raw) {
  7219. this._tangents[l - 1].normalize();
  7220. }
  7221. // normals and binormals at first point : arbitrary vector with _normalVector()
  7222. var tg0 = this._tangents[0];
  7223. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7224. this._normals[0] = pp0;
  7225. if (!this._raw) {
  7226. this._normals[0].normalize();
  7227. }
  7228. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7229. if (!this._raw) {
  7230. this._binormals[0].normalize();
  7231. }
  7232. this._distances[0] = 0.0;
  7233. // normals and binormals : next points
  7234. var prev; // previous vector (segment)
  7235. var cur; // current vector (segment)
  7236. var curTang; // current tangent
  7237. // previous normal
  7238. var prevBinor; // previous binormal
  7239. for (var i = 1; i < l; i++) {
  7240. // tangents
  7241. prev = this._getLastNonNullVector(i);
  7242. if (i < l - 1) {
  7243. cur = this._getFirstNonNullVector(i);
  7244. this._tangents[i] = prev.add(cur);
  7245. this._tangents[i].normalize();
  7246. }
  7247. this._distances[i] = this._distances[i - 1] + prev.length();
  7248. // normals and binormals
  7249. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7250. curTang = this._tangents[i];
  7251. prevBinor = this._binormals[i - 1];
  7252. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7253. if (!this._raw) {
  7254. this._normals[i].normalize();
  7255. }
  7256. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7257. if (!this._raw) {
  7258. this._binormals[i].normalize();
  7259. }
  7260. }
  7261. };
  7262. // private function getFirstNonNullVector(index)
  7263. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7264. Path3D.prototype._getFirstNonNullVector = function (index) {
  7265. var i = 1;
  7266. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7267. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7268. i++;
  7269. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7270. }
  7271. return nNVector;
  7272. };
  7273. // private function getLastNonNullVector(index)
  7274. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7275. Path3D.prototype._getLastNonNullVector = function (index) {
  7276. var i = 1;
  7277. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7278. while (nLVector.length() === 0 && index > i + 1) {
  7279. i++;
  7280. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7281. }
  7282. return nLVector;
  7283. };
  7284. // private function normalVector(v0, vt, va) :
  7285. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7286. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7287. Path3D.prototype._normalVector = function (v0, vt, va) {
  7288. var normal0;
  7289. var tgl = vt.length();
  7290. if (tgl === 0.0) {
  7291. tgl = 1.0;
  7292. }
  7293. if (va === undefined || va === null) {
  7294. var point;
  7295. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7296. point = new Vector3(0.0, -1.0, 0.0);
  7297. }
  7298. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7299. point = new Vector3(1.0, 0.0, 0.0);
  7300. }
  7301. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7302. point = new Vector3(0.0, 0.0, 1.0);
  7303. }
  7304. else {
  7305. point = Vector3.Zero();
  7306. }
  7307. normal0 = Vector3.Cross(vt, point);
  7308. }
  7309. else {
  7310. normal0 = Vector3.Cross(vt, va);
  7311. Vector3.CrossToRef(normal0, vt, normal0);
  7312. }
  7313. normal0.normalize();
  7314. return normal0;
  7315. };
  7316. return Path3D;
  7317. }());
  7318. BABYLON.Path3D = Path3D;
  7319. var Curve3 = /** @class */ (function () {
  7320. /**
  7321. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7322. * A Curve3 is designed from a series of successive Vector3.
  7323. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7324. */
  7325. function Curve3(points) {
  7326. this._length = 0.0;
  7327. this._points = points;
  7328. this._length = this._computeLength(points);
  7329. }
  7330. /**
  7331. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7332. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7333. * @param v1 (Vector3) the control point
  7334. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7335. * @param nbPoints (integer) the wanted number of points in the curve
  7336. */
  7337. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7338. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7339. var bez = new Array();
  7340. var equation = function (t, val0, val1, val2) {
  7341. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7342. return res;
  7343. };
  7344. for (var i = 0; i <= nbPoints; i++) {
  7345. 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)));
  7346. }
  7347. return new Curve3(bez);
  7348. };
  7349. /**
  7350. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7351. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7352. * @param v1 (Vector3) the first control point
  7353. * @param v2 (Vector3) the second control point
  7354. * @param v3 (Vector3) the end point of the Cubic Bezier
  7355. * @param nbPoints (integer) the wanted number of points in the curve
  7356. */
  7357. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7358. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7359. var bez = new Array();
  7360. var equation = function (t, val0, val1, val2, val3) {
  7361. 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;
  7362. return res;
  7363. };
  7364. for (var i = 0; i <= nbPoints; i++) {
  7365. 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)));
  7366. }
  7367. return new Curve3(bez);
  7368. };
  7369. /**
  7370. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7371. * @param p1 (Vector3) the origin point of the Hermite Spline
  7372. * @param t1 (Vector3) the tangent vector at the origin point
  7373. * @param p2 (Vector3) the end point of the Hermite Spline
  7374. * @param t2 (Vector3) the tangent vector at the end point
  7375. * @param nbPoints (integer) the wanted number of points in the curve
  7376. */
  7377. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7378. var hermite = new Array();
  7379. var step = 1.0 / nbPoints;
  7380. for (var i = 0; i <= nbPoints; i++) {
  7381. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7382. }
  7383. return new Curve3(hermite);
  7384. };
  7385. /**
  7386. * Returns a Curve3 object along a CatmullRom Spline curve :
  7387. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7388. * @param nbPoints (integer) the wanted number of points between each curve control points
  7389. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7390. */
  7391. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7392. var catmullRom = new Array();
  7393. var step = 1.0 / nbPoints;
  7394. var amount = 0.0;
  7395. if (closed) {
  7396. var pointsCount = points.length;
  7397. for (var i = 0; i < pointsCount; i++) {
  7398. amount = 0;
  7399. for (var c = 0; c < nbPoints; c++) {
  7400. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7401. amount += step;
  7402. }
  7403. }
  7404. catmullRom.push(catmullRom[0]);
  7405. }
  7406. else {
  7407. var totalPoints = new Array();
  7408. totalPoints.push(points[0].clone());
  7409. Array.prototype.push.apply(totalPoints, points);
  7410. totalPoints.push(points[points.length - 1].clone());
  7411. for (var i = 0; i < totalPoints.length - 3; i++) {
  7412. amount = 0;
  7413. for (var c = 0; c < nbPoints; c++) {
  7414. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7415. amount += step;
  7416. }
  7417. }
  7418. i--;
  7419. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7420. }
  7421. return new Curve3(catmullRom);
  7422. };
  7423. /**
  7424. * Returns the Curve3 stored array of successive Vector3
  7425. */
  7426. Curve3.prototype.getPoints = function () {
  7427. return this._points;
  7428. };
  7429. /**
  7430. * Returns the computed length (float) of the curve.
  7431. */
  7432. Curve3.prototype.length = function () {
  7433. return this._length;
  7434. };
  7435. /**
  7436. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7437. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7438. * curveA and curveB keep unchanged.
  7439. */
  7440. Curve3.prototype.continue = function (curve) {
  7441. var lastPoint = this._points[this._points.length - 1];
  7442. var continuedPoints = this._points.slice();
  7443. var curvePoints = curve.getPoints();
  7444. for (var i = 1; i < curvePoints.length; i++) {
  7445. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7446. }
  7447. var continuedCurve = new Curve3(continuedPoints);
  7448. return continuedCurve;
  7449. };
  7450. Curve3.prototype._computeLength = function (path) {
  7451. var l = 0;
  7452. for (var i = 1; i < path.length; i++) {
  7453. l += (path[i].subtract(path[i - 1])).length();
  7454. }
  7455. return l;
  7456. };
  7457. return Curve3;
  7458. }());
  7459. BABYLON.Curve3 = Curve3;
  7460. // Vertex formats
  7461. var PositionNormalVertex = /** @class */ (function () {
  7462. function PositionNormalVertex(position, normal) {
  7463. if (position === void 0) { position = Vector3.Zero(); }
  7464. if (normal === void 0) { normal = Vector3.Up(); }
  7465. this.position = position;
  7466. this.normal = normal;
  7467. }
  7468. PositionNormalVertex.prototype.clone = function () {
  7469. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7470. };
  7471. return PositionNormalVertex;
  7472. }());
  7473. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7474. var PositionNormalTextureVertex = /** @class */ (function () {
  7475. function PositionNormalTextureVertex(position, normal, uv) {
  7476. if (position === void 0) { position = Vector3.Zero(); }
  7477. if (normal === void 0) { normal = Vector3.Up(); }
  7478. if (uv === void 0) { uv = Vector2.Zero(); }
  7479. this.position = position;
  7480. this.normal = normal;
  7481. this.uv = uv;
  7482. }
  7483. PositionNormalTextureVertex.prototype.clone = function () {
  7484. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7485. };
  7486. return PositionNormalTextureVertex;
  7487. }());
  7488. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7489. // Temporary pre-allocated objects for engine internal use
  7490. // usage in any internal function :
  7491. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7492. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7493. var Tmp = /** @class */ (function () {
  7494. function Tmp() {
  7495. }
  7496. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7497. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7498. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7499. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7500. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7501. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7502. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7503. Matrix.Zero(), Matrix.Zero(),
  7504. Matrix.Zero(), Matrix.Zero(),
  7505. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7506. return Tmp;
  7507. }());
  7508. BABYLON.Tmp = Tmp;
  7509. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7510. var MathTmp = /** @class */ (function () {
  7511. function MathTmp() {
  7512. }
  7513. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7514. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7515. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7516. return MathTmp;
  7517. }());
  7518. })(BABYLON || (BABYLON = {}));
  7519. //# sourceMappingURL=babylon.math.js.map
  7520. var BABYLON;
  7521. (function (BABYLON) {
  7522. var Scalar = /** @class */ (function () {
  7523. function Scalar() {
  7524. }
  7525. /**
  7526. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7527. */
  7528. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7529. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7530. var num = a - b;
  7531. return -epsilon <= num && num <= epsilon;
  7532. };
  7533. /**
  7534. * Returns a string : the upper case translation of the number i to hexadecimal.
  7535. */
  7536. Scalar.ToHex = function (i) {
  7537. var str = i.toString(16);
  7538. if (i <= 15) {
  7539. return ("0" + str).toUpperCase();
  7540. }
  7541. return str.toUpperCase();
  7542. };
  7543. /**
  7544. * Returns -1 if value is negative and +1 is value is positive.
  7545. * Returns the value itself if it's equal to zero.
  7546. */
  7547. Scalar.Sign = function (value) {
  7548. value = +value; // convert to a number
  7549. if (value === 0 || isNaN(value))
  7550. return value;
  7551. return value > 0 ? 1 : -1;
  7552. };
  7553. /**
  7554. * Returns the value itself if it's between min and max.
  7555. * Returns min if the value is lower than min.
  7556. * Returns max if the value is greater than max.
  7557. */
  7558. Scalar.Clamp = function (value, min, max) {
  7559. if (min === void 0) { min = 0; }
  7560. if (max === void 0) { max = 1; }
  7561. return Math.min(max, Math.max(min, value));
  7562. };
  7563. /**
  7564. * Returns the log2 of value.
  7565. */
  7566. Scalar.Log2 = function (value) {
  7567. return Math.log(value) * Math.LOG2E;
  7568. };
  7569. /**
  7570. * Loops the value, so that it is never larger than length and never smaller than 0.
  7571. *
  7572. * This is similar to the modulo operator but it works with floating point numbers.
  7573. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7574. * With t = 5 and length = 2.5, the result would be 0.0.
  7575. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7576. */
  7577. Scalar.Repeat = function (value, length) {
  7578. return value - Math.floor(value / length) * length;
  7579. };
  7580. /**
  7581. * Normalize the value between 0.0 and 1.0 using min and max values
  7582. */
  7583. Scalar.Normalize = function (value, min, max) {
  7584. return (value - min) / (max - min);
  7585. };
  7586. /**
  7587. * Denormalize the value from 0.0 and 1.0 using min and max values
  7588. */
  7589. Scalar.Denormalize = function (normalized, min, max) {
  7590. return (normalized * (max - min) + min);
  7591. };
  7592. /**
  7593. * Calculates the shortest difference between two given angles given in degrees.
  7594. */
  7595. Scalar.DeltaAngle = function (current, target) {
  7596. var num = Scalar.Repeat(target - current, 360.0);
  7597. if (num > 180.0) {
  7598. num -= 360.0;
  7599. }
  7600. return num;
  7601. };
  7602. /**
  7603. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7604. *
  7605. * The returned value will move back and forth between 0 and length
  7606. */
  7607. Scalar.PingPong = function (tx, length) {
  7608. var t = Scalar.Repeat(tx, length * 2.0);
  7609. return length - Math.abs(t - length);
  7610. };
  7611. /**
  7612. * Interpolates between min and max with smoothing at the limits.
  7613. *
  7614. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7615. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7616. */
  7617. Scalar.SmoothStep = function (from, to, tx) {
  7618. var t = Scalar.Clamp(tx);
  7619. t = -2.0 * t * t * t + 3.0 * t * t;
  7620. return to * t + from * (1.0 - t);
  7621. };
  7622. /**
  7623. * Moves a value current towards target.
  7624. *
  7625. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7626. * Negative values of maxDelta pushes the value away from target.
  7627. */
  7628. Scalar.MoveTowards = function (current, target, maxDelta) {
  7629. var result = 0;
  7630. if (Math.abs(target - current) <= maxDelta) {
  7631. result = target;
  7632. }
  7633. else {
  7634. result = current + Scalar.Sign(target - current) * maxDelta;
  7635. }
  7636. return result;
  7637. };
  7638. /**
  7639. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7640. *
  7641. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7642. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7643. */
  7644. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7645. var num = Scalar.DeltaAngle(current, target);
  7646. var result = 0;
  7647. if (-maxDelta < num && num < maxDelta) {
  7648. result = target;
  7649. }
  7650. else {
  7651. target = current + num;
  7652. result = Scalar.MoveTowards(current, target, maxDelta);
  7653. }
  7654. return result;
  7655. };
  7656. /**
  7657. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7658. */
  7659. Scalar.Lerp = function (start, end, amount) {
  7660. return start + ((end - start) * amount);
  7661. };
  7662. /**
  7663. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7664. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7665. */
  7666. Scalar.LerpAngle = function (start, end, amount) {
  7667. var num = Scalar.Repeat(end - start, 360.0);
  7668. if (num > 180.0) {
  7669. num -= 360.0;
  7670. }
  7671. return start + num * Scalar.Clamp(amount);
  7672. };
  7673. /**
  7674. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7675. */
  7676. Scalar.InverseLerp = function (a, b, value) {
  7677. var result = 0;
  7678. if (a != b) {
  7679. result = Scalar.Clamp((value - a) / (b - a));
  7680. }
  7681. else {
  7682. result = 0.0;
  7683. }
  7684. return result;
  7685. };
  7686. /**
  7687. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7688. */
  7689. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7690. var squared = amount * amount;
  7691. var cubed = amount * squared;
  7692. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7693. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7694. var part3 = (cubed - (2.0 * squared)) + amount;
  7695. var part4 = cubed - squared;
  7696. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7697. };
  7698. /**
  7699. * Returns a random float number between and min and max values
  7700. */
  7701. Scalar.RandomRange = function (min, max) {
  7702. if (min === max)
  7703. return min;
  7704. return ((Math.random() * (max - min)) + min);
  7705. };
  7706. /**
  7707. * This function returns percentage of a number in a given range.
  7708. *
  7709. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7710. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7711. */
  7712. Scalar.RangeToPercent = function (number, min, max) {
  7713. return ((number - min) / (max - min));
  7714. };
  7715. /**
  7716. * This function returns number that corresponds to the percentage in a given range.
  7717. *
  7718. * PercentToRange(0.34,0,100) will return 34.
  7719. */
  7720. Scalar.PercentToRange = function (percent, min, max) {
  7721. return ((max - min) * percent + min);
  7722. };
  7723. /**
  7724. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7725. * @param angle The angle to normalize in radian.
  7726. * @return The converted angle.
  7727. */
  7728. Scalar.NormalizeRadians = function (angle) {
  7729. // More precise but slower version kept for reference.
  7730. // angle = angle % Tools.TwoPi;
  7731. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7732. //if (angle > Math.PI) {
  7733. // angle -= Tools.TwoPi;
  7734. //}
  7735. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7736. return angle;
  7737. };
  7738. /**
  7739. * Two pi constants convenient for computation.
  7740. */
  7741. Scalar.TwoPi = Math.PI * 2;
  7742. return Scalar;
  7743. }());
  7744. BABYLON.Scalar = Scalar;
  7745. })(BABYLON || (BABYLON = {}));
  7746. //# sourceMappingURL=babylon.math.scalar.js.map
  7747. //# sourceMappingURL=babylon.mixins.js.map
  7748. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7749. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7750. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7751. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7752. //# sourceMappingURL=babylon.webgl2.js.map
  7753. var BABYLON;
  7754. (function (BABYLON) {
  7755. var __decoratorInitialStore = {};
  7756. var __mergedStore = {};
  7757. var _copySource = function (creationFunction, source, instanciate) {
  7758. var destination = creationFunction();
  7759. // Tags
  7760. if (BABYLON.Tags) {
  7761. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7762. }
  7763. var classStore = getMergedStore(destination);
  7764. // Properties
  7765. for (var property in classStore) {
  7766. var propertyDescriptor = classStore[property];
  7767. var sourceProperty = source[property];
  7768. var propertyType = propertyDescriptor.type;
  7769. if (sourceProperty !== undefined && sourceProperty !== null) {
  7770. switch (propertyType) {
  7771. case 0: // Value
  7772. case 6: // Mesh reference
  7773. case 11: // Camera reference
  7774. destination[property] = sourceProperty;
  7775. break;
  7776. case 1: // Texture
  7777. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7778. break;
  7779. case 2: // Color3
  7780. case 3: // FresnelParameters
  7781. case 4: // Vector2
  7782. case 5: // Vector3
  7783. case 7: // Color Curves
  7784. case 10: // Quaternion
  7785. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7786. break;
  7787. }
  7788. }
  7789. }
  7790. return destination;
  7791. };
  7792. function getDirectStore(target) {
  7793. var classKey = target.getClassName();
  7794. if (!__decoratorInitialStore[classKey]) {
  7795. __decoratorInitialStore[classKey] = {};
  7796. }
  7797. return __decoratorInitialStore[classKey];
  7798. }
  7799. /**
  7800. * Return the list of properties flagged as serializable
  7801. * @param target: host object
  7802. */
  7803. function getMergedStore(target) {
  7804. var classKey = target.getClassName();
  7805. if (__mergedStore[classKey]) {
  7806. return __mergedStore[classKey];
  7807. }
  7808. __mergedStore[classKey] = {};
  7809. var store = __mergedStore[classKey];
  7810. var currentTarget = target;
  7811. var currentKey = classKey;
  7812. while (currentKey) {
  7813. var initialStore = __decoratorInitialStore[currentKey];
  7814. for (var property in initialStore) {
  7815. store[property] = initialStore[property];
  7816. }
  7817. var parent_1 = void 0;
  7818. var done = false;
  7819. do {
  7820. parent_1 = Object.getPrototypeOf(currentTarget);
  7821. if (!parent_1.getClassName) {
  7822. done = true;
  7823. break;
  7824. }
  7825. if (parent_1.getClassName() !== currentKey) {
  7826. break;
  7827. }
  7828. currentTarget = parent_1;
  7829. } while (parent_1);
  7830. if (done) {
  7831. break;
  7832. }
  7833. currentKey = parent_1.getClassName();
  7834. currentTarget = parent_1;
  7835. }
  7836. return store;
  7837. }
  7838. function generateSerializableMember(type, sourceName) {
  7839. return function (target, propertyKey) {
  7840. var classStore = getDirectStore(target);
  7841. if (!classStore[propertyKey]) {
  7842. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7843. }
  7844. };
  7845. }
  7846. function generateExpandMember(setCallback, targetKey) {
  7847. if (targetKey === void 0) { targetKey = null; }
  7848. return function (target, propertyKey) {
  7849. var key = targetKey || ("_" + propertyKey);
  7850. Object.defineProperty(target, propertyKey, {
  7851. get: function () {
  7852. return this[key];
  7853. },
  7854. set: function (value) {
  7855. if (this[key] === value) {
  7856. return;
  7857. }
  7858. this[key] = value;
  7859. target[setCallback].apply(this);
  7860. },
  7861. enumerable: true,
  7862. configurable: true
  7863. });
  7864. };
  7865. }
  7866. function expandToProperty(callback, targetKey) {
  7867. if (targetKey === void 0) { targetKey = null; }
  7868. return generateExpandMember(callback, targetKey);
  7869. }
  7870. BABYLON.expandToProperty = expandToProperty;
  7871. function serialize(sourceName) {
  7872. return generateSerializableMember(0, sourceName); // value member
  7873. }
  7874. BABYLON.serialize = serialize;
  7875. function serializeAsTexture(sourceName) {
  7876. return generateSerializableMember(1, sourceName); // texture member
  7877. }
  7878. BABYLON.serializeAsTexture = serializeAsTexture;
  7879. function serializeAsColor3(sourceName) {
  7880. return generateSerializableMember(2, sourceName); // color3 member
  7881. }
  7882. BABYLON.serializeAsColor3 = serializeAsColor3;
  7883. function serializeAsFresnelParameters(sourceName) {
  7884. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7885. }
  7886. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7887. function serializeAsVector2(sourceName) {
  7888. return generateSerializableMember(4, sourceName); // vector2 member
  7889. }
  7890. BABYLON.serializeAsVector2 = serializeAsVector2;
  7891. function serializeAsVector3(sourceName) {
  7892. return generateSerializableMember(5, sourceName); // vector3 member
  7893. }
  7894. BABYLON.serializeAsVector3 = serializeAsVector3;
  7895. function serializeAsMeshReference(sourceName) {
  7896. return generateSerializableMember(6, sourceName); // mesh reference member
  7897. }
  7898. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7899. function serializeAsColorCurves(sourceName) {
  7900. return generateSerializableMember(7, sourceName); // color curves
  7901. }
  7902. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7903. function serializeAsColor4(sourceName) {
  7904. return generateSerializableMember(8, sourceName); // color 4
  7905. }
  7906. BABYLON.serializeAsColor4 = serializeAsColor4;
  7907. function serializeAsImageProcessingConfiguration(sourceName) {
  7908. return generateSerializableMember(9, sourceName); // image processing
  7909. }
  7910. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7911. function serializeAsQuaternion(sourceName) {
  7912. return generateSerializableMember(10, sourceName); // quaternion member
  7913. }
  7914. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7915. /**
  7916. * Decorator used to define property that can be serialized as reference to a camera
  7917. * @param sourceName defines the name of the property to decorate
  7918. */
  7919. function serializeAsCameraReference(sourceName) {
  7920. return generateSerializableMember(11, sourceName); // camera reference member
  7921. }
  7922. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7923. var SerializationHelper = /** @class */ (function () {
  7924. function SerializationHelper() {
  7925. }
  7926. SerializationHelper.Serialize = function (entity, serializationObject) {
  7927. if (!serializationObject) {
  7928. serializationObject = {};
  7929. }
  7930. // Tags
  7931. if (BABYLON.Tags) {
  7932. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7933. }
  7934. var serializedProperties = getMergedStore(entity);
  7935. // Properties
  7936. for (var property in serializedProperties) {
  7937. var propertyDescriptor = serializedProperties[property];
  7938. var targetPropertyName = propertyDescriptor.sourceName || property;
  7939. var propertyType = propertyDescriptor.type;
  7940. var sourceProperty = entity[property];
  7941. if (sourceProperty !== undefined && sourceProperty !== null) {
  7942. switch (propertyType) {
  7943. case 0: // Value
  7944. serializationObject[targetPropertyName] = sourceProperty;
  7945. break;
  7946. case 1: // Texture
  7947. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7948. break;
  7949. case 2: // Color3
  7950. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7951. break;
  7952. case 3: // FresnelParameters
  7953. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7954. break;
  7955. case 4: // Vector2
  7956. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7957. break;
  7958. case 5: // Vector3
  7959. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7960. break;
  7961. case 6: // Mesh reference
  7962. serializationObject[targetPropertyName] = sourceProperty.id;
  7963. break;
  7964. case 7: // Color Curves
  7965. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7966. break;
  7967. case 8: // Color 4
  7968. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7969. break;
  7970. case 9: // Image Processing
  7971. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7972. break;
  7973. case 10: // Quaternion
  7974. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7975. break;
  7976. case 11: // Camera reference
  7977. serializationObject[targetPropertyName] = sourceProperty.id;
  7978. break;
  7979. }
  7980. }
  7981. }
  7982. return serializationObject;
  7983. };
  7984. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7985. if (rootUrl === void 0) { rootUrl = null; }
  7986. var destination = creationFunction();
  7987. if (!rootUrl) {
  7988. rootUrl = "";
  7989. }
  7990. // Tags
  7991. if (BABYLON.Tags) {
  7992. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7993. }
  7994. var classStore = getMergedStore(destination);
  7995. // Properties
  7996. for (var property in classStore) {
  7997. var propertyDescriptor = classStore[property];
  7998. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7999. var propertyType = propertyDescriptor.type;
  8000. if (sourceProperty !== undefined && sourceProperty !== null) {
  8001. var dest = destination;
  8002. switch (propertyType) {
  8003. case 0: // Value
  8004. dest[property] = sourceProperty;
  8005. break;
  8006. case 1: // Texture
  8007. if (scene) {
  8008. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8009. }
  8010. break;
  8011. case 2: // Color3
  8012. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8013. break;
  8014. case 3: // FresnelParameters
  8015. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8016. break;
  8017. case 4: // Vector2
  8018. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8019. break;
  8020. case 5: // Vector3
  8021. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8022. break;
  8023. case 6: // Mesh reference
  8024. if (scene) {
  8025. dest[property] = scene.getLastMeshByID(sourceProperty);
  8026. }
  8027. break;
  8028. case 7: // Color Curves
  8029. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8030. break;
  8031. case 8: // Color 4
  8032. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8033. break;
  8034. case 9: // Image Processing
  8035. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8036. break;
  8037. case 10: // Quaternion
  8038. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8039. break;
  8040. case 11: // Camera reference
  8041. if (scene) {
  8042. dest[property] = scene.getCameraByID(sourceProperty);
  8043. }
  8044. break;
  8045. }
  8046. }
  8047. }
  8048. return destination;
  8049. };
  8050. SerializationHelper.Clone = function (creationFunction, source) {
  8051. return _copySource(creationFunction, source, false);
  8052. };
  8053. SerializationHelper.Instanciate = function (creationFunction, source) {
  8054. return _copySource(creationFunction, source, true);
  8055. };
  8056. return SerializationHelper;
  8057. }());
  8058. BABYLON.SerializationHelper = SerializationHelper;
  8059. })(BABYLON || (BABYLON = {}));
  8060. //# sourceMappingURL=babylon.decorators.js.map
  8061. var BABYLON;
  8062. (function (BABYLON) {
  8063. /**
  8064. * Wrapper class for promise with external resolve and reject.
  8065. */
  8066. var Deferred = /** @class */ (function () {
  8067. /**
  8068. * Constructor for this deferred object.
  8069. */
  8070. function Deferred() {
  8071. var _this = this;
  8072. this.promise = new Promise(function (resolve, reject) {
  8073. _this._resolve = resolve;
  8074. _this._reject = reject;
  8075. });
  8076. }
  8077. Object.defineProperty(Deferred.prototype, "resolve", {
  8078. /**
  8079. * The resolve method of the promise associated with this deferred object.
  8080. */
  8081. get: function () {
  8082. return this._resolve;
  8083. },
  8084. enumerable: true,
  8085. configurable: true
  8086. });
  8087. Object.defineProperty(Deferred.prototype, "reject", {
  8088. /**
  8089. * The reject method of the promise associated with this deferred object.
  8090. */
  8091. get: function () {
  8092. return this._reject;
  8093. },
  8094. enumerable: true,
  8095. configurable: true
  8096. });
  8097. return Deferred;
  8098. }());
  8099. BABYLON.Deferred = Deferred;
  8100. })(BABYLON || (BABYLON = {}));
  8101. //# sourceMappingURL=babylon.deferred.js.map
  8102. var BABYLON;
  8103. (function (BABYLON) {
  8104. /**
  8105. * A class serves as a medium between the observable and its observers
  8106. */
  8107. var EventState = /** @class */ (function () {
  8108. /**
  8109. * Create a new EventState
  8110. * @param mask defines the mask associated with this state
  8111. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8112. * @param target defines the original target of the state
  8113. * @param currentTarget defines the current target of the state
  8114. */
  8115. function EventState(mask, skipNextObservers, target, currentTarget) {
  8116. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8117. this.initalize(mask, skipNextObservers, target, currentTarget);
  8118. }
  8119. /**
  8120. * Initialize the current event state
  8121. * @param mask defines the mask associated with this state
  8122. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8123. * @param target defines the original target of the state
  8124. * @param currentTarget defines the current target of the state
  8125. * @returns the current event state
  8126. */
  8127. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8128. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8129. this.mask = mask;
  8130. this.skipNextObservers = skipNextObservers;
  8131. this.target = target;
  8132. this.currentTarget = currentTarget;
  8133. return this;
  8134. };
  8135. return EventState;
  8136. }());
  8137. BABYLON.EventState = EventState;
  8138. /**
  8139. * Represent an Observer registered to a given Observable object.
  8140. */
  8141. var Observer = /** @class */ (function () {
  8142. /**
  8143. * Creates a new observer
  8144. * @param callback defines the callback to call when the observer is notified
  8145. * @param mask defines the mask of the observer (used to filter notifications)
  8146. * @param scope defines the current scope used to restore the JS context
  8147. */
  8148. function Observer(
  8149. /**
  8150. * Defines the callback to call when the observer is notified
  8151. */
  8152. callback,
  8153. /**
  8154. * Defines the mask of the observer (used to filter notifications)
  8155. */
  8156. mask,
  8157. /**
  8158. * Defines the current scope used to restore the JS context
  8159. */
  8160. scope) {
  8161. if (scope === void 0) { scope = null; }
  8162. this.callback = callback;
  8163. this.mask = mask;
  8164. this.scope = scope;
  8165. /** @hidden */
  8166. this._willBeUnregistered = false;
  8167. /**
  8168. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8169. */
  8170. this.unregisterOnNextCall = false;
  8171. }
  8172. return Observer;
  8173. }());
  8174. BABYLON.Observer = Observer;
  8175. /**
  8176. * Represent a list of observers registered to multiple Observables object.
  8177. */
  8178. var MultiObserver = /** @class */ (function () {
  8179. function MultiObserver() {
  8180. }
  8181. /**
  8182. * Release associated resources
  8183. */
  8184. MultiObserver.prototype.dispose = function () {
  8185. if (this._observers && this._observables) {
  8186. for (var index = 0; index < this._observers.length; index++) {
  8187. this._observables[index].remove(this._observers[index]);
  8188. }
  8189. }
  8190. this._observers = null;
  8191. this._observables = null;
  8192. };
  8193. /**
  8194. * Raise a callback when one of the observable will notify
  8195. * @param observables defines a list of observables to watch
  8196. * @param callback defines the callback to call on notification
  8197. * @param mask defines the mask used to filter notifications
  8198. * @param scope defines the current scope used to restore the JS context
  8199. * @returns the new MultiObserver
  8200. */
  8201. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8202. if (mask === void 0) { mask = -1; }
  8203. if (scope === void 0) { scope = null; }
  8204. var result = new MultiObserver();
  8205. result._observers = new Array();
  8206. result._observables = observables;
  8207. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8208. var observable = observables_1[_i];
  8209. var observer = observable.add(callback, mask, false, scope);
  8210. if (observer) {
  8211. result._observers.push(observer);
  8212. }
  8213. }
  8214. return result;
  8215. };
  8216. return MultiObserver;
  8217. }());
  8218. BABYLON.MultiObserver = MultiObserver;
  8219. /**
  8220. * The Observable class is a simple implementation of the Observable pattern.
  8221. *
  8222. * 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.
  8223. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8224. * 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).
  8225. * 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.
  8226. */
  8227. var Observable = /** @class */ (function () {
  8228. /**
  8229. * Creates a new observable
  8230. * @param onObserverAdded defines a callback to call when a new observer is added
  8231. */
  8232. function Observable(onObserverAdded) {
  8233. this._observers = new Array();
  8234. this._eventState = new EventState(0);
  8235. if (onObserverAdded) {
  8236. this._onObserverAdded = onObserverAdded;
  8237. }
  8238. }
  8239. /**
  8240. * Create a new Observer with the specified callback
  8241. * @param callback the callback that will be executed for that Observer
  8242. * @param mask the mask used to filter observers
  8243. * @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.
  8244. * @param scope optional scope for the callback to be called from
  8245. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8246. * @returns the new observer created for the callback
  8247. */
  8248. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8249. if (mask === void 0) { mask = -1; }
  8250. if (insertFirst === void 0) { insertFirst = false; }
  8251. if (scope === void 0) { scope = null; }
  8252. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8253. if (!callback) {
  8254. return null;
  8255. }
  8256. var observer = new Observer(callback, mask, scope);
  8257. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8258. if (insertFirst) {
  8259. this._observers.unshift(observer);
  8260. }
  8261. else {
  8262. this._observers.push(observer);
  8263. }
  8264. if (this._onObserverAdded) {
  8265. this._onObserverAdded(observer);
  8266. }
  8267. return observer;
  8268. };
  8269. /**
  8270. * Create a new Observer with the specified callback and unregisters after the next notification
  8271. * @param callback the callback that will be executed for that Observer
  8272. * @returns the new observer created for the callback
  8273. */
  8274. Observable.prototype.addOnce = function (callback) {
  8275. return this.add(callback, undefined, undefined, undefined, true);
  8276. };
  8277. /**
  8278. * Remove an Observer from the Observable object
  8279. * @param observer the instance of the Observer to remove
  8280. * @returns false if it doesn't belong to this Observable
  8281. */
  8282. Observable.prototype.remove = function (observer) {
  8283. if (!observer) {
  8284. return false;
  8285. }
  8286. var index = this._observers.indexOf(observer);
  8287. if (index !== -1) {
  8288. this._observers.splice(index, 1);
  8289. return true;
  8290. }
  8291. return false;
  8292. };
  8293. /**
  8294. * Remove a callback from the Observable object
  8295. * @param callback the callback to remove
  8296. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8297. * @returns false if it doesn't belong to this Observable
  8298. */
  8299. Observable.prototype.removeCallback = function (callback, scope) {
  8300. for (var index = 0; index < this._observers.length; index++) {
  8301. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8302. this._observers.splice(index, 1);
  8303. return true;
  8304. }
  8305. }
  8306. return false;
  8307. };
  8308. Observable.prototype._deferUnregister = function (observer) {
  8309. var _this = this;
  8310. observer.unregisterOnNextCall = false;
  8311. observer._willBeUnregistered = true;
  8312. BABYLON.Tools.SetImmediate(function () {
  8313. _this.remove(observer);
  8314. });
  8315. };
  8316. /**
  8317. * Notify all Observers by calling their respective callback with the given data
  8318. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8319. * @param eventData defines the data to send to all observers
  8320. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8321. * @param target defines the original target of the state
  8322. * @param currentTarget defines the current target of the state
  8323. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8324. */
  8325. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8326. if (mask === void 0) { mask = -1; }
  8327. if (!this._observers.length) {
  8328. return true;
  8329. }
  8330. var state = this._eventState;
  8331. state.mask = mask;
  8332. state.target = target;
  8333. state.currentTarget = currentTarget;
  8334. state.skipNextObservers = false;
  8335. state.lastReturnValue = eventData;
  8336. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8337. var obs = _a[_i];
  8338. if (obs._willBeUnregistered) {
  8339. continue;
  8340. }
  8341. if (obs.mask & mask) {
  8342. if (obs.scope) {
  8343. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8344. }
  8345. else {
  8346. state.lastReturnValue = obs.callback(eventData, state);
  8347. }
  8348. if (obs.unregisterOnNextCall) {
  8349. this._deferUnregister(obs);
  8350. }
  8351. }
  8352. if (state.skipNextObservers) {
  8353. return false;
  8354. }
  8355. }
  8356. return true;
  8357. };
  8358. /**
  8359. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8360. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8361. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8362. * and it is crucial that all callbacks will be executed.
  8363. * The order of the callbacks is kept, callbacks are not executed parallel.
  8364. *
  8365. * @param eventData The data to be sent to each callback
  8366. * @param mask is used to filter observers defaults to -1
  8367. * @param target defines the callback target (see EventState)
  8368. * @param currentTarget defines he current object in the bubbling phase
  8369. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8370. */
  8371. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8372. var _this = this;
  8373. if (mask === void 0) { mask = -1; }
  8374. // create an empty promise
  8375. var p = Promise.resolve(eventData);
  8376. // no observers? return this promise.
  8377. if (!this._observers.length) {
  8378. return p;
  8379. }
  8380. var state = this._eventState;
  8381. state.mask = mask;
  8382. state.target = target;
  8383. state.currentTarget = currentTarget;
  8384. state.skipNextObservers = false;
  8385. // execute one callback after another (not using Promise.all, the order is important)
  8386. this._observers.forEach(function (obs) {
  8387. if (state.skipNextObservers) {
  8388. return;
  8389. }
  8390. if (obs._willBeUnregistered) {
  8391. return;
  8392. }
  8393. if (obs.mask & mask) {
  8394. if (obs.scope) {
  8395. p = p.then(function (lastReturnedValue) {
  8396. state.lastReturnValue = lastReturnedValue;
  8397. return obs.callback.apply(obs.scope, [eventData, state]);
  8398. });
  8399. }
  8400. else {
  8401. p = p.then(function (lastReturnedValue) {
  8402. state.lastReturnValue = lastReturnedValue;
  8403. return obs.callback(eventData, state);
  8404. });
  8405. }
  8406. if (obs.unregisterOnNextCall) {
  8407. _this._deferUnregister(obs);
  8408. }
  8409. }
  8410. });
  8411. // return the eventData
  8412. return p.then(function () { return eventData; });
  8413. };
  8414. /**
  8415. * Notify a specific observer
  8416. * @param observer defines the observer to notify
  8417. * @param eventData defines the data to be sent to each callback
  8418. * @param mask is used to filter observers defaults to -1
  8419. */
  8420. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8421. if (mask === void 0) { mask = -1; }
  8422. var state = this._eventState;
  8423. state.mask = mask;
  8424. state.skipNextObservers = false;
  8425. observer.callback(eventData, state);
  8426. };
  8427. /**
  8428. * Gets a boolean indicating if the observable has at least one observer
  8429. * @returns true is the Observable has at least one Observer registered
  8430. */
  8431. Observable.prototype.hasObservers = function () {
  8432. return this._observers.length > 0;
  8433. };
  8434. /**
  8435. * Clear the list of observers
  8436. */
  8437. Observable.prototype.clear = function () {
  8438. this._observers = new Array();
  8439. this._onObserverAdded = null;
  8440. };
  8441. /**
  8442. * Clone the current observable
  8443. * @returns a new observable
  8444. */
  8445. Observable.prototype.clone = function () {
  8446. var result = new Observable();
  8447. result._observers = this._observers.slice(0);
  8448. return result;
  8449. };
  8450. /**
  8451. * Does this observable handles observer registered with a given mask
  8452. * @param mask defines the mask to be tested
  8453. * @return whether or not one observer registered with the given mask is handeled
  8454. **/
  8455. Observable.prototype.hasSpecificMask = function (mask) {
  8456. if (mask === void 0) { mask = -1; }
  8457. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8458. var obs = _a[_i];
  8459. if (obs.mask & mask || obs.mask === mask) {
  8460. return true;
  8461. }
  8462. }
  8463. return false;
  8464. };
  8465. return Observable;
  8466. }());
  8467. BABYLON.Observable = Observable;
  8468. })(BABYLON || (BABYLON = {}));
  8469. //# sourceMappingURL=babylon.observable.js.map
  8470. var BABYLON;
  8471. (function (BABYLON) {
  8472. var SmartArray = /** @class */ (function () {
  8473. function SmartArray(capacity) {
  8474. this.length = 0;
  8475. this.data = new Array(capacity);
  8476. this._id = SmartArray._GlobalId++;
  8477. }
  8478. SmartArray.prototype.push = function (value) {
  8479. this.data[this.length++] = value;
  8480. if (this.length > this.data.length) {
  8481. this.data.length *= 2;
  8482. }
  8483. };
  8484. SmartArray.prototype.forEach = function (func) {
  8485. for (var index = 0; index < this.length; index++) {
  8486. func(this.data[index]);
  8487. }
  8488. };
  8489. SmartArray.prototype.sort = function (compareFn) {
  8490. this.data.sort(compareFn);
  8491. };
  8492. SmartArray.prototype.reset = function () {
  8493. this.length = 0;
  8494. };
  8495. SmartArray.prototype.dispose = function () {
  8496. this.reset();
  8497. if (this.data) {
  8498. this.data.length = 0;
  8499. this.data = [];
  8500. }
  8501. };
  8502. SmartArray.prototype.concat = function (array) {
  8503. if (array.length === 0) {
  8504. return;
  8505. }
  8506. if (this.length + array.length > this.data.length) {
  8507. this.data.length = (this.length + array.length) * 2;
  8508. }
  8509. for (var index = 0; index < array.length; index++) {
  8510. this.data[this.length++] = (array.data || array)[index];
  8511. }
  8512. };
  8513. SmartArray.prototype.indexOf = function (value) {
  8514. var position = this.data.indexOf(value);
  8515. if (position >= this.length) {
  8516. return -1;
  8517. }
  8518. return position;
  8519. };
  8520. SmartArray.prototype.contains = function (value) {
  8521. return this.data.indexOf(value) !== -1;
  8522. };
  8523. // Statics
  8524. SmartArray._GlobalId = 0;
  8525. return SmartArray;
  8526. }());
  8527. BABYLON.SmartArray = SmartArray;
  8528. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8529. __extends(SmartArrayNoDuplicate, _super);
  8530. function SmartArrayNoDuplicate() {
  8531. var _this = _super !== null && _super.apply(this, arguments) || this;
  8532. _this._duplicateId = 0;
  8533. return _this;
  8534. }
  8535. SmartArrayNoDuplicate.prototype.push = function (value) {
  8536. _super.prototype.push.call(this, value);
  8537. if (!value.__smartArrayFlags) {
  8538. value.__smartArrayFlags = {};
  8539. }
  8540. value.__smartArrayFlags[this._id] = this._duplicateId;
  8541. };
  8542. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8543. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8544. return false;
  8545. }
  8546. this.push(value);
  8547. return true;
  8548. };
  8549. SmartArrayNoDuplicate.prototype.reset = function () {
  8550. _super.prototype.reset.call(this);
  8551. this._duplicateId++;
  8552. };
  8553. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8554. if (array.length === 0) {
  8555. return;
  8556. }
  8557. if (this.length + array.length > this.data.length) {
  8558. this.data.length = (this.length + array.length) * 2;
  8559. }
  8560. for (var index = 0; index < array.length; index++) {
  8561. var item = (array.data || array)[index];
  8562. this.pushNoDuplicate(item);
  8563. }
  8564. };
  8565. return SmartArrayNoDuplicate;
  8566. }(SmartArray));
  8567. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8568. })(BABYLON || (BABYLON = {}));
  8569. //# sourceMappingURL=babylon.smartArray.js.map
  8570. var BABYLON;
  8571. (function (BABYLON) {
  8572. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8573. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8574. var LoadFileError = /** @class */ (function (_super) {
  8575. __extends(LoadFileError, _super);
  8576. function LoadFileError(message, request) {
  8577. var _this = _super.call(this, message) || this;
  8578. _this.request = request;
  8579. _this.name = "LoadFileError";
  8580. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8581. return _this;
  8582. }
  8583. // Polyfill for Object.setPrototypeOf if necessary.
  8584. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8585. return LoadFileError;
  8586. }(Error));
  8587. BABYLON.LoadFileError = LoadFileError;
  8588. var RetryStrategy = /** @class */ (function () {
  8589. function RetryStrategy() {
  8590. }
  8591. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8592. if (maxRetries === void 0) { maxRetries = 3; }
  8593. if (baseInterval === void 0) { baseInterval = 500; }
  8594. return function (url, request, retryIndex) {
  8595. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8596. return -1;
  8597. }
  8598. return Math.pow(2, retryIndex) * baseInterval;
  8599. };
  8600. };
  8601. return RetryStrategy;
  8602. }());
  8603. BABYLON.RetryStrategy = RetryStrategy;
  8604. // Screenshots
  8605. var screenshotCanvas;
  8606. var cloneValue = function (source, destinationObject) {
  8607. if (!source)
  8608. return null;
  8609. if (source instanceof BABYLON.Mesh) {
  8610. return null;
  8611. }
  8612. if (source instanceof BABYLON.SubMesh) {
  8613. return source.clone(destinationObject);
  8614. }
  8615. else if (source.clone) {
  8616. return source.clone();
  8617. }
  8618. return null;
  8619. };
  8620. var Tools = /** @class */ (function () {
  8621. function Tools() {
  8622. }
  8623. /**
  8624. * Interpolates between a and b via alpha
  8625. * @param a The lower value (returned when alpha = 0)
  8626. * @param b The upper value (returned when alpha = 1)
  8627. * @param alpha The interpolation-factor
  8628. * @return The mixed value
  8629. */
  8630. Tools.Mix = function (a, b, alpha) {
  8631. return a * (1 - alpha) + b * alpha;
  8632. };
  8633. Tools.Instantiate = function (className) {
  8634. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8635. return Tools.RegisteredExternalClasses[className];
  8636. }
  8637. var arr = className.split(".");
  8638. var fn = (window || this);
  8639. for (var i = 0, len = arr.length; i < len; i++) {
  8640. fn = fn[arr[i]];
  8641. }
  8642. if (typeof fn !== "function") {
  8643. return null;
  8644. }
  8645. return fn;
  8646. };
  8647. /**
  8648. * Provides a slice function that will work even on IE
  8649. * @param data defines the array to slice
  8650. * @param start defines the start of the data (optional)
  8651. * @param end defines the end of the data (optional)
  8652. * @returns the new sliced array
  8653. */
  8654. Tools.Slice = function (data, start, end) {
  8655. if (data.slice) {
  8656. return data.slice(start, end);
  8657. }
  8658. return Array.prototype.slice.call(data, start, end);
  8659. };
  8660. Tools.SetImmediate = function (action) {
  8661. if (window.setImmediate) {
  8662. window.setImmediate(action);
  8663. }
  8664. else {
  8665. setTimeout(action, 1);
  8666. }
  8667. };
  8668. Tools.IsExponentOfTwo = function (value) {
  8669. var count = 1;
  8670. do {
  8671. count *= 2;
  8672. } while (count < value);
  8673. return count === value;
  8674. };
  8675. /**
  8676. * Returns the nearest 32-bit single precision float representation of a Number
  8677. * @param value A Number. If the parameter is of a different type, it will get converted
  8678. * to a number or to NaN if it cannot be converted
  8679. * @returns number
  8680. */
  8681. Tools.FloatRound = function (value) {
  8682. if (Math.fround) {
  8683. return Math.fround(value);
  8684. }
  8685. return (Tools._tmpFloatArray[0] = value);
  8686. };
  8687. /**
  8688. * Find the next highest power of two.
  8689. * @param x Number to start search from.
  8690. * @return Next highest power of two.
  8691. */
  8692. Tools.CeilingPOT = function (x) {
  8693. x--;
  8694. x |= x >> 1;
  8695. x |= x >> 2;
  8696. x |= x >> 4;
  8697. x |= x >> 8;
  8698. x |= x >> 16;
  8699. x++;
  8700. return x;
  8701. };
  8702. /**
  8703. * Find the next lowest power of two.
  8704. * @param x Number to start search from.
  8705. * @return Next lowest power of two.
  8706. */
  8707. Tools.FloorPOT = function (x) {
  8708. x = x | (x >> 1);
  8709. x = x | (x >> 2);
  8710. x = x | (x >> 4);
  8711. x = x | (x >> 8);
  8712. x = x | (x >> 16);
  8713. return x - (x >> 1);
  8714. };
  8715. /**
  8716. * Find the nearest power of two.
  8717. * @param x Number to start search from.
  8718. * @return Next nearest power of two.
  8719. */
  8720. Tools.NearestPOT = function (x) {
  8721. var c = Tools.CeilingPOT(x);
  8722. var f = Tools.FloorPOT(x);
  8723. return (c - x) > (x - f) ? f : c;
  8724. };
  8725. Tools.GetExponentOfTwo = function (value, max, mode) {
  8726. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8727. var pot;
  8728. switch (mode) {
  8729. case BABYLON.Engine.SCALEMODE_FLOOR:
  8730. pot = Tools.FloorPOT(value);
  8731. break;
  8732. case BABYLON.Engine.SCALEMODE_NEAREST:
  8733. pot = Tools.NearestPOT(value);
  8734. break;
  8735. case BABYLON.Engine.SCALEMODE_CEILING:
  8736. default:
  8737. pot = Tools.CeilingPOT(value);
  8738. break;
  8739. }
  8740. return Math.min(pot, max);
  8741. };
  8742. Tools.GetFilename = function (path) {
  8743. var index = path.lastIndexOf("/");
  8744. if (index < 0)
  8745. return path;
  8746. return path.substring(index + 1);
  8747. };
  8748. /**
  8749. * Extracts the "folder" part of a path (everything before the filename).
  8750. * @param uri The URI to extract the info from
  8751. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8752. * @returns The "folder" part of the path
  8753. */
  8754. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8755. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8756. var index = uri.lastIndexOf("/");
  8757. if (index < 0) {
  8758. if (returnUnchangedIfNoSlash) {
  8759. return uri;
  8760. }
  8761. return "";
  8762. }
  8763. return uri.substring(0, index + 1);
  8764. };
  8765. Tools.GetDOMTextContent = function (element) {
  8766. var result = "";
  8767. var child = element.firstChild;
  8768. while (child) {
  8769. if (child.nodeType === 3) {
  8770. result += child.textContent;
  8771. }
  8772. child = child.nextSibling;
  8773. }
  8774. return result;
  8775. };
  8776. Tools.ToDegrees = function (angle) {
  8777. return angle * 180 / Math.PI;
  8778. };
  8779. Tools.ToRadians = function (angle) {
  8780. return angle * Math.PI / 180;
  8781. };
  8782. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8783. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8784. var output = "";
  8785. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8786. var i = 0;
  8787. var bytes = new Uint8Array(buffer);
  8788. while (i < bytes.length) {
  8789. chr1 = bytes[i++];
  8790. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8791. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8792. enc1 = chr1 >> 2;
  8793. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8794. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8795. enc4 = chr3 & 63;
  8796. if (isNaN(chr2)) {
  8797. enc3 = enc4 = 64;
  8798. }
  8799. else if (isNaN(chr3)) {
  8800. enc4 = 64;
  8801. }
  8802. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8803. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8804. }
  8805. return "data:image/png;base64," + output;
  8806. };
  8807. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8808. if (bias === void 0) { bias = null; }
  8809. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8810. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8811. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8812. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8813. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8814. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8815. }
  8816. if (bias) {
  8817. minimum.x -= minimum.x * bias.x + bias.y;
  8818. minimum.y -= minimum.y * bias.x + bias.y;
  8819. minimum.z -= minimum.z * bias.x + bias.y;
  8820. maximum.x += maximum.x * bias.x + bias.y;
  8821. maximum.y += maximum.y * bias.x + bias.y;
  8822. maximum.z += maximum.z * bias.x + bias.y;
  8823. }
  8824. return {
  8825. minimum: minimum,
  8826. maximum: maximum
  8827. };
  8828. };
  8829. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8830. if (bias === void 0) { bias = null; }
  8831. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8832. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8833. if (!stride) {
  8834. stride = 3;
  8835. }
  8836. for (var index = start; index < start + count; index++) {
  8837. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8838. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8839. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8840. }
  8841. if (bias) {
  8842. minimum.x -= minimum.x * bias.x + bias.y;
  8843. minimum.y -= minimum.y * bias.x + bias.y;
  8844. minimum.z -= minimum.z * bias.x + bias.y;
  8845. maximum.x += maximum.x * bias.x + bias.y;
  8846. maximum.y += maximum.y * bias.x + bias.y;
  8847. maximum.z += maximum.z * bias.x + bias.y;
  8848. }
  8849. return {
  8850. minimum: minimum,
  8851. maximum: maximum
  8852. };
  8853. };
  8854. Tools.Vector2ArrayFeeder = function (array) {
  8855. return function (index) {
  8856. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8857. var length = isFloatArray ? array.length / 2 : array.length;
  8858. if (index >= length) {
  8859. return null;
  8860. }
  8861. if (isFloatArray) {
  8862. var fa = array;
  8863. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8864. }
  8865. var a = array;
  8866. return a[index];
  8867. };
  8868. };
  8869. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8870. if (bias === void 0) { bias = null; }
  8871. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8872. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8873. var i = 0;
  8874. var cur = feeder(i++);
  8875. while (cur) {
  8876. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8877. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8878. cur = feeder(i++);
  8879. }
  8880. if (bias) {
  8881. minimum.x -= minimum.x * bias.x + bias.y;
  8882. minimum.y -= minimum.y * bias.x + bias.y;
  8883. maximum.x += maximum.x * bias.x + bias.y;
  8884. maximum.y += maximum.y * bias.x + bias.y;
  8885. }
  8886. return {
  8887. minimum: minimum,
  8888. maximum: maximum
  8889. };
  8890. };
  8891. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8892. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8893. return null;
  8894. return Array.isArray(obj) ? obj : [obj];
  8895. };
  8896. // Misc.
  8897. Tools.GetPointerPrefix = function () {
  8898. var eventPrefix = "pointer";
  8899. // Check if pointer events are supported
  8900. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8901. eventPrefix = "mouse";
  8902. }
  8903. return eventPrefix;
  8904. };
  8905. /**
  8906. * @param func - the function to be called
  8907. * @param requester - the object that will request the next frame. Falls back to window.
  8908. */
  8909. Tools.QueueNewFrame = function (func, requester) {
  8910. if (!Tools.IsWindowObjectExist()) {
  8911. return setTimeout(func, 16);
  8912. }
  8913. if (!requester) {
  8914. requester = window;
  8915. }
  8916. if (requester.requestAnimationFrame) {
  8917. return requester.requestAnimationFrame(func);
  8918. }
  8919. else if (requester.msRequestAnimationFrame) {
  8920. return requester.msRequestAnimationFrame(func);
  8921. }
  8922. else if (requester.webkitRequestAnimationFrame) {
  8923. return requester.webkitRequestAnimationFrame(func);
  8924. }
  8925. else if (requester.mozRequestAnimationFrame) {
  8926. return requester.mozRequestAnimationFrame(func);
  8927. }
  8928. else if (requester.oRequestAnimationFrame) {
  8929. return requester.oRequestAnimationFrame(func);
  8930. }
  8931. else {
  8932. return window.setTimeout(func, 16);
  8933. }
  8934. };
  8935. Tools.RequestFullscreen = function (element) {
  8936. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8937. if (!requestFunction)
  8938. return;
  8939. requestFunction.call(element);
  8940. };
  8941. Tools.ExitFullscreen = function () {
  8942. if (document.exitFullscreen) {
  8943. document.exitFullscreen();
  8944. }
  8945. else if (document.mozCancelFullScreen) {
  8946. document.mozCancelFullScreen();
  8947. }
  8948. else if (document.webkitCancelFullScreen) {
  8949. document.webkitCancelFullScreen();
  8950. }
  8951. else if (document.msCancelFullScreen) {
  8952. document.msCancelFullScreen();
  8953. }
  8954. };
  8955. Tools.SetCorsBehavior = function (url, element) {
  8956. if (url && url.indexOf("data:") === 0) {
  8957. return;
  8958. }
  8959. if (Tools.CorsBehavior) {
  8960. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8961. element.crossOrigin = Tools.CorsBehavior;
  8962. }
  8963. else {
  8964. var result = Tools.CorsBehavior(url);
  8965. if (result) {
  8966. element.crossOrigin = result;
  8967. }
  8968. }
  8969. }
  8970. };
  8971. // External files
  8972. Tools.CleanUrl = function (url) {
  8973. url = url.replace(/#/mg, "%23");
  8974. return url;
  8975. };
  8976. /**
  8977. * Loads an image as an HTMLImageElement.
  8978. * @param input url string, ArrayBuffer, or Blob to load
  8979. * @param onLoad callback called when the image successfully loads
  8980. * @param onError callback called when the image fails to load
  8981. * @param database database for caching
  8982. * @returns the HTMLImageElement of the loaded image
  8983. */
  8984. Tools.LoadImage = function (input, onLoad, onError, database) {
  8985. var url;
  8986. var usingObjectURL = false;
  8987. if (input instanceof ArrayBuffer) {
  8988. url = URL.createObjectURL(new Blob([input]));
  8989. usingObjectURL = true;
  8990. }
  8991. else if (input instanceof Blob) {
  8992. url = URL.createObjectURL(input);
  8993. usingObjectURL = true;
  8994. }
  8995. else {
  8996. url = Tools.CleanUrl(input);
  8997. url = Tools.PreprocessUrl(input);
  8998. }
  8999. var img = new Image();
  9000. Tools.SetCorsBehavior(url, img);
  9001. var loadHandler = function () {
  9002. if (usingObjectURL && img.src) {
  9003. URL.revokeObjectURL(img.src);
  9004. }
  9005. img.removeEventListener("load", loadHandler);
  9006. img.removeEventListener("error", errorHandler);
  9007. onLoad(img);
  9008. };
  9009. var errorHandler = function (err) {
  9010. if (usingObjectURL && img.src) {
  9011. URL.revokeObjectURL(img.src);
  9012. }
  9013. img.removeEventListener("load", loadHandler);
  9014. img.removeEventListener("error", errorHandler);
  9015. Tools.Error("Error while trying to load image: " + input);
  9016. if (onError) {
  9017. onError("Error while trying to load image: " + input, err);
  9018. }
  9019. };
  9020. img.addEventListener("load", loadHandler);
  9021. img.addEventListener("error", errorHandler);
  9022. var noIndexedDB = function () {
  9023. img.src = url;
  9024. };
  9025. var loadFromIndexedDB = function () {
  9026. if (database) {
  9027. database.loadImageFromDB(url, img);
  9028. }
  9029. };
  9030. //ANY database to do!
  9031. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9032. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9033. }
  9034. else {
  9035. if (url.indexOf("file:") !== -1) {
  9036. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9037. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9038. try {
  9039. var blobURL;
  9040. try {
  9041. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  9042. }
  9043. catch (ex) {
  9044. // Chrome doesn't support oneTimeOnly parameter
  9045. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9046. }
  9047. img.src = blobURL;
  9048. usingObjectURL = true;
  9049. }
  9050. catch (e) {
  9051. img.src = "";
  9052. }
  9053. return img;
  9054. }
  9055. }
  9056. noIndexedDB();
  9057. }
  9058. return img;
  9059. };
  9060. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9061. url = Tools.CleanUrl(url);
  9062. url = Tools.PreprocessUrl(url);
  9063. // If file and file input are set
  9064. if (url.indexOf("file:") !== -1) {
  9065. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9066. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9067. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9068. }
  9069. }
  9070. var loadUrl = Tools.BaseUrl + url;
  9071. var aborted = false;
  9072. var fileRequest = {
  9073. onCompleteObservable: new BABYLON.Observable(),
  9074. abort: function () { return aborted = true; },
  9075. };
  9076. var requestFile = function () {
  9077. var request = new XMLHttpRequest();
  9078. var retryHandle = null;
  9079. fileRequest.abort = function () {
  9080. aborted = true;
  9081. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9082. request.abort();
  9083. }
  9084. if (retryHandle !== null) {
  9085. clearTimeout(retryHandle);
  9086. retryHandle = null;
  9087. }
  9088. };
  9089. var retryLoop = function (retryIndex) {
  9090. request.open('GET', loadUrl, true);
  9091. if (useArrayBuffer) {
  9092. request.responseType = "arraybuffer";
  9093. }
  9094. if (onProgress) {
  9095. request.addEventListener("progress", onProgress);
  9096. }
  9097. var onLoadEnd = function () {
  9098. request.removeEventListener("loadend", onLoadEnd);
  9099. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9100. fileRequest.onCompleteObservable.clear();
  9101. };
  9102. request.addEventListener("loadend", onLoadEnd);
  9103. var onReadyStateChange = function () {
  9104. if (aborted) {
  9105. return;
  9106. }
  9107. // In case of undefined state in some browsers.
  9108. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9109. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9110. request.removeEventListener("readystatechange", onReadyStateChange);
  9111. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9112. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9113. return;
  9114. }
  9115. var retryStrategy = Tools.DefaultRetryStrategy;
  9116. if (retryStrategy) {
  9117. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9118. if (waitTime !== -1) {
  9119. // Prevent the request from completing for retry.
  9120. request.removeEventListener("loadend", onLoadEnd);
  9121. request = new XMLHttpRequest();
  9122. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9123. return;
  9124. }
  9125. }
  9126. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9127. if (onError) {
  9128. onError(request, e);
  9129. }
  9130. else {
  9131. throw e;
  9132. }
  9133. }
  9134. };
  9135. request.addEventListener("readystatechange", onReadyStateChange);
  9136. request.send();
  9137. };
  9138. retryLoop(0);
  9139. };
  9140. // Caching all files
  9141. if (database && database.enableSceneOffline) {
  9142. var noIndexedDB_1 = function () {
  9143. if (!aborted) {
  9144. requestFile();
  9145. }
  9146. };
  9147. var loadFromIndexedDB = function () {
  9148. // TODO: database needs to support aborting and should return a IFileRequest
  9149. if (aborted) {
  9150. return;
  9151. }
  9152. if (database) {
  9153. database.loadFileFromDB(url, function (data) {
  9154. if (!aborted) {
  9155. onSuccess(data);
  9156. }
  9157. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9158. }, onProgress ? function (event) {
  9159. if (!aborted) {
  9160. onProgress(event);
  9161. }
  9162. } : undefined, noIndexedDB_1, useArrayBuffer);
  9163. }
  9164. };
  9165. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9166. }
  9167. else {
  9168. requestFile();
  9169. }
  9170. return fileRequest;
  9171. };
  9172. /**
  9173. * Load a script (identified by an url). When the url returns, the
  9174. * content of this file is added into a new script element, attached to the DOM (body element)
  9175. */
  9176. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9177. var head = document.getElementsByTagName('head')[0];
  9178. var script = document.createElement('script');
  9179. script.type = 'text/javascript';
  9180. script.src = scriptUrl;
  9181. script.onload = function () {
  9182. if (onSuccess) {
  9183. onSuccess();
  9184. }
  9185. };
  9186. script.onerror = function (e) {
  9187. if (onError) {
  9188. onError("Unable to load script '" + scriptUrl + "'", e);
  9189. }
  9190. };
  9191. head.appendChild(script);
  9192. };
  9193. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9194. var reader = new FileReader();
  9195. var request = {
  9196. onCompleteObservable: new BABYLON.Observable(),
  9197. abort: function () { return reader.abort(); },
  9198. };
  9199. reader.onloadend = function (e) {
  9200. request.onCompleteObservable.notifyObservers(request);
  9201. };
  9202. reader.onload = function (e) {
  9203. //target doesn't have result from ts 1.3
  9204. callback(e.target['result']);
  9205. };
  9206. reader.onprogress = progressCallback;
  9207. reader.readAsDataURL(fileToLoad);
  9208. return request;
  9209. };
  9210. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9211. var reader = new FileReader();
  9212. var request = {
  9213. onCompleteObservable: new BABYLON.Observable(),
  9214. abort: function () { return reader.abort(); },
  9215. };
  9216. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9217. reader.onerror = function (e) {
  9218. Tools.Log("Error while reading file: " + fileToLoad.name);
  9219. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9220. };
  9221. reader.onload = function (e) {
  9222. //target doesn't have result from ts 1.3
  9223. callback(e.target['result']);
  9224. };
  9225. if (progressCallBack) {
  9226. reader.onprogress = progressCallBack;
  9227. }
  9228. if (!useArrayBuffer) {
  9229. // Asynchronous read
  9230. reader.readAsText(fileToLoad);
  9231. }
  9232. else {
  9233. reader.readAsArrayBuffer(fileToLoad);
  9234. }
  9235. return request;
  9236. };
  9237. //returns a downloadable url to a file content.
  9238. Tools.FileAsURL = function (content) {
  9239. var fileBlob = new Blob([content]);
  9240. var url = window.URL || window.webkitURL;
  9241. var link = url.createObjectURL(fileBlob);
  9242. return link;
  9243. };
  9244. // Misc.
  9245. Tools.Format = function (value, decimals) {
  9246. if (decimals === void 0) { decimals = 2; }
  9247. return value.toFixed(decimals);
  9248. };
  9249. Tools.CheckExtends = function (v, min, max) {
  9250. if (v.x < min.x)
  9251. min.x = v.x;
  9252. if (v.y < min.y)
  9253. min.y = v.y;
  9254. if (v.z < min.z)
  9255. min.z = v.z;
  9256. if (v.x > max.x)
  9257. max.x = v.x;
  9258. if (v.y > max.y)
  9259. max.y = v.y;
  9260. if (v.z > max.z)
  9261. max.z = v.z;
  9262. };
  9263. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9264. for (var prop in source) {
  9265. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9266. continue;
  9267. }
  9268. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9269. continue;
  9270. }
  9271. var sourceValue = source[prop];
  9272. var typeOfSourceValue = typeof sourceValue;
  9273. if (typeOfSourceValue === "function") {
  9274. continue;
  9275. }
  9276. try {
  9277. if (typeOfSourceValue === "object") {
  9278. if (sourceValue instanceof Array) {
  9279. destination[prop] = [];
  9280. if (sourceValue.length > 0) {
  9281. if (typeof sourceValue[0] == "object") {
  9282. for (var index = 0; index < sourceValue.length; index++) {
  9283. var clonedValue = cloneValue(sourceValue[index], destination);
  9284. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9285. destination[prop].push(clonedValue);
  9286. }
  9287. }
  9288. }
  9289. else {
  9290. destination[prop] = sourceValue.slice(0);
  9291. }
  9292. }
  9293. }
  9294. else {
  9295. destination[prop] = cloneValue(sourceValue, destination);
  9296. }
  9297. }
  9298. else {
  9299. destination[prop] = sourceValue;
  9300. }
  9301. }
  9302. catch (e) {
  9303. // Just ignore error (it could be because of a read-only property)
  9304. }
  9305. }
  9306. };
  9307. Tools.IsEmpty = function (obj) {
  9308. for (var i in obj) {
  9309. if (obj.hasOwnProperty(i)) {
  9310. return false;
  9311. }
  9312. }
  9313. return true;
  9314. };
  9315. Tools.RegisterTopRootEvents = function (events) {
  9316. for (var index = 0; index < events.length; index++) {
  9317. var event = events[index];
  9318. window.addEventListener(event.name, event.handler, false);
  9319. try {
  9320. if (window.parent) {
  9321. window.parent.addEventListener(event.name, event.handler, false);
  9322. }
  9323. }
  9324. catch (e) {
  9325. // Silently fails...
  9326. }
  9327. }
  9328. };
  9329. Tools.UnregisterTopRootEvents = function (events) {
  9330. for (var index = 0; index < events.length; index++) {
  9331. var event = events[index];
  9332. window.removeEventListener(event.name, event.handler);
  9333. try {
  9334. if (window.parent) {
  9335. window.parent.removeEventListener(event.name, event.handler);
  9336. }
  9337. }
  9338. catch (e) {
  9339. // Silently fails...
  9340. }
  9341. }
  9342. };
  9343. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9344. if (mimeType === void 0) { mimeType = "image/png"; }
  9345. // Read the contents of the framebuffer
  9346. var numberOfChannelsByLine = width * 4;
  9347. var halfHeight = height / 2;
  9348. //Reading datas from WebGL
  9349. var data = engine.readPixels(0, 0, width, height);
  9350. //To flip image on Y axis.
  9351. for (var i = 0; i < halfHeight; i++) {
  9352. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9353. var currentCell = j + i * numberOfChannelsByLine;
  9354. var targetLine = height - i - 1;
  9355. var targetCell = j + targetLine * numberOfChannelsByLine;
  9356. var temp = data[currentCell];
  9357. data[currentCell] = data[targetCell];
  9358. data[targetCell] = temp;
  9359. }
  9360. }
  9361. // Create a 2D canvas to store the result
  9362. if (!screenshotCanvas) {
  9363. screenshotCanvas = document.createElement('canvas');
  9364. }
  9365. screenshotCanvas.width = width;
  9366. screenshotCanvas.height = height;
  9367. var context = screenshotCanvas.getContext('2d');
  9368. if (context) {
  9369. // Copy the pixels to a 2D canvas
  9370. var imageData = context.createImageData(width, height);
  9371. var castData = (imageData.data);
  9372. castData.set(data);
  9373. context.putImageData(imageData, 0, 0);
  9374. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9375. }
  9376. };
  9377. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9378. if (mimeType === void 0) { mimeType = "image/png"; }
  9379. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9380. if (successCallback) {
  9381. successCallback(base64Image);
  9382. }
  9383. else {
  9384. // We need HTMLCanvasElement.toBlob for HD screenshots
  9385. if (!screenshotCanvas.toBlob) {
  9386. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9387. screenshotCanvas.toBlob = function (callback, type, quality) {
  9388. var _this = this;
  9389. setTimeout(function () {
  9390. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9391. for (var i = 0; i < len; i++) {
  9392. arr[i] = binStr.charCodeAt(i);
  9393. }
  9394. callback(new Blob([arr], { type: type || 'image/png' }));
  9395. });
  9396. };
  9397. }
  9398. screenshotCanvas.toBlob(function (blob) {
  9399. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9400. if (("download" in document.createElement("a"))) {
  9401. if (!fileName) {
  9402. var date = new Date();
  9403. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9404. fileName = "screenshot_" + stringDate + ".png";
  9405. }
  9406. Tools.Download(blob, fileName);
  9407. }
  9408. else {
  9409. var url = URL.createObjectURL(blob);
  9410. var newWindow = window.open("");
  9411. if (!newWindow)
  9412. return;
  9413. var img = newWindow.document.createElement("img");
  9414. img.onload = function () {
  9415. // no longer need to read the blob so it's revoked
  9416. URL.revokeObjectURL(url);
  9417. };
  9418. img.src = url;
  9419. newWindow.document.body.appendChild(img);
  9420. }
  9421. });
  9422. }
  9423. };
  9424. /**
  9425. * Downloads a blob in the browser
  9426. * @param blob defines the blob to download
  9427. * @param fileName defines the name of the downloaded file
  9428. */
  9429. Tools.Download = function (blob, fileName) {
  9430. var url = window.URL.createObjectURL(blob);
  9431. var a = document.createElement("a");
  9432. document.body.appendChild(a);
  9433. a.style.display = "none";
  9434. a.href = url;
  9435. a.download = fileName;
  9436. a.addEventListener("click", function () {
  9437. if (a.parentElement) {
  9438. a.parentElement.removeChild(a);
  9439. }
  9440. });
  9441. a.click();
  9442. window.URL.revokeObjectURL(url);
  9443. };
  9444. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9445. if (mimeType === void 0) { mimeType = "image/png"; }
  9446. var width;
  9447. var height;
  9448. // If a precision value is specified
  9449. if (size.precision) {
  9450. width = Math.round(engine.getRenderWidth() * size.precision);
  9451. height = Math.round(width / engine.getAspectRatio(camera));
  9452. }
  9453. else if (size.width && size.height) {
  9454. width = size.width;
  9455. height = size.height;
  9456. }
  9457. //If passing only width, computing height to keep display canvas ratio.
  9458. else if (size.width && !size.height) {
  9459. width = size.width;
  9460. height = Math.round(width / engine.getAspectRatio(camera));
  9461. }
  9462. //If passing only height, computing width to keep display canvas ratio.
  9463. else if (size.height && !size.width) {
  9464. height = size.height;
  9465. width = Math.round(height * engine.getAspectRatio(camera));
  9466. }
  9467. //Assuming here that "size" parameter is a number
  9468. else if (!isNaN(size)) {
  9469. height = size;
  9470. width = size;
  9471. }
  9472. else {
  9473. Tools.Error("Invalid 'size' parameter !");
  9474. return;
  9475. }
  9476. if (!screenshotCanvas) {
  9477. screenshotCanvas = document.createElement('canvas');
  9478. }
  9479. screenshotCanvas.width = width;
  9480. screenshotCanvas.height = height;
  9481. var renderContext = screenshotCanvas.getContext("2d");
  9482. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9483. var newWidth = width;
  9484. var newHeight = newWidth / ratio;
  9485. if (newHeight > height) {
  9486. newHeight = height;
  9487. newWidth = newHeight * ratio;
  9488. }
  9489. var offsetX = Math.max(0, width - newWidth) / 2;
  9490. var offsetY = Math.max(0, height - newHeight) / 2;
  9491. var renderingCanvas = engine.getRenderingCanvas();
  9492. if (renderContext && renderingCanvas) {
  9493. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9494. }
  9495. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9496. };
  9497. /**
  9498. * Generates an image screenshot from the specified camera.
  9499. *
  9500. * @param engine The engine to use for rendering
  9501. * @param camera The camera to use for rendering
  9502. * @param size This parameter can be set to a single number or to an object with the
  9503. * following (optional) properties: precision, width, height. If a single number is passed,
  9504. * it will be used for both width and height. If an object is passed, the screenshot size
  9505. * will be derived from the parameters. The precision property is a multiplier allowing
  9506. * rendering at a higher or lower resolution.
  9507. * @param successCallback The callback receives a single parameter which contains the
  9508. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9509. * src parameter of an <img> to display it.
  9510. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9511. * Check your browser for supported MIME types.
  9512. * @param samples Texture samples (default: 1)
  9513. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9514. * @param fileName A name for for the downloaded file.
  9515. * @constructor
  9516. */
  9517. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9518. if (mimeType === void 0) { mimeType = "image/png"; }
  9519. if (samples === void 0) { samples = 1; }
  9520. if (antialiasing === void 0) { antialiasing = false; }
  9521. var width;
  9522. var height;
  9523. //If a precision value is specified
  9524. if (size.precision) {
  9525. width = Math.round(engine.getRenderWidth() * size.precision);
  9526. height = Math.round(width / engine.getAspectRatio(camera));
  9527. size = { width: width, height: height };
  9528. }
  9529. else if (size.width && size.height) {
  9530. width = size.width;
  9531. height = size.height;
  9532. }
  9533. //If passing only width, computing height to keep display canvas ratio.
  9534. else if (size.width && !size.height) {
  9535. width = size.width;
  9536. height = Math.round(width / engine.getAspectRatio(camera));
  9537. size = { width: width, height: height };
  9538. }
  9539. //If passing only height, computing width to keep display canvas ratio.
  9540. else if (size.height && !size.width) {
  9541. height = size.height;
  9542. width = Math.round(height * engine.getAspectRatio(camera));
  9543. size = { width: width, height: height };
  9544. }
  9545. //Assuming here that "size" parameter is a number
  9546. else if (!isNaN(size)) {
  9547. height = size;
  9548. width = size;
  9549. }
  9550. else {
  9551. Tools.Error("Invalid 'size' parameter !");
  9552. return;
  9553. }
  9554. var scene = camera.getScene();
  9555. var previousCamera = null;
  9556. if (scene.activeCamera !== camera) {
  9557. previousCamera = scene.activeCamera;
  9558. scene.activeCamera = camera;
  9559. }
  9560. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9561. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9562. texture.renderList = null;
  9563. texture.samples = samples;
  9564. if (antialiasing) {
  9565. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9566. }
  9567. texture.onAfterRenderObservable.add(function () {
  9568. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9569. });
  9570. scene.incrementRenderId();
  9571. scene.resetCachedMaterial();
  9572. texture.render(true);
  9573. texture.dispose();
  9574. if (previousCamera) {
  9575. scene.activeCamera = previousCamera;
  9576. }
  9577. camera.getProjectionMatrix(true); // Force cache refresh;
  9578. };
  9579. // XHR response validator for local file scenario
  9580. Tools.ValidateXHRData = function (xhr, dataType) {
  9581. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9582. if (dataType === void 0) { dataType = 7; }
  9583. try {
  9584. if (dataType & 1) {
  9585. if (xhr.responseText && xhr.responseText.length > 0) {
  9586. return true;
  9587. }
  9588. else if (dataType === 1) {
  9589. return false;
  9590. }
  9591. }
  9592. if (dataType & 2) {
  9593. // Check header width and height since there is no "TGA" magic number
  9594. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9595. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9596. return true;
  9597. }
  9598. else if (dataType === 2) {
  9599. return false;
  9600. }
  9601. }
  9602. if (dataType & 4) {
  9603. // Check for the "DDS" magic number
  9604. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9605. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9606. return true;
  9607. }
  9608. else {
  9609. return false;
  9610. }
  9611. }
  9612. }
  9613. catch (e) {
  9614. // Global protection
  9615. }
  9616. return false;
  9617. };
  9618. /**
  9619. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9620. * Be aware Math.random() could cause collisions, but:
  9621. * "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"
  9622. */
  9623. Tools.RandomId = function () {
  9624. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9625. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9626. return v.toString(16);
  9627. });
  9628. };
  9629. /**
  9630. * Test if the given uri is a base64 string.
  9631. * @param uri The uri to test
  9632. * @return True if the uri is a base64 string or false otherwise.
  9633. */
  9634. Tools.IsBase64 = function (uri) {
  9635. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9636. };
  9637. /**
  9638. * Decode the given base64 uri.
  9639. * @param uri The uri to decode
  9640. * @return The decoded base64 data.
  9641. */
  9642. Tools.DecodeBase64 = function (uri) {
  9643. var decodedString = atob(uri.split(",")[1]);
  9644. var bufferLength = decodedString.length;
  9645. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9646. for (var i = 0; i < bufferLength; i++) {
  9647. bufferView[i] = decodedString.charCodeAt(i);
  9648. }
  9649. return bufferView.buffer;
  9650. };
  9651. Object.defineProperty(Tools, "NoneLogLevel", {
  9652. get: function () {
  9653. return Tools._NoneLogLevel;
  9654. },
  9655. enumerable: true,
  9656. configurable: true
  9657. });
  9658. Object.defineProperty(Tools, "MessageLogLevel", {
  9659. get: function () {
  9660. return Tools._MessageLogLevel;
  9661. },
  9662. enumerable: true,
  9663. configurable: true
  9664. });
  9665. Object.defineProperty(Tools, "WarningLogLevel", {
  9666. get: function () {
  9667. return Tools._WarningLogLevel;
  9668. },
  9669. enumerable: true,
  9670. configurable: true
  9671. });
  9672. Object.defineProperty(Tools, "ErrorLogLevel", {
  9673. get: function () {
  9674. return Tools._ErrorLogLevel;
  9675. },
  9676. enumerable: true,
  9677. configurable: true
  9678. });
  9679. Object.defineProperty(Tools, "AllLogLevel", {
  9680. get: function () {
  9681. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9682. },
  9683. enumerable: true,
  9684. configurable: true
  9685. });
  9686. Tools._AddLogEntry = function (entry) {
  9687. Tools._LogCache = entry + Tools._LogCache;
  9688. if (Tools.OnNewCacheEntry) {
  9689. Tools.OnNewCacheEntry(entry);
  9690. }
  9691. };
  9692. Tools._FormatMessage = function (message) {
  9693. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9694. var date = new Date();
  9695. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9696. };
  9697. Tools._LogDisabled = function (message) {
  9698. // nothing to do
  9699. };
  9700. Tools._LogEnabled = function (message) {
  9701. var formattedMessage = Tools._FormatMessage(message);
  9702. console.log("BJS - " + formattedMessage);
  9703. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9704. Tools._AddLogEntry(entry);
  9705. };
  9706. Tools._WarnDisabled = function (message) {
  9707. // nothing to do
  9708. };
  9709. Tools._WarnEnabled = function (message) {
  9710. var formattedMessage = Tools._FormatMessage(message);
  9711. console.warn("BJS - " + formattedMessage);
  9712. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9713. Tools._AddLogEntry(entry);
  9714. };
  9715. Tools._ErrorDisabled = function (message) {
  9716. // nothing to do
  9717. };
  9718. Tools._ErrorEnabled = function (message) {
  9719. Tools.errorsCount++;
  9720. var formattedMessage = Tools._FormatMessage(message);
  9721. console.error("BJS - " + formattedMessage);
  9722. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9723. Tools._AddLogEntry(entry);
  9724. };
  9725. Object.defineProperty(Tools, "LogCache", {
  9726. get: function () {
  9727. return Tools._LogCache;
  9728. },
  9729. enumerable: true,
  9730. configurable: true
  9731. });
  9732. Tools.ClearLogCache = function () {
  9733. Tools._LogCache = "";
  9734. Tools.errorsCount = 0;
  9735. };
  9736. Object.defineProperty(Tools, "LogLevels", {
  9737. set: function (level) {
  9738. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9739. Tools.Log = Tools._LogEnabled;
  9740. }
  9741. else {
  9742. Tools.Log = Tools._LogDisabled;
  9743. }
  9744. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9745. Tools.Warn = Tools._WarnEnabled;
  9746. }
  9747. else {
  9748. Tools.Warn = Tools._WarnDisabled;
  9749. }
  9750. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9751. Tools.Error = Tools._ErrorEnabled;
  9752. }
  9753. else {
  9754. Tools.Error = Tools._ErrorDisabled;
  9755. }
  9756. },
  9757. enumerable: true,
  9758. configurable: true
  9759. });
  9760. Tools.IsWindowObjectExist = function () {
  9761. return (typeof window) !== "undefined";
  9762. };
  9763. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9764. get: function () {
  9765. return Tools._PerformanceNoneLogLevel;
  9766. },
  9767. enumerable: true,
  9768. configurable: true
  9769. });
  9770. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9771. get: function () {
  9772. return Tools._PerformanceUserMarkLogLevel;
  9773. },
  9774. enumerable: true,
  9775. configurable: true
  9776. });
  9777. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9778. get: function () {
  9779. return Tools._PerformanceConsoleLogLevel;
  9780. },
  9781. enumerable: true,
  9782. configurable: true
  9783. });
  9784. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9785. set: function (level) {
  9786. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9787. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9788. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9789. return;
  9790. }
  9791. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9792. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9793. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9794. return;
  9795. }
  9796. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9797. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9798. },
  9799. enumerable: true,
  9800. configurable: true
  9801. });
  9802. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9803. };
  9804. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9805. };
  9806. Tools._StartUserMark = function (counterName, condition) {
  9807. if (condition === void 0) { condition = true; }
  9808. if (!Tools._performance) {
  9809. if (!Tools.IsWindowObjectExist()) {
  9810. return;
  9811. }
  9812. Tools._performance = window.performance;
  9813. }
  9814. if (!condition || !Tools._performance.mark) {
  9815. return;
  9816. }
  9817. Tools._performance.mark(counterName + "-Begin");
  9818. };
  9819. Tools._EndUserMark = function (counterName, condition) {
  9820. if (condition === void 0) { condition = true; }
  9821. if (!condition || !Tools._performance.mark) {
  9822. return;
  9823. }
  9824. Tools._performance.mark(counterName + "-End");
  9825. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9826. };
  9827. Tools._StartPerformanceConsole = function (counterName, condition) {
  9828. if (condition === void 0) { condition = true; }
  9829. if (!condition) {
  9830. return;
  9831. }
  9832. Tools._StartUserMark(counterName, condition);
  9833. if (console.time) {
  9834. console.time(counterName);
  9835. }
  9836. };
  9837. Tools._EndPerformanceConsole = function (counterName, condition) {
  9838. if (condition === void 0) { condition = true; }
  9839. if (!condition) {
  9840. return;
  9841. }
  9842. Tools._EndUserMark(counterName, condition);
  9843. if (console.time) {
  9844. console.timeEnd(counterName);
  9845. }
  9846. };
  9847. Object.defineProperty(Tools, "Now", {
  9848. get: function () {
  9849. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9850. return window.performance.now();
  9851. }
  9852. return Date.now();
  9853. },
  9854. enumerable: true,
  9855. configurable: true
  9856. });
  9857. /**
  9858. * This method will return the name of the class used to create the instance of the given object.
  9859. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9860. * @param object the object to get the class name from
  9861. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9862. */
  9863. Tools.GetClassName = function (object, isType) {
  9864. if (isType === void 0) { isType = false; }
  9865. var name = null;
  9866. if (!isType && object.getClassName) {
  9867. name = object.getClassName();
  9868. }
  9869. else {
  9870. if (object instanceof Object) {
  9871. var classObj = isType ? object : Object.getPrototypeOf(object);
  9872. name = classObj.constructor["__bjsclassName__"];
  9873. }
  9874. if (!name) {
  9875. name = typeof object;
  9876. }
  9877. }
  9878. return name;
  9879. };
  9880. Tools.First = function (array, predicate) {
  9881. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9882. var el = array_1[_i];
  9883. if (predicate(el)) {
  9884. return el;
  9885. }
  9886. }
  9887. return null;
  9888. };
  9889. /**
  9890. * This method will return the name of the full name of the class, including its owning module (if any).
  9891. * 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).
  9892. * @param object the object to get the class name from
  9893. * @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.
  9894. */
  9895. Tools.getFullClassName = function (object, isType) {
  9896. if (isType === void 0) { isType = false; }
  9897. var className = null;
  9898. var moduleName = null;
  9899. if (!isType && object.getClassName) {
  9900. className = object.getClassName();
  9901. }
  9902. else {
  9903. if (object instanceof Object) {
  9904. var classObj = isType ? object : Object.getPrototypeOf(object);
  9905. className = classObj.constructor["__bjsclassName__"];
  9906. moduleName = classObj.constructor["__bjsmoduleName__"];
  9907. }
  9908. if (!className) {
  9909. className = typeof object;
  9910. }
  9911. }
  9912. if (!className) {
  9913. return null;
  9914. }
  9915. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9916. };
  9917. /**
  9918. * 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.
  9919. * @param array
  9920. */
  9921. Tools.arrayOrStringFeeder = function (array) {
  9922. return function (index) {
  9923. if (index >= array.length) {
  9924. return null;
  9925. }
  9926. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9927. if (val && val.getHashCode) {
  9928. val = val.getHashCode();
  9929. }
  9930. if (typeof val === "string") {
  9931. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9932. }
  9933. return val;
  9934. };
  9935. };
  9936. /**
  9937. * Compute the hashCode of a stream of number
  9938. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9939. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9940. * @return the hash code computed
  9941. */
  9942. Tools.hashCodeFromStream = function (feeder) {
  9943. // Based from here: http://stackoverflow.com/a/7616484/802124
  9944. var hash = 0;
  9945. var index = 0;
  9946. var chr = feeder(index++);
  9947. while (chr != null) {
  9948. hash = ((hash << 5) - hash) + chr;
  9949. hash |= 0; // Convert to 32bit integer
  9950. chr = feeder(index++);
  9951. }
  9952. return hash;
  9953. };
  9954. /**
  9955. * Returns a promise that resolves after the given amount of time.
  9956. * @param delay Number of milliseconds to delay
  9957. * @returns Promise that resolves after the given amount of time
  9958. */
  9959. Tools.DelayAsync = function (delay) {
  9960. return new Promise(function (resolve) {
  9961. setTimeout(function () {
  9962. resolve();
  9963. }, delay);
  9964. });
  9965. };
  9966. Tools.BaseUrl = "";
  9967. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9968. /**
  9969. * Default behaviour for cors in the application.
  9970. * It can be a string if the expected behavior is identical in the entire app.
  9971. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9972. */
  9973. Tools.CorsBehavior = "anonymous";
  9974. Tools.UseFallbackTexture = true;
  9975. /**
  9976. * Use this object to register external classes like custom textures or material
  9977. * to allow the laoders to instantiate them
  9978. */
  9979. Tools.RegisteredExternalClasses = {};
  9980. // Used in case of a texture loading problem
  9981. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh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uj+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";
  9982. Tools._tmpFloatArray = new Float32Array(1);
  9983. Tools.PreprocessUrl = function (url) {
  9984. return url;
  9985. };
  9986. // Logs
  9987. Tools._NoneLogLevel = 0;
  9988. Tools._MessageLogLevel = 1;
  9989. Tools._WarningLogLevel = 2;
  9990. Tools._ErrorLogLevel = 4;
  9991. Tools._LogCache = "";
  9992. Tools.errorsCount = 0;
  9993. Tools.Log = Tools._LogEnabled;
  9994. Tools.Warn = Tools._WarnEnabled;
  9995. Tools.Error = Tools._ErrorEnabled;
  9996. // Performances
  9997. Tools._PerformanceNoneLogLevel = 0;
  9998. Tools._PerformanceUserMarkLogLevel = 1;
  9999. Tools._PerformanceConsoleLogLevel = 2;
  10000. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10001. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10002. return Tools;
  10003. }());
  10004. BABYLON.Tools = Tools;
  10005. /**
  10006. * This class is used to track a performance counter which is number based.
  10007. * The user has access to many properties which give statistics of different nature
  10008. *
  10009. * The implementer can track two kinds of Performance Counter: time and count
  10010. * 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.
  10011. * 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.
  10012. */
  10013. var PerfCounter = /** @class */ (function () {
  10014. function PerfCounter() {
  10015. this._startMonitoringTime = 0;
  10016. this._min = 0;
  10017. this._max = 0;
  10018. this._average = 0;
  10019. this._lastSecAverage = 0;
  10020. this._current = 0;
  10021. this._totalValueCount = 0;
  10022. this._totalAccumulated = 0;
  10023. this._lastSecAccumulated = 0;
  10024. this._lastSecTime = 0;
  10025. this._lastSecValueCount = 0;
  10026. }
  10027. Object.defineProperty(PerfCounter.prototype, "min", {
  10028. /**
  10029. * Returns the smallest value ever
  10030. */
  10031. get: function () {
  10032. return this._min;
  10033. },
  10034. enumerable: true,
  10035. configurable: true
  10036. });
  10037. Object.defineProperty(PerfCounter.prototype, "max", {
  10038. /**
  10039. * Returns the biggest value ever
  10040. */
  10041. get: function () {
  10042. return this._max;
  10043. },
  10044. enumerable: true,
  10045. configurable: true
  10046. });
  10047. Object.defineProperty(PerfCounter.prototype, "average", {
  10048. /**
  10049. * Returns the average value since the performance counter is running
  10050. */
  10051. get: function () {
  10052. return this._average;
  10053. },
  10054. enumerable: true,
  10055. configurable: true
  10056. });
  10057. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10058. /**
  10059. * Returns the average value of the last second the counter was monitored
  10060. */
  10061. get: function () {
  10062. return this._lastSecAverage;
  10063. },
  10064. enumerable: true,
  10065. configurable: true
  10066. });
  10067. Object.defineProperty(PerfCounter.prototype, "current", {
  10068. /**
  10069. * Returns the current value
  10070. */
  10071. get: function () {
  10072. return this._current;
  10073. },
  10074. enumerable: true,
  10075. configurable: true
  10076. });
  10077. Object.defineProperty(PerfCounter.prototype, "total", {
  10078. get: function () {
  10079. return this._totalAccumulated;
  10080. },
  10081. enumerable: true,
  10082. configurable: true
  10083. });
  10084. Object.defineProperty(PerfCounter.prototype, "count", {
  10085. get: function () {
  10086. return this._totalValueCount;
  10087. },
  10088. enumerable: true,
  10089. configurable: true
  10090. });
  10091. /**
  10092. * Call this method to start monitoring a new frame.
  10093. * 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.
  10094. */
  10095. PerfCounter.prototype.fetchNewFrame = function () {
  10096. this._totalValueCount++;
  10097. this._current = 0;
  10098. this._lastSecValueCount++;
  10099. };
  10100. /**
  10101. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10102. * @param newCount the count value to add to the monitored count
  10103. * @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.
  10104. */
  10105. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10106. if (!PerfCounter.Enabled) {
  10107. return;
  10108. }
  10109. this._current += newCount;
  10110. if (fetchResult) {
  10111. this._fetchResult();
  10112. }
  10113. };
  10114. /**
  10115. * Start monitoring this performance counter
  10116. */
  10117. PerfCounter.prototype.beginMonitoring = function () {
  10118. if (!PerfCounter.Enabled) {
  10119. return;
  10120. }
  10121. this._startMonitoringTime = Tools.Now;
  10122. };
  10123. /**
  10124. * Compute the time lapsed since the previous beginMonitoring() call.
  10125. * @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
  10126. */
  10127. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10128. if (newFrame === void 0) { newFrame = true; }
  10129. if (!PerfCounter.Enabled) {
  10130. return;
  10131. }
  10132. if (newFrame) {
  10133. this.fetchNewFrame();
  10134. }
  10135. var currentTime = Tools.Now;
  10136. this._current = currentTime - this._startMonitoringTime;
  10137. if (newFrame) {
  10138. this._fetchResult();
  10139. }
  10140. };
  10141. PerfCounter.prototype._fetchResult = function () {
  10142. this._totalAccumulated += this._current;
  10143. this._lastSecAccumulated += this._current;
  10144. // Min/Max update
  10145. this._min = Math.min(this._min, this._current);
  10146. this._max = Math.max(this._max, this._current);
  10147. this._average = this._totalAccumulated / this._totalValueCount;
  10148. // Reset last sec?
  10149. var now = Tools.Now;
  10150. if ((now - this._lastSecTime) > 1000) {
  10151. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10152. this._lastSecTime = now;
  10153. this._lastSecAccumulated = 0;
  10154. this._lastSecValueCount = 0;
  10155. }
  10156. };
  10157. PerfCounter.Enabled = true;
  10158. return PerfCounter;
  10159. }());
  10160. BABYLON.PerfCounter = PerfCounter;
  10161. /**
  10162. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10163. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10164. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10165. * @param name The name of the class, case should be preserved
  10166. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10167. */
  10168. function className(name, module) {
  10169. return function (target) {
  10170. target["__bjsclassName__"] = name;
  10171. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10172. };
  10173. }
  10174. BABYLON.className = className;
  10175. /**
  10176. * An implementation of a loop for asynchronous functions.
  10177. */
  10178. var AsyncLoop = /** @class */ (function () {
  10179. /**
  10180. * Constroctor.
  10181. * @param iterations the number of iterations.
  10182. * @param _fn the function to run each iteration
  10183. * @param _successCallback the callback that will be called upon succesful execution
  10184. * @param offset starting offset.
  10185. */
  10186. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10187. if (offset === void 0) { offset = 0; }
  10188. this.iterations = iterations;
  10189. this._fn = _fn;
  10190. this._successCallback = _successCallback;
  10191. this.index = offset - 1;
  10192. this._done = false;
  10193. }
  10194. /**
  10195. * Execute the next iteration. Must be called after the last iteration was finished.
  10196. */
  10197. AsyncLoop.prototype.executeNext = function () {
  10198. if (!this._done) {
  10199. if (this.index + 1 < this.iterations) {
  10200. ++this.index;
  10201. this._fn(this);
  10202. }
  10203. else {
  10204. this.breakLoop();
  10205. }
  10206. }
  10207. };
  10208. /**
  10209. * Break the loop and run the success callback.
  10210. */
  10211. AsyncLoop.prototype.breakLoop = function () {
  10212. this._done = true;
  10213. this._successCallback();
  10214. };
  10215. /**
  10216. * Helper function
  10217. */
  10218. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10219. if (offset === void 0) { offset = 0; }
  10220. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10221. loop.executeNext();
  10222. return loop;
  10223. };
  10224. /**
  10225. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10226. * @param iterations total number of iterations
  10227. * @param syncedIterations number of synchronous iterations in each async iteration.
  10228. * @param fn the function to call each iteration.
  10229. * @param callback a success call back that will be called when iterating stops.
  10230. * @param breakFunction a break condition (optional)
  10231. * @param timeout timeout settings for the setTimeout function. default - 0.
  10232. * @constructor
  10233. */
  10234. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10235. if (timeout === void 0) { timeout = 0; }
  10236. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10237. if (breakFunction && breakFunction())
  10238. loop.breakLoop();
  10239. else {
  10240. setTimeout(function () {
  10241. for (var i = 0; i < syncedIterations; ++i) {
  10242. var iteration = (loop.index * syncedIterations) + i;
  10243. if (iteration >= iterations)
  10244. break;
  10245. fn(iteration);
  10246. if (breakFunction && breakFunction()) {
  10247. loop.breakLoop();
  10248. break;
  10249. }
  10250. }
  10251. loop.executeNext();
  10252. }, timeout);
  10253. }
  10254. }, callback);
  10255. };
  10256. return AsyncLoop;
  10257. }());
  10258. BABYLON.AsyncLoop = AsyncLoop;
  10259. })(BABYLON || (BABYLON = {}));
  10260. //# sourceMappingURL=babylon.tools.js.map
  10261. var BABYLON;
  10262. (function (BABYLON) {
  10263. var PromiseStates;
  10264. (function (PromiseStates) {
  10265. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10266. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10267. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10268. })(PromiseStates || (PromiseStates = {}));
  10269. var FulFillmentAgregator = /** @class */ (function () {
  10270. function FulFillmentAgregator() {
  10271. this.count = 0;
  10272. this.target = 0;
  10273. this.results = [];
  10274. }
  10275. return FulFillmentAgregator;
  10276. }());
  10277. var InternalPromise = /** @class */ (function () {
  10278. function InternalPromise(resolver) {
  10279. var _this = this;
  10280. this._state = PromiseStates.Pending;
  10281. this._children = new Array();
  10282. this._rejectWasConsumed = false;
  10283. if (!resolver) {
  10284. return;
  10285. }
  10286. try {
  10287. resolver(function (value) {
  10288. _this._resolve(value);
  10289. }, function (reason) {
  10290. _this._reject(reason);
  10291. });
  10292. }
  10293. catch (e) {
  10294. this._reject(e);
  10295. }
  10296. }
  10297. Object.defineProperty(InternalPromise.prototype, "_result", {
  10298. get: function () {
  10299. return this._resultValue;
  10300. },
  10301. set: function (value) {
  10302. this._resultValue = value;
  10303. if (this._parent && this._parent._result === undefined) {
  10304. this._parent._result = value;
  10305. }
  10306. },
  10307. enumerable: true,
  10308. configurable: true
  10309. });
  10310. InternalPromise.prototype.catch = function (onRejected) {
  10311. return this.then(undefined, onRejected);
  10312. };
  10313. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10314. var _this = this;
  10315. var newPromise = new InternalPromise();
  10316. newPromise._onFulfilled = onFulfilled;
  10317. newPromise._onRejected = onRejected;
  10318. // Composition
  10319. this._children.push(newPromise);
  10320. newPromise._parent = this;
  10321. if (this._state !== PromiseStates.Pending) {
  10322. BABYLON.Tools.SetImmediate(function () {
  10323. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10324. var returnedValue = newPromise._resolve(_this._result);
  10325. if (returnedValue !== undefined && returnedValue !== null) {
  10326. if (returnedValue._state !== undefined) {
  10327. var returnedPromise = returnedValue;
  10328. newPromise._children.push(returnedPromise);
  10329. returnedPromise._parent = newPromise;
  10330. newPromise = returnedPromise;
  10331. }
  10332. else {
  10333. newPromise._result = returnedValue;
  10334. }
  10335. }
  10336. }
  10337. else {
  10338. newPromise._reject(_this._reason);
  10339. }
  10340. });
  10341. }
  10342. return newPromise;
  10343. };
  10344. InternalPromise.prototype._moveChildren = function (children) {
  10345. var _this = this;
  10346. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10347. this._children.forEach(function (child) {
  10348. child._parent = _this;
  10349. });
  10350. if (this._state === PromiseStates.Fulfilled) {
  10351. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10352. var child = _b[_i];
  10353. child._resolve(this._result);
  10354. }
  10355. }
  10356. else if (this._state === PromiseStates.Rejected) {
  10357. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10358. var child = _d[_c];
  10359. child._reject(this._reason);
  10360. }
  10361. }
  10362. var _a;
  10363. };
  10364. InternalPromise.prototype._resolve = function (value) {
  10365. try {
  10366. this._state = PromiseStates.Fulfilled;
  10367. var returnedValue = null;
  10368. if (this._onFulfilled) {
  10369. returnedValue = this._onFulfilled(value);
  10370. }
  10371. if (returnedValue !== undefined && returnedValue !== null) {
  10372. if (returnedValue._state !== undefined) {
  10373. // Transmit children
  10374. var returnedPromise = returnedValue;
  10375. returnedPromise._parent = this;
  10376. returnedPromise._moveChildren(this._children);
  10377. value = returnedPromise._result;
  10378. }
  10379. else {
  10380. value = returnedValue;
  10381. }
  10382. }
  10383. this._result = value;
  10384. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10385. var child = _a[_i];
  10386. child._resolve(value);
  10387. }
  10388. this._children.length = 0;
  10389. delete this._onFulfilled;
  10390. delete this._onRejected;
  10391. }
  10392. catch (e) {
  10393. this._reject(e, true);
  10394. }
  10395. };
  10396. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10397. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10398. this._state = PromiseStates.Rejected;
  10399. this._reason = reason;
  10400. if (this._onRejected && !onLocalThrow) {
  10401. try {
  10402. this._onRejected(reason);
  10403. this._rejectWasConsumed = true;
  10404. }
  10405. catch (e) {
  10406. reason = e;
  10407. }
  10408. }
  10409. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10410. var child = _a[_i];
  10411. if (this._rejectWasConsumed) {
  10412. child._resolve(null);
  10413. }
  10414. else {
  10415. child._reject(reason);
  10416. }
  10417. }
  10418. this._children.length = 0;
  10419. delete this._onFulfilled;
  10420. delete this._onRejected;
  10421. };
  10422. InternalPromise.resolve = function (value) {
  10423. var newPromise = new InternalPromise();
  10424. newPromise._resolve(value);
  10425. return newPromise;
  10426. };
  10427. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10428. promise.then(function (value) {
  10429. agregator.results[index] = value;
  10430. agregator.count++;
  10431. if (agregator.count === agregator.target) {
  10432. agregator.rootPromise._resolve(agregator.results);
  10433. }
  10434. return null;
  10435. }, function (reason) {
  10436. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10437. agregator.rootPromise._reject(reason);
  10438. }
  10439. });
  10440. };
  10441. InternalPromise.all = function (promises) {
  10442. var newPromise = new InternalPromise();
  10443. var agregator = new FulFillmentAgregator();
  10444. agregator.target = promises.length;
  10445. agregator.rootPromise = newPromise;
  10446. if (promises.length) {
  10447. for (var index = 0; index < promises.length; index++) {
  10448. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10449. }
  10450. }
  10451. else {
  10452. newPromise._resolve([]);
  10453. }
  10454. return newPromise;
  10455. };
  10456. InternalPromise.race = function (promises) {
  10457. var newPromise = new InternalPromise();
  10458. if (promises.length) {
  10459. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10460. var promise = promises_1[_i];
  10461. promise.then(function (value) {
  10462. if (newPromise) {
  10463. newPromise._resolve(value);
  10464. newPromise = null;
  10465. }
  10466. return null;
  10467. }, function (reason) {
  10468. if (newPromise) {
  10469. newPromise._reject(reason);
  10470. newPromise = null;
  10471. }
  10472. });
  10473. }
  10474. }
  10475. return newPromise;
  10476. };
  10477. return InternalPromise;
  10478. }());
  10479. /**
  10480. * Helper class that provides a small promise polyfill
  10481. */
  10482. var PromisePolyfill = /** @class */ (function () {
  10483. function PromisePolyfill() {
  10484. }
  10485. /**
  10486. * Static function used to check if the polyfill is required
  10487. * If this is the case then the function will inject the polyfill to window.Promise
  10488. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10489. */
  10490. PromisePolyfill.Apply = function (force) {
  10491. if (force === void 0) { force = false; }
  10492. if (force || typeof Promise === 'undefined') {
  10493. var root = window;
  10494. root.Promise = InternalPromise;
  10495. }
  10496. };
  10497. return PromisePolyfill;
  10498. }());
  10499. BABYLON.PromisePolyfill = PromisePolyfill;
  10500. })(BABYLON || (BABYLON = {}));
  10501. //# sourceMappingURL=babylon.promise.js.map
  10502. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10503. var BABYLON;
  10504. (function (BABYLON) {
  10505. /**
  10506. * Helper class to push actions to a pool of workers.
  10507. */
  10508. var WorkerPool = /** @class */ (function () {
  10509. /**
  10510. * Constructor
  10511. * @param workers Array of workers to use for actions
  10512. */
  10513. function WorkerPool(workers) {
  10514. this._pendingActions = new Array();
  10515. this._workerInfos = workers.map(function (worker) { return ({
  10516. worker: worker,
  10517. active: false
  10518. }); });
  10519. }
  10520. /**
  10521. * Terminates all workers and clears any pending actions.
  10522. */
  10523. WorkerPool.prototype.dispose = function () {
  10524. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10525. var workerInfo = _a[_i];
  10526. workerInfo.worker.terminate();
  10527. }
  10528. delete this._workerInfos;
  10529. delete this._pendingActions;
  10530. };
  10531. /**
  10532. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10533. * pended until a worker has completed its action.
  10534. * @param action The action to perform. Call onComplete when the action is complete.
  10535. */
  10536. WorkerPool.prototype.push = function (action) {
  10537. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10538. var workerInfo = _a[_i];
  10539. if (!workerInfo.active) {
  10540. this._execute(workerInfo, action);
  10541. return;
  10542. }
  10543. }
  10544. this._pendingActions.push(action);
  10545. };
  10546. WorkerPool.prototype._execute = function (workerInfo, action) {
  10547. var _this = this;
  10548. workerInfo.active = true;
  10549. action(workerInfo.worker, function () {
  10550. workerInfo.active = false;
  10551. var nextAction = _this._pendingActions.shift();
  10552. if (nextAction) {
  10553. _this._execute(workerInfo, nextAction);
  10554. }
  10555. });
  10556. };
  10557. return WorkerPool;
  10558. }());
  10559. BABYLON.WorkerPool = WorkerPool;
  10560. })(BABYLON || (BABYLON = {}));
  10561. //# sourceMappingURL=babylon.workerPool.js.map
  10562. var BABYLON;
  10563. (function (BABYLON) {
  10564. /**
  10565. * @hidden
  10566. **/
  10567. var _AlphaState = /** @class */ (function () {
  10568. /**
  10569. * Initializes the state.
  10570. */
  10571. function _AlphaState() {
  10572. this._isAlphaBlendDirty = false;
  10573. this._isBlendFunctionParametersDirty = false;
  10574. this._isBlendEquationParametersDirty = false;
  10575. this._isBlendConstantsDirty = false;
  10576. this._alphaBlend = false;
  10577. this._blendFunctionParameters = new Array(4);
  10578. this._blendEquationParameters = new Array(2);
  10579. this._blendConstants = new Array(4);
  10580. this.reset();
  10581. }
  10582. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10583. get: function () {
  10584. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10585. },
  10586. enumerable: true,
  10587. configurable: true
  10588. });
  10589. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10590. get: function () {
  10591. return this._alphaBlend;
  10592. },
  10593. set: function (value) {
  10594. if (this._alphaBlend === value) {
  10595. return;
  10596. }
  10597. this._alphaBlend = value;
  10598. this._isAlphaBlendDirty = true;
  10599. },
  10600. enumerable: true,
  10601. configurable: true
  10602. });
  10603. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10604. if (this._blendConstants[0] === r &&
  10605. this._blendConstants[1] === g &&
  10606. this._blendConstants[2] === b &&
  10607. this._blendConstants[3] === a) {
  10608. return;
  10609. }
  10610. this._blendConstants[0] = r;
  10611. this._blendConstants[1] = g;
  10612. this._blendConstants[2] = b;
  10613. this._blendConstants[3] = a;
  10614. this._isBlendConstantsDirty = true;
  10615. };
  10616. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10617. if (this._blendFunctionParameters[0] === value0 &&
  10618. this._blendFunctionParameters[1] === value1 &&
  10619. this._blendFunctionParameters[2] === value2 &&
  10620. this._blendFunctionParameters[3] === value3) {
  10621. return;
  10622. }
  10623. this._blendFunctionParameters[0] = value0;
  10624. this._blendFunctionParameters[1] = value1;
  10625. this._blendFunctionParameters[2] = value2;
  10626. this._blendFunctionParameters[3] = value3;
  10627. this._isBlendFunctionParametersDirty = true;
  10628. };
  10629. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10630. if (this._blendEquationParameters[0] === rgb &&
  10631. this._blendEquationParameters[1] === alpha) {
  10632. return;
  10633. }
  10634. this._blendEquationParameters[0] = rgb;
  10635. this._blendEquationParameters[1] = alpha;
  10636. this._isBlendEquationParametersDirty = true;
  10637. };
  10638. _AlphaState.prototype.reset = function () {
  10639. this._alphaBlend = false;
  10640. this._blendFunctionParameters[0] = null;
  10641. this._blendFunctionParameters[1] = null;
  10642. this._blendFunctionParameters[2] = null;
  10643. this._blendFunctionParameters[3] = null;
  10644. this._blendEquationParameters[0] = null;
  10645. this._blendEquationParameters[1] = null;
  10646. this._blendConstants[0] = null;
  10647. this._blendConstants[1] = null;
  10648. this._blendConstants[2] = null;
  10649. this._blendConstants[3] = null;
  10650. this._isAlphaBlendDirty = true;
  10651. this._isBlendFunctionParametersDirty = false;
  10652. this._isBlendEquationParametersDirty = false;
  10653. this._isBlendConstantsDirty = false;
  10654. };
  10655. _AlphaState.prototype.apply = function (gl) {
  10656. if (!this.isDirty) {
  10657. return;
  10658. }
  10659. // Alpha blend
  10660. if (this._isAlphaBlendDirty) {
  10661. if (this._alphaBlend) {
  10662. gl.enable(gl.BLEND);
  10663. }
  10664. else {
  10665. gl.disable(gl.BLEND);
  10666. }
  10667. this._isAlphaBlendDirty = false;
  10668. }
  10669. // Alpha function
  10670. if (this._isBlendFunctionParametersDirty) {
  10671. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10672. this._isBlendFunctionParametersDirty = false;
  10673. }
  10674. // Alpha equation
  10675. if (this._isBlendEquationParametersDirty) {
  10676. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10677. this._isBlendEquationParametersDirty = false;
  10678. }
  10679. // Constants
  10680. if (this._isBlendConstantsDirty) {
  10681. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10682. this._isBlendConstantsDirty = false;
  10683. }
  10684. };
  10685. return _AlphaState;
  10686. }());
  10687. BABYLON._AlphaState = _AlphaState;
  10688. })(BABYLON || (BABYLON = {}));
  10689. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10690. var BABYLON;
  10691. (function (BABYLON) {
  10692. /**
  10693. * @hidden
  10694. **/
  10695. var _DepthCullingState = /** @class */ (function () {
  10696. /**
  10697. * Initializes the state.
  10698. */
  10699. function _DepthCullingState() {
  10700. this._isDepthTestDirty = false;
  10701. this._isDepthMaskDirty = false;
  10702. this._isDepthFuncDirty = false;
  10703. this._isCullFaceDirty = false;
  10704. this._isCullDirty = false;
  10705. this._isZOffsetDirty = false;
  10706. this._isFrontFaceDirty = false;
  10707. this.reset();
  10708. }
  10709. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10710. get: function () {
  10711. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10712. },
  10713. enumerable: true,
  10714. configurable: true
  10715. });
  10716. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10717. get: function () {
  10718. return this._zOffset;
  10719. },
  10720. set: function (value) {
  10721. if (this._zOffset === value) {
  10722. return;
  10723. }
  10724. this._zOffset = value;
  10725. this._isZOffsetDirty = true;
  10726. },
  10727. enumerable: true,
  10728. configurable: true
  10729. });
  10730. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10731. get: function () {
  10732. return this._cullFace;
  10733. },
  10734. set: function (value) {
  10735. if (this._cullFace === value) {
  10736. return;
  10737. }
  10738. this._cullFace = value;
  10739. this._isCullFaceDirty = true;
  10740. },
  10741. enumerable: true,
  10742. configurable: true
  10743. });
  10744. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10745. get: function () {
  10746. return this._cull;
  10747. },
  10748. set: function (value) {
  10749. if (this._cull === value) {
  10750. return;
  10751. }
  10752. this._cull = value;
  10753. this._isCullDirty = true;
  10754. },
  10755. enumerable: true,
  10756. configurable: true
  10757. });
  10758. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10759. get: function () {
  10760. return this._depthFunc;
  10761. },
  10762. set: function (value) {
  10763. if (this._depthFunc === value) {
  10764. return;
  10765. }
  10766. this._depthFunc = value;
  10767. this._isDepthFuncDirty = true;
  10768. },
  10769. enumerable: true,
  10770. configurable: true
  10771. });
  10772. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10773. get: function () {
  10774. return this._depthMask;
  10775. },
  10776. set: function (value) {
  10777. if (this._depthMask === value) {
  10778. return;
  10779. }
  10780. this._depthMask = value;
  10781. this._isDepthMaskDirty = true;
  10782. },
  10783. enumerable: true,
  10784. configurable: true
  10785. });
  10786. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10787. get: function () {
  10788. return this._depthTest;
  10789. },
  10790. set: function (value) {
  10791. if (this._depthTest === value) {
  10792. return;
  10793. }
  10794. this._depthTest = value;
  10795. this._isDepthTestDirty = true;
  10796. },
  10797. enumerable: true,
  10798. configurable: true
  10799. });
  10800. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10801. get: function () {
  10802. return this._frontFace;
  10803. },
  10804. set: function (value) {
  10805. if (this._frontFace === value) {
  10806. return;
  10807. }
  10808. this._frontFace = value;
  10809. this._isFrontFaceDirty = true;
  10810. },
  10811. enumerable: true,
  10812. configurable: true
  10813. });
  10814. _DepthCullingState.prototype.reset = function () {
  10815. this._depthMask = true;
  10816. this._depthTest = true;
  10817. this._depthFunc = null;
  10818. this._cullFace = null;
  10819. this._cull = null;
  10820. this._zOffset = 0;
  10821. this._frontFace = null;
  10822. this._isDepthTestDirty = true;
  10823. this._isDepthMaskDirty = true;
  10824. this._isDepthFuncDirty = false;
  10825. this._isCullFaceDirty = false;
  10826. this._isCullDirty = false;
  10827. this._isZOffsetDirty = false;
  10828. this._isFrontFaceDirty = false;
  10829. };
  10830. _DepthCullingState.prototype.apply = function (gl) {
  10831. if (!this.isDirty) {
  10832. return;
  10833. }
  10834. // Cull
  10835. if (this._isCullDirty) {
  10836. if (this.cull) {
  10837. gl.enable(gl.CULL_FACE);
  10838. }
  10839. else {
  10840. gl.disable(gl.CULL_FACE);
  10841. }
  10842. this._isCullDirty = false;
  10843. }
  10844. // Cull face
  10845. if (this._isCullFaceDirty) {
  10846. gl.cullFace(this.cullFace);
  10847. this._isCullFaceDirty = false;
  10848. }
  10849. // Depth mask
  10850. if (this._isDepthMaskDirty) {
  10851. gl.depthMask(this.depthMask);
  10852. this._isDepthMaskDirty = false;
  10853. }
  10854. // Depth test
  10855. if (this._isDepthTestDirty) {
  10856. if (this.depthTest) {
  10857. gl.enable(gl.DEPTH_TEST);
  10858. }
  10859. else {
  10860. gl.disable(gl.DEPTH_TEST);
  10861. }
  10862. this._isDepthTestDirty = false;
  10863. }
  10864. // Depth func
  10865. if (this._isDepthFuncDirty) {
  10866. gl.depthFunc(this.depthFunc);
  10867. this._isDepthFuncDirty = false;
  10868. }
  10869. // zOffset
  10870. if (this._isZOffsetDirty) {
  10871. if (this.zOffset) {
  10872. gl.enable(gl.POLYGON_OFFSET_FILL);
  10873. gl.polygonOffset(this.zOffset, 0);
  10874. }
  10875. else {
  10876. gl.disable(gl.POLYGON_OFFSET_FILL);
  10877. }
  10878. this._isZOffsetDirty = false;
  10879. }
  10880. // Front face
  10881. if (this._isFrontFaceDirty) {
  10882. gl.frontFace(this.frontFace);
  10883. this._isFrontFaceDirty = false;
  10884. }
  10885. };
  10886. return _DepthCullingState;
  10887. }());
  10888. BABYLON._DepthCullingState = _DepthCullingState;
  10889. })(BABYLON || (BABYLON = {}));
  10890. //# sourceMappingURL=babylon.depthCullingState.js.map
  10891. var BABYLON;
  10892. (function (BABYLON) {
  10893. /**
  10894. * @hidden
  10895. **/
  10896. var _StencilState = /** @class */ (function () {
  10897. function _StencilState() {
  10898. this._isStencilTestDirty = false;
  10899. this._isStencilMaskDirty = false;
  10900. this._isStencilFuncDirty = false;
  10901. this._isStencilOpDirty = false;
  10902. this.reset();
  10903. }
  10904. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10905. get: function () {
  10906. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10907. },
  10908. enumerable: true,
  10909. configurable: true
  10910. });
  10911. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10912. get: function () {
  10913. return this._stencilFunc;
  10914. },
  10915. set: function (value) {
  10916. if (this._stencilFunc === value) {
  10917. return;
  10918. }
  10919. this._stencilFunc = value;
  10920. this._isStencilFuncDirty = true;
  10921. },
  10922. enumerable: true,
  10923. configurable: true
  10924. });
  10925. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10926. get: function () {
  10927. return this._stencilFuncRef;
  10928. },
  10929. set: function (value) {
  10930. if (this._stencilFuncRef === value) {
  10931. return;
  10932. }
  10933. this._stencilFuncRef = value;
  10934. this._isStencilFuncDirty = true;
  10935. },
  10936. enumerable: true,
  10937. configurable: true
  10938. });
  10939. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10940. get: function () {
  10941. return this._stencilFuncMask;
  10942. },
  10943. set: function (value) {
  10944. if (this._stencilFuncMask === value) {
  10945. return;
  10946. }
  10947. this._stencilFuncMask = value;
  10948. this._isStencilFuncDirty = true;
  10949. },
  10950. enumerable: true,
  10951. configurable: true
  10952. });
  10953. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10954. get: function () {
  10955. return this._stencilOpStencilFail;
  10956. },
  10957. set: function (value) {
  10958. if (this._stencilOpStencilFail === value) {
  10959. return;
  10960. }
  10961. this._stencilOpStencilFail = value;
  10962. this._isStencilOpDirty = true;
  10963. },
  10964. enumerable: true,
  10965. configurable: true
  10966. });
  10967. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10968. get: function () {
  10969. return this._stencilOpDepthFail;
  10970. },
  10971. set: function (value) {
  10972. if (this._stencilOpDepthFail === value) {
  10973. return;
  10974. }
  10975. this._stencilOpDepthFail = value;
  10976. this._isStencilOpDirty = true;
  10977. },
  10978. enumerable: true,
  10979. configurable: true
  10980. });
  10981. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10982. get: function () {
  10983. return this._stencilOpStencilDepthPass;
  10984. },
  10985. set: function (value) {
  10986. if (this._stencilOpStencilDepthPass === value) {
  10987. return;
  10988. }
  10989. this._stencilOpStencilDepthPass = value;
  10990. this._isStencilOpDirty = true;
  10991. },
  10992. enumerable: true,
  10993. configurable: true
  10994. });
  10995. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10996. get: function () {
  10997. return this._stencilMask;
  10998. },
  10999. set: function (value) {
  11000. if (this._stencilMask === value) {
  11001. return;
  11002. }
  11003. this._stencilMask = value;
  11004. this._isStencilMaskDirty = true;
  11005. },
  11006. enumerable: true,
  11007. configurable: true
  11008. });
  11009. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11010. get: function () {
  11011. return this._stencilTest;
  11012. },
  11013. set: function (value) {
  11014. if (this._stencilTest === value) {
  11015. return;
  11016. }
  11017. this._stencilTest = value;
  11018. this._isStencilTestDirty = true;
  11019. },
  11020. enumerable: true,
  11021. configurable: true
  11022. });
  11023. _StencilState.prototype.reset = function () {
  11024. this._stencilTest = false;
  11025. this._stencilMask = 0xFF;
  11026. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11027. this._stencilFuncRef = 1;
  11028. this._stencilFuncMask = 0xFF;
  11029. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11030. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11031. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11032. this._isStencilTestDirty = true;
  11033. this._isStencilMaskDirty = true;
  11034. this._isStencilFuncDirty = true;
  11035. this._isStencilOpDirty = true;
  11036. };
  11037. _StencilState.prototype.apply = function (gl) {
  11038. if (!this.isDirty) {
  11039. return;
  11040. }
  11041. // Stencil test
  11042. if (this._isStencilTestDirty) {
  11043. if (this.stencilTest) {
  11044. gl.enable(gl.STENCIL_TEST);
  11045. }
  11046. else {
  11047. gl.disable(gl.STENCIL_TEST);
  11048. }
  11049. this._isStencilTestDirty = false;
  11050. }
  11051. // Stencil mask
  11052. if (this._isStencilMaskDirty) {
  11053. gl.stencilMask(this.stencilMask);
  11054. this._isStencilMaskDirty = false;
  11055. }
  11056. // Stencil func
  11057. if (this._isStencilFuncDirty) {
  11058. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11059. this._isStencilFuncDirty = false;
  11060. }
  11061. // Stencil op
  11062. if (this._isStencilOpDirty) {
  11063. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11064. this._isStencilOpDirty = false;
  11065. }
  11066. };
  11067. return _StencilState;
  11068. }());
  11069. BABYLON._StencilState = _StencilState;
  11070. })(BABYLON || (BABYLON = {}));
  11071. //# sourceMappingURL=babylon.stencilState.js.map
  11072. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11073. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11074. s = arguments[i];
  11075. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11076. t[p] = s[p];
  11077. }
  11078. return t;
  11079. };
  11080. var BABYLON;
  11081. (function (BABYLON) {
  11082. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11083. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11084. };
  11085. var compileRawShader = function (gl, source, type) {
  11086. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11087. gl.shaderSource(shader, source);
  11088. gl.compileShader(shader);
  11089. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11090. var log = gl.getShaderInfoLog(shader);
  11091. if (log) {
  11092. throw new Error(log);
  11093. }
  11094. }
  11095. if (!shader) {
  11096. throw new Error("Something went wrong while compile the shader.");
  11097. }
  11098. return shader;
  11099. };
  11100. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11101. var magFilter = gl.NEAREST;
  11102. var minFilter = gl.NEAREST;
  11103. switch (samplingMode) {
  11104. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11105. magFilter = gl.LINEAR;
  11106. if (generateMipMaps) {
  11107. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11108. }
  11109. else {
  11110. minFilter = gl.LINEAR;
  11111. }
  11112. break;
  11113. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11114. magFilter = gl.LINEAR;
  11115. if (generateMipMaps) {
  11116. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11117. }
  11118. else {
  11119. minFilter = gl.LINEAR;
  11120. }
  11121. break;
  11122. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11123. magFilter = gl.NEAREST;
  11124. if (generateMipMaps) {
  11125. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11126. }
  11127. else {
  11128. minFilter = gl.NEAREST;
  11129. }
  11130. break;
  11131. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11132. magFilter = gl.NEAREST;
  11133. if (generateMipMaps) {
  11134. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11135. }
  11136. else {
  11137. minFilter = gl.NEAREST;
  11138. }
  11139. break;
  11140. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11141. magFilter = gl.NEAREST;
  11142. if (generateMipMaps) {
  11143. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11144. }
  11145. else {
  11146. minFilter = gl.LINEAR;
  11147. }
  11148. break;
  11149. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11150. magFilter = gl.NEAREST;
  11151. if (generateMipMaps) {
  11152. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11153. }
  11154. else {
  11155. minFilter = gl.LINEAR;
  11156. }
  11157. break;
  11158. case BABYLON.Texture.NEAREST_LINEAR:
  11159. magFilter = gl.NEAREST;
  11160. minFilter = gl.LINEAR;
  11161. break;
  11162. case BABYLON.Texture.NEAREST_NEAREST:
  11163. magFilter = gl.NEAREST;
  11164. minFilter = gl.NEAREST;
  11165. break;
  11166. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11167. magFilter = gl.LINEAR;
  11168. if (generateMipMaps) {
  11169. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11170. }
  11171. else {
  11172. minFilter = gl.NEAREST;
  11173. }
  11174. break;
  11175. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11176. magFilter = gl.LINEAR;
  11177. if (generateMipMaps) {
  11178. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11179. }
  11180. else {
  11181. minFilter = gl.NEAREST;
  11182. }
  11183. break;
  11184. case BABYLON.Texture.LINEAR_LINEAR:
  11185. magFilter = gl.LINEAR;
  11186. minFilter = gl.LINEAR;
  11187. break;
  11188. case BABYLON.Texture.LINEAR_NEAREST:
  11189. magFilter = gl.LINEAR;
  11190. minFilter = gl.NEAREST;
  11191. break;
  11192. }
  11193. return {
  11194. min: minFilter,
  11195. mag: magFilter
  11196. };
  11197. };
  11198. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11199. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11200. var img;
  11201. var onload = function () {
  11202. loadedImages[index] = img;
  11203. loadedImages._internalCount++;
  11204. if (scene) {
  11205. scene._removePendingData(img);
  11206. }
  11207. if (loadedImages._internalCount === 6) {
  11208. onfinish(loadedImages);
  11209. }
  11210. };
  11211. var onerror = function (message, exception) {
  11212. if (scene) {
  11213. scene._removePendingData(img);
  11214. }
  11215. if (onErrorCallBack) {
  11216. onErrorCallBack(message, exception);
  11217. }
  11218. };
  11219. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11220. if (scene) {
  11221. scene._addPendingData(img);
  11222. }
  11223. };
  11224. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11225. if (onError === void 0) { onError = null; }
  11226. var loadedImages = [];
  11227. loadedImages._internalCount = 0;
  11228. for (var index = 0; index < 6; index++) {
  11229. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11230. }
  11231. };
  11232. var BufferPointer = /** @class */ (function () {
  11233. function BufferPointer() {
  11234. }
  11235. return BufferPointer;
  11236. }());
  11237. /**
  11238. * Interface for attribute information associated with buffer instanciation
  11239. */
  11240. var InstancingAttributeInfo = /** @class */ (function () {
  11241. function InstancingAttributeInfo() {
  11242. }
  11243. return InstancingAttributeInfo;
  11244. }());
  11245. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11246. /**
  11247. * Define options used to create a render target texture
  11248. */
  11249. var RenderTargetCreationOptions = /** @class */ (function () {
  11250. function RenderTargetCreationOptions() {
  11251. }
  11252. return RenderTargetCreationOptions;
  11253. }());
  11254. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11255. /**
  11256. * Define options used to create a depth texture
  11257. */
  11258. var DepthTextureCreationOptions = /** @class */ (function () {
  11259. function DepthTextureCreationOptions() {
  11260. }
  11261. return DepthTextureCreationOptions;
  11262. }());
  11263. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11264. /**
  11265. * Class used to describe the capabilities of the engine relatively to the current browser
  11266. */
  11267. var EngineCapabilities = /** @class */ (function () {
  11268. function EngineCapabilities() {
  11269. }
  11270. return EngineCapabilities;
  11271. }());
  11272. BABYLON.EngineCapabilities = EngineCapabilities;
  11273. /**
  11274. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11275. */
  11276. var Engine = /** @class */ (function () {
  11277. /**
  11278. * Creates a new engine
  11279. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11280. * @param antialias defines enable antialiasing (default: false)
  11281. * @param options defines further options to be sent to the getContext() function
  11282. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11283. */
  11284. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11285. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11286. var _this = this;
  11287. // Public members
  11288. /**
  11289. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11290. */
  11291. this.forcePOTTextures = false;
  11292. /**
  11293. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11294. */
  11295. this.isFullscreen = false;
  11296. /**
  11297. * Gets a boolean indicating if the pointer is currently locked
  11298. */
  11299. this.isPointerLock = false;
  11300. /**
  11301. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11302. */
  11303. this.cullBackFaces = true;
  11304. /**
  11305. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11306. */
  11307. this.renderEvenInBackground = true;
  11308. /**
  11309. * Gets or sets a boolean indicating that cache can be kept between frames
  11310. */
  11311. this.preventCacheWipeBetweenFrames = false;
  11312. /**
  11313. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11314. **/
  11315. this.enableOfflineSupport = false;
  11316. /**
  11317. * 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)
  11318. **/
  11319. this.disableManifestCheck = false;
  11320. /**
  11321. * Gets the list of created scenes
  11322. */
  11323. this.scenes = new Array();
  11324. /**
  11325. * Gets the list of created postprocesses
  11326. */
  11327. this.postProcesses = new Array();
  11328. // Observables
  11329. /**
  11330. * Observable event triggered each time the rendering canvas is resized
  11331. */
  11332. this.onResizeObservable = new BABYLON.Observable();
  11333. /**
  11334. * Observable event triggered each time the canvas loses focus
  11335. */
  11336. this.onCanvasBlurObservable = new BABYLON.Observable();
  11337. /**
  11338. * Observable event triggered each time the canvas gains focus
  11339. */
  11340. this.onCanvasFocusObservable = new BABYLON.Observable();
  11341. /**
  11342. * Observable event triggered each time the canvas receives pointerout event
  11343. */
  11344. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11345. /**
  11346. * Observable event triggered before each texture is initialized
  11347. */
  11348. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11349. //WebVR
  11350. this._vrDisplay = undefined;
  11351. this._vrSupported = false;
  11352. this._vrExclusivePointerMode = false;
  11353. // Uniform buffers list
  11354. /**
  11355. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11356. */
  11357. this.disableUniformBuffers = false;
  11358. /** @hidden */
  11359. this._uniformBuffers = new Array();
  11360. // Observables
  11361. /**
  11362. * Observable raised when the engine begins a new frame
  11363. */
  11364. this.onBeginFrameObservable = new BABYLON.Observable();
  11365. /**
  11366. * Observable raised when the engine ends the current frame
  11367. */
  11368. this.onEndFrameObservable = new BABYLON.Observable();
  11369. /**
  11370. * Observable raised when the engine is about to compile a shader
  11371. */
  11372. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11373. /**
  11374. * Observable raised when the engine has jsut compiled a shader
  11375. */
  11376. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11377. this._windowIsBackground = false;
  11378. this._webGLVersion = 1.0;
  11379. /** @hidden */
  11380. this._badOS = false;
  11381. /** @hidden */
  11382. this._badDesktopOS = false;
  11383. /**
  11384. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11385. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11386. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11387. */
  11388. this.disableTextureBindingOptimization = false;
  11389. /**
  11390. * Observable signaled when VR display mode changes
  11391. */
  11392. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11393. /**
  11394. * Observable signaled when VR request present is complete
  11395. */
  11396. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11397. /**
  11398. * Observable signaled when VR request present starts
  11399. */
  11400. this.onVRRequestPresentStart = new BABYLON.Observable();
  11401. this._colorWrite = true;
  11402. /** @hidden */
  11403. this._drawCalls = new BABYLON.PerfCounter();
  11404. /** @hidden */
  11405. this._textureCollisions = new BABYLON.PerfCounter();
  11406. this._renderingQueueLaunched = false;
  11407. this._activeRenderLoops = new Array();
  11408. // Deterministic lockstepMaxSteps
  11409. this._deterministicLockstep = false;
  11410. this._lockstepMaxSteps = 4;
  11411. // Lost context
  11412. /**
  11413. * Observable signaled when a context lost event is raised
  11414. */
  11415. this.onContextLostObservable = new BABYLON.Observable();
  11416. /**
  11417. * Observable signaled when a context restored event is raised
  11418. */
  11419. this.onContextRestoredObservable = new BABYLON.Observable();
  11420. this._contextWasLost = false;
  11421. this._doNotHandleContextLost = false;
  11422. // FPS
  11423. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11424. this._fps = 60;
  11425. this._deltaTime = 0;
  11426. /**
  11427. * Turn this value on if you want to pause FPS computation when in background
  11428. */
  11429. this.disablePerformanceMonitorInBackground = false;
  11430. // States
  11431. /** @hidden */
  11432. this._depthCullingState = new BABYLON._DepthCullingState();
  11433. /** @hidden */
  11434. this._stencilState = new BABYLON._StencilState();
  11435. /** @hidden */
  11436. this._alphaState = new BABYLON._AlphaState();
  11437. /** @hidden */
  11438. this._alphaMode = Engine.ALPHA_DISABLE;
  11439. // Cache
  11440. this._internalTexturesCache = new Array();
  11441. /** @hidden */
  11442. this._activeChannel = 0;
  11443. this._currentTextureChannel = -1;
  11444. /** @hidden */
  11445. this._boundTexturesCache = {};
  11446. this._compiledEffects = {};
  11447. this._vertexAttribArraysEnabled = [];
  11448. this._uintIndicesCurrentlySet = false;
  11449. this._currentBoundBuffer = new Array();
  11450. this._currentBufferPointers = new Array();
  11451. this._currentInstanceLocations = new Array();
  11452. this._currentInstanceBuffers = new Array();
  11453. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11454. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11455. this._vaoRecordInProgress = false;
  11456. this._mustWipeVertexAttributes = false;
  11457. this._nextFreeTextureSlots = new Array();
  11458. this._maxSimultaneousTextures = 0;
  11459. this._activeRequests = new Array();
  11460. // Hardware supported Compressed Textures
  11461. this._texturesSupported = new Array();
  11462. /**
  11463. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11464. */
  11465. this.premultipliedAlpha = true;
  11466. this._onVRFullScreenTriggered = function () {
  11467. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11468. //get the old size before we change
  11469. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11470. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11471. //get the width and height, change the render size
  11472. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11473. _this.setHardwareScalingLevel(1);
  11474. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11475. }
  11476. else {
  11477. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11478. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11479. }
  11480. };
  11481. this._boundUniforms = {};
  11482. // Register promises
  11483. BABYLON.PromisePolyfill.Apply();
  11484. var canvas = null;
  11485. Engine.Instances.push(this);
  11486. if (!canvasOrContext) {
  11487. return;
  11488. }
  11489. options = options || {};
  11490. if (canvasOrContext.getContext) {
  11491. canvas = canvasOrContext;
  11492. this._renderingCanvas = canvas;
  11493. if (antialias != null) {
  11494. options.antialias = antialias;
  11495. }
  11496. if (options.deterministicLockstep === undefined) {
  11497. options.deterministicLockstep = false;
  11498. }
  11499. if (options.lockstepMaxSteps === undefined) {
  11500. options.lockstepMaxSteps = 4;
  11501. }
  11502. if (options.preserveDrawingBuffer === undefined) {
  11503. options.preserveDrawingBuffer = false;
  11504. }
  11505. if (options.audioEngine === undefined) {
  11506. options.audioEngine = true;
  11507. }
  11508. if (options.stencil === undefined) {
  11509. options.stencil = true;
  11510. }
  11511. if (options.premultipliedAlpha === false) {
  11512. this.premultipliedAlpha = false;
  11513. }
  11514. this._deterministicLockstep = options.deterministicLockstep;
  11515. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11516. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11517. // Exceptions
  11518. if (navigator && navigator.userAgent) {
  11519. var ua = navigator.userAgent;
  11520. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11521. var exception = _a[_i];
  11522. var key = exception.key;
  11523. var targets = exception.targets;
  11524. if (ua.indexOf(key) > -1) {
  11525. if (exception.capture && exception.captureConstraint) {
  11526. var capture = exception.capture;
  11527. var constraint = exception.captureConstraint;
  11528. var regex = new RegExp(capture);
  11529. var matches = regex.exec(ua);
  11530. if (matches && matches.length > 0) {
  11531. var capturedValue = parseInt(matches[matches.length - 1]);
  11532. if (capturedValue >= constraint) {
  11533. continue;
  11534. }
  11535. }
  11536. }
  11537. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11538. var target = targets_1[_b];
  11539. switch (target) {
  11540. case "uniformBuffer":
  11541. this.disableUniformBuffers = true;
  11542. break;
  11543. case "textureBindingOptimization":
  11544. this.disableTextureBindingOptimization = true;
  11545. break;
  11546. }
  11547. }
  11548. }
  11549. }
  11550. }
  11551. // GL
  11552. if (!options.disableWebGL2Support) {
  11553. try {
  11554. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11555. if (this._gl) {
  11556. this._webGLVersion = 2.0;
  11557. }
  11558. }
  11559. catch (e) {
  11560. // Do nothing
  11561. }
  11562. }
  11563. if (!this._gl) {
  11564. if (!canvas) {
  11565. throw new Error("The provided canvas is null or undefined.");
  11566. }
  11567. try {
  11568. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11569. }
  11570. catch (e) {
  11571. throw new Error("WebGL not supported");
  11572. }
  11573. }
  11574. if (!this._gl) {
  11575. throw new Error("WebGL not supported");
  11576. }
  11577. this._onCanvasFocus = function () {
  11578. _this.onCanvasFocusObservable.notifyObservers(_this);
  11579. };
  11580. this._onCanvasBlur = function () {
  11581. _this.onCanvasBlurObservable.notifyObservers(_this);
  11582. };
  11583. canvas.addEventListener("focus", this._onCanvasFocus);
  11584. canvas.addEventListener("blur", this._onCanvasBlur);
  11585. this._onBlur = function () {
  11586. if (_this.disablePerformanceMonitorInBackground) {
  11587. _this._performanceMonitor.disable();
  11588. }
  11589. _this._windowIsBackground = true;
  11590. };
  11591. this._onFocus = function () {
  11592. if (_this.disablePerformanceMonitorInBackground) {
  11593. _this._performanceMonitor.enable();
  11594. }
  11595. _this._windowIsBackground = false;
  11596. };
  11597. this._onCanvasPointerOut = function (ev) {
  11598. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11599. };
  11600. window.addEventListener("blur", this._onBlur);
  11601. window.addEventListener("focus", this._onFocus);
  11602. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11603. // Context lost
  11604. if (!this._doNotHandleContextLost) {
  11605. this._onContextLost = function (evt) {
  11606. evt.preventDefault();
  11607. _this._contextWasLost = true;
  11608. BABYLON.Tools.Warn("WebGL context lost.");
  11609. _this.onContextLostObservable.notifyObservers(_this);
  11610. };
  11611. this._onContextRestored = function (evt) {
  11612. // Adding a timeout to avoid race condition at browser level
  11613. setTimeout(function () {
  11614. // Rebuild gl context
  11615. _this._initGLContext();
  11616. // Rebuild effects
  11617. _this._rebuildEffects();
  11618. // Rebuild textures
  11619. _this._rebuildInternalTextures();
  11620. // Rebuild buffers
  11621. _this._rebuildBuffers();
  11622. // Cache
  11623. _this.wipeCaches(true);
  11624. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11625. _this.onContextRestoredObservable.notifyObservers(_this);
  11626. _this._contextWasLost = false;
  11627. }, 0);
  11628. };
  11629. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11630. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11631. }
  11632. }
  11633. else {
  11634. this._gl = canvasOrContext;
  11635. this._renderingCanvas = this._gl.canvas;
  11636. if (this._gl.renderbufferStorageMultisample) {
  11637. this._webGLVersion = 2.0;
  11638. }
  11639. options.stencil = this._gl.getContextAttributes().stencil;
  11640. }
  11641. // Viewport
  11642. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11643. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11644. this.resize();
  11645. this._isStencilEnable = options.stencil ? true : false;
  11646. this._initGLContext();
  11647. if (canvas) {
  11648. // Fullscreen
  11649. this._onFullscreenChange = function () {
  11650. if (document.fullscreen !== undefined) {
  11651. _this.isFullscreen = document.fullscreen;
  11652. }
  11653. else if (document.mozFullScreen !== undefined) {
  11654. _this.isFullscreen = document.mozFullScreen;
  11655. }
  11656. else if (document.webkitIsFullScreen !== undefined) {
  11657. _this.isFullscreen = document.webkitIsFullScreen;
  11658. }
  11659. else if (document.msIsFullScreen !== undefined) {
  11660. _this.isFullscreen = document.msIsFullScreen;
  11661. }
  11662. // Pointer lock
  11663. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11664. canvas.requestPointerLock = canvas.requestPointerLock ||
  11665. canvas.msRequestPointerLock ||
  11666. canvas.mozRequestPointerLock ||
  11667. canvas.webkitRequestPointerLock;
  11668. if (canvas.requestPointerLock) {
  11669. canvas.requestPointerLock();
  11670. }
  11671. }
  11672. };
  11673. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11674. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11675. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11676. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11677. // Pointer lock
  11678. this._onPointerLockChange = function () {
  11679. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11680. document.webkitPointerLockElement === canvas ||
  11681. document.msPointerLockElement === canvas ||
  11682. document.pointerLockElement === canvas);
  11683. };
  11684. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11685. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11686. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11687. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11688. this._onVRDisplayPointerRestricted = function () {
  11689. if (canvas) {
  11690. canvas.requestPointerLock();
  11691. }
  11692. };
  11693. this._onVRDisplayPointerUnrestricted = function () {
  11694. document.exitPointerLock();
  11695. };
  11696. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11697. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11698. }
  11699. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11700. Engine.audioEngine = new BABYLON.AudioEngine();
  11701. }
  11702. // Prepare buffer pointers
  11703. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11704. this._currentBufferPointers[i] = new BufferPointer();
  11705. }
  11706. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11707. // Load WebVR Devices
  11708. if (options.autoEnableWebVR) {
  11709. this.initWebVR();
  11710. }
  11711. // Detect if we are running on a faulty buggy OS.
  11712. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11713. // Detect if we are running on a faulty buggy desktop OS.
  11714. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11715. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11716. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11717. }
  11718. Object.defineProperty(Engine, "LastCreatedEngine", {
  11719. /**
  11720. * Gets the latest created engine
  11721. */
  11722. get: function () {
  11723. if (Engine.Instances.length === 0) {
  11724. return null;
  11725. }
  11726. return Engine.Instances[Engine.Instances.length - 1];
  11727. },
  11728. enumerable: true,
  11729. configurable: true
  11730. });
  11731. Object.defineProperty(Engine, "LastCreatedScene", {
  11732. /**
  11733. * Gets the latest created scene
  11734. */
  11735. get: function () {
  11736. var lastCreatedEngine = Engine.LastCreatedEngine;
  11737. if (!lastCreatedEngine) {
  11738. return null;
  11739. }
  11740. if (lastCreatedEngine.scenes.length === 0) {
  11741. return null;
  11742. }
  11743. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11744. },
  11745. enumerable: true,
  11746. configurable: true
  11747. });
  11748. /**
  11749. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11750. * @param flag defines which part of the materials must be marked as dirty
  11751. * @param predicate defines a predicate used to filter which materials should be affected
  11752. */
  11753. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11754. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11755. var engine = Engine.Instances[engineIndex];
  11756. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11757. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11758. }
  11759. }
  11760. };
  11761. Object.defineProperty(Engine, "NEVER", {
  11762. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11763. get: function () {
  11764. return Engine._NEVER;
  11765. },
  11766. enumerable: true,
  11767. configurable: true
  11768. });
  11769. Object.defineProperty(Engine, "ALWAYS", {
  11770. /** 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 */
  11771. get: function () {
  11772. return Engine._ALWAYS;
  11773. },
  11774. enumerable: true,
  11775. configurable: true
  11776. });
  11777. Object.defineProperty(Engine, "LESS", {
  11778. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11779. get: function () {
  11780. return Engine._LESS;
  11781. },
  11782. enumerable: true,
  11783. configurable: true
  11784. });
  11785. Object.defineProperty(Engine, "EQUAL", {
  11786. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11787. get: function () {
  11788. return Engine._EQUAL;
  11789. },
  11790. enumerable: true,
  11791. configurable: true
  11792. });
  11793. Object.defineProperty(Engine, "LEQUAL", {
  11794. /** 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 */
  11795. get: function () {
  11796. return Engine._LEQUAL;
  11797. },
  11798. enumerable: true,
  11799. configurable: true
  11800. });
  11801. Object.defineProperty(Engine, "GREATER", {
  11802. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11803. get: function () {
  11804. return Engine._GREATER;
  11805. },
  11806. enumerable: true,
  11807. configurable: true
  11808. });
  11809. Object.defineProperty(Engine, "GEQUAL", {
  11810. /** 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 */
  11811. get: function () {
  11812. return Engine._GEQUAL;
  11813. },
  11814. enumerable: true,
  11815. configurable: true
  11816. });
  11817. Object.defineProperty(Engine, "NOTEQUAL", {
  11818. /** 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 */
  11819. get: function () {
  11820. return Engine._NOTEQUAL;
  11821. },
  11822. enumerable: true,
  11823. configurable: true
  11824. });
  11825. Object.defineProperty(Engine, "KEEP", {
  11826. /** Passed to stencilOperation to specify that stencil value must be kept */
  11827. get: function () {
  11828. return Engine._KEEP;
  11829. },
  11830. enumerable: true,
  11831. configurable: true
  11832. });
  11833. Object.defineProperty(Engine, "REPLACE", {
  11834. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11835. get: function () {
  11836. return Engine._REPLACE;
  11837. },
  11838. enumerable: true,
  11839. configurable: true
  11840. });
  11841. Object.defineProperty(Engine, "INCR", {
  11842. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11843. get: function () {
  11844. return Engine._INCR;
  11845. },
  11846. enumerable: true,
  11847. configurable: true
  11848. });
  11849. Object.defineProperty(Engine, "DECR", {
  11850. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11851. get: function () {
  11852. return Engine._DECR;
  11853. },
  11854. enumerable: true,
  11855. configurable: true
  11856. });
  11857. Object.defineProperty(Engine, "INVERT", {
  11858. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11859. get: function () {
  11860. return Engine._INVERT;
  11861. },
  11862. enumerable: true,
  11863. configurable: true
  11864. });
  11865. Object.defineProperty(Engine, "INCR_WRAP", {
  11866. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11867. get: function () {
  11868. return Engine._INCR_WRAP;
  11869. },
  11870. enumerable: true,
  11871. configurable: true
  11872. });
  11873. Object.defineProperty(Engine, "DECR_WRAP", {
  11874. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11875. get: function () {
  11876. return Engine._DECR_WRAP;
  11877. },
  11878. enumerable: true,
  11879. configurable: true
  11880. });
  11881. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11882. // Alpha
  11883. /** Defines that alpha blending is disabled */
  11884. get: function () {
  11885. return Engine._ALPHA_DISABLE;
  11886. },
  11887. enumerable: true,
  11888. configurable: true
  11889. });
  11890. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11891. /** Defines that alpha blending to SRC + DEST */
  11892. get: function () {
  11893. return Engine._ALPHA_ONEONE;
  11894. },
  11895. enumerable: true,
  11896. configurable: true
  11897. });
  11898. Object.defineProperty(Engine, "ALPHA_ADD", {
  11899. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11900. get: function () {
  11901. return Engine._ALPHA_ADD;
  11902. },
  11903. enumerable: true,
  11904. configurable: true
  11905. });
  11906. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11907. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11908. get: function () {
  11909. return Engine._ALPHA_COMBINE;
  11910. },
  11911. enumerable: true,
  11912. configurable: true
  11913. });
  11914. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11915. /** Defines that alpha blending to DEST - SRC * DEST */
  11916. get: function () {
  11917. return Engine._ALPHA_SUBTRACT;
  11918. },
  11919. enumerable: true,
  11920. configurable: true
  11921. });
  11922. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11923. /** Defines that alpha blending to SRC * DEST */
  11924. get: function () {
  11925. return Engine._ALPHA_MULTIPLY;
  11926. },
  11927. enumerable: true,
  11928. configurable: true
  11929. });
  11930. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11931. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11932. get: function () {
  11933. return Engine._ALPHA_MAXIMIZED;
  11934. },
  11935. enumerable: true,
  11936. configurable: true
  11937. });
  11938. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11939. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11940. get: function () {
  11941. return Engine._ALPHA_PREMULTIPLIED;
  11942. },
  11943. enumerable: true,
  11944. configurable: true
  11945. });
  11946. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11947. /**
  11948. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11949. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11950. */
  11951. get: function () {
  11952. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11953. },
  11954. enumerable: true,
  11955. configurable: true
  11956. });
  11957. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11958. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11959. get: function () {
  11960. return Engine._ALPHA_INTERPOLATE;
  11961. },
  11962. enumerable: true,
  11963. configurable: true
  11964. });
  11965. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11966. /**
  11967. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11968. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11969. */
  11970. get: function () {
  11971. return Engine._ALPHA_SCREENMODE;
  11972. },
  11973. enumerable: true,
  11974. configurable: true
  11975. });
  11976. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11977. // Delays
  11978. /** Defines that the ressource is not delayed*/
  11979. get: function () {
  11980. return Engine._DELAYLOADSTATE_NONE;
  11981. },
  11982. enumerable: true,
  11983. configurable: true
  11984. });
  11985. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11986. /** Defines that the ressource was successfully delay loaded */
  11987. get: function () {
  11988. return Engine._DELAYLOADSTATE_LOADED;
  11989. },
  11990. enumerable: true,
  11991. configurable: true
  11992. });
  11993. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11994. /** Defines that the ressource is currently delay loading */
  11995. get: function () {
  11996. return Engine._DELAYLOADSTATE_LOADING;
  11997. },
  11998. enumerable: true,
  11999. configurable: true
  12000. });
  12001. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  12002. /** Defines that the ressource is delayed and has not started loading */
  12003. get: function () {
  12004. return Engine._DELAYLOADSTATE_NOTLOADED;
  12005. },
  12006. enumerable: true,
  12007. configurable: true
  12008. });
  12009. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  12010. /** ALPHA */
  12011. get: function () {
  12012. return Engine._TEXTUREFORMAT_ALPHA;
  12013. },
  12014. enumerable: true,
  12015. configurable: true
  12016. });
  12017. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  12018. /** LUMINANCE */
  12019. get: function () {
  12020. return Engine._TEXTUREFORMAT_LUMINANCE;
  12021. },
  12022. enumerable: true,
  12023. configurable: true
  12024. });
  12025. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  12026. /**
  12027. * R
  12028. */
  12029. get: function () {
  12030. return Engine._TEXTUREFORMAT_R;
  12031. },
  12032. enumerable: true,
  12033. configurable: true
  12034. });
  12035. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  12036. /**
  12037. * RG
  12038. */
  12039. get: function () {
  12040. return Engine._TEXTUREFORMAT_RG;
  12041. },
  12042. enumerable: true,
  12043. configurable: true
  12044. });
  12045. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  12046. /** LUMINANCE_ALPHA */
  12047. get: function () {
  12048. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  12049. },
  12050. enumerable: true,
  12051. configurable: true
  12052. });
  12053. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  12054. /** RGB */
  12055. get: function () {
  12056. return Engine._TEXTUREFORMAT_RGB;
  12057. },
  12058. enumerable: true,
  12059. configurable: true
  12060. });
  12061. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  12062. /** RGBA */
  12063. get: function () {
  12064. return Engine._TEXTUREFORMAT_RGBA;
  12065. },
  12066. enumerable: true,
  12067. configurable: true
  12068. });
  12069. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12070. /** UNSIGNED_INT */
  12071. get: function () {
  12072. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12073. },
  12074. enumerable: true,
  12075. configurable: true
  12076. });
  12077. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12078. /** FLOAT */
  12079. get: function () {
  12080. return Engine._TEXTURETYPE_FLOAT;
  12081. },
  12082. enumerable: true,
  12083. configurable: true
  12084. });
  12085. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12086. /** HALF_FLOAT */
  12087. get: function () {
  12088. return Engine._TEXTURETYPE_HALF_FLOAT;
  12089. },
  12090. enumerable: true,
  12091. configurable: true
  12092. });
  12093. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12094. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12095. get: function () {
  12096. return Engine._SCALEMODE_FLOOR;
  12097. },
  12098. enumerable: true,
  12099. configurable: true
  12100. });
  12101. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12102. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12103. get: function () {
  12104. return Engine._SCALEMODE_NEAREST;
  12105. },
  12106. enumerable: true,
  12107. configurable: true
  12108. });
  12109. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12110. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12111. get: function () {
  12112. return Engine._SCALEMODE_CEILING;
  12113. },
  12114. enumerable: true,
  12115. configurable: true
  12116. });
  12117. Object.defineProperty(Engine, "Version", {
  12118. /**
  12119. * Returns the current version of the framework
  12120. */
  12121. get: function () {
  12122. return "3.3.0-alpha.5";
  12123. },
  12124. enumerable: true,
  12125. configurable: true
  12126. });
  12127. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12128. /**
  12129. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12130. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12131. */
  12132. get: function () {
  12133. return this._vrExclusivePointerMode;
  12134. },
  12135. enumerable: true,
  12136. configurable: true
  12137. });
  12138. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12139. /**
  12140. * Gets a boolean indicating that the engine supports uniform buffers
  12141. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12142. */
  12143. get: function () {
  12144. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12145. },
  12146. enumerable: true,
  12147. configurable: true
  12148. });
  12149. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12150. /**
  12151. * Gets a boolean indicating that only power of 2 textures are supported
  12152. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12153. */
  12154. get: function () {
  12155. return this._webGLVersion < 2 || this.forcePOTTextures;
  12156. },
  12157. enumerable: true,
  12158. configurable: true
  12159. });
  12160. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12161. /**
  12162. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12163. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12164. */
  12165. get: function () {
  12166. return this._doNotHandleContextLost;
  12167. },
  12168. set: function (value) {
  12169. this._doNotHandleContextLost = value;
  12170. },
  12171. enumerable: true,
  12172. configurable: true
  12173. });
  12174. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12175. /**
  12176. * Gets the performance monitor attached to this engine
  12177. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12178. */
  12179. get: function () {
  12180. return this._performanceMonitor;
  12181. },
  12182. enumerable: true,
  12183. configurable: true
  12184. });
  12185. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12186. /**
  12187. * Gets the list of texture formats supported
  12188. */
  12189. get: function () {
  12190. return this._texturesSupported;
  12191. },
  12192. enumerable: true,
  12193. configurable: true
  12194. });
  12195. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12196. /**
  12197. * Gets the list of texture formats in use
  12198. */
  12199. get: function () {
  12200. return this._textureFormatInUse;
  12201. },
  12202. enumerable: true,
  12203. configurable: true
  12204. });
  12205. Object.defineProperty(Engine.prototype, "currentViewport", {
  12206. /**
  12207. * Gets the current viewport
  12208. */
  12209. get: function () {
  12210. return this._cachedViewport;
  12211. },
  12212. enumerable: true,
  12213. configurable: true
  12214. });
  12215. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12216. /**
  12217. * Gets the default empty texture
  12218. */
  12219. get: function () {
  12220. if (!this._emptyTexture) {
  12221. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12222. }
  12223. return this._emptyTexture;
  12224. },
  12225. enumerable: true,
  12226. configurable: true
  12227. });
  12228. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12229. /**
  12230. * Gets the default empty 3D texture
  12231. */
  12232. get: function () {
  12233. if (!this._emptyTexture3D) {
  12234. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12235. }
  12236. return this._emptyTexture3D;
  12237. },
  12238. enumerable: true,
  12239. configurable: true
  12240. });
  12241. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12242. /**
  12243. * Gets the default empty cube texture
  12244. */
  12245. get: function () {
  12246. if (!this._emptyCubeTexture) {
  12247. var faceData = new Uint8Array(4);
  12248. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12249. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12250. }
  12251. return this._emptyCubeTexture;
  12252. },
  12253. enumerable: true,
  12254. configurable: true
  12255. });
  12256. Engine.prototype._rebuildInternalTextures = function () {
  12257. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12258. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12259. var internalTexture = currentState_1[_i];
  12260. internalTexture._rebuild();
  12261. }
  12262. };
  12263. Engine.prototype._rebuildEffects = function () {
  12264. for (var key in this._compiledEffects) {
  12265. var effect = this._compiledEffects[key];
  12266. effect._prepareEffect();
  12267. }
  12268. BABYLON.Effect.ResetCache();
  12269. };
  12270. Engine.prototype._rebuildBuffers = function () {
  12271. // Index / Vertex
  12272. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12273. var scene = _a[_i];
  12274. scene.resetCachedMaterial();
  12275. scene._rebuildGeometries();
  12276. scene._rebuildTextures();
  12277. }
  12278. // Uniforms
  12279. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12280. var uniformBuffer = _c[_b];
  12281. uniformBuffer._rebuild();
  12282. }
  12283. };
  12284. Engine.prototype._initGLContext = function () {
  12285. // Caps
  12286. this._caps = new EngineCapabilities();
  12287. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12288. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12289. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12290. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12291. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12292. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12293. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12294. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12295. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12296. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12297. // Infos
  12298. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12299. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12300. if (rendererInfo != null) {
  12301. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12302. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12303. }
  12304. if (!this._glVendor) {
  12305. this._glVendor = "Unknown vendor";
  12306. }
  12307. if (!this._glRenderer) {
  12308. this._glRenderer = "Unknown renderer";
  12309. }
  12310. // Constants
  12311. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12312. if (this._gl.RGBA16F !== 0x881A) {
  12313. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12314. }
  12315. if (this._gl.RGBA32F !== 0x8814) {
  12316. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12317. }
  12318. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12319. this._gl.DEPTH24_STENCIL8 = 35056;
  12320. }
  12321. // Extensions
  12322. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12323. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12324. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12325. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12326. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12327. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12328. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12329. 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');
  12330. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12331. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12332. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12333. this._caps.highPrecisionShaderSupported = true;
  12334. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12335. if (this._caps.timerQuery) {
  12336. if (this._webGLVersion === 1) {
  12337. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12338. }
  12339. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12340. }
  12341. // Checks if some of the format renders first to allow the use of webgl inspector.
  12342. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12343. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12344. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12345. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12346. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12347. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12348. if (this._webGLVersion > 1) {
  12349. this._gl.HALF_FLOAT_OES = 0x140B;
  12350. }
  12351. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12352. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12353. // Draw buffers
  12354. if (this._webGLVersion > 1) {
  12355. this._caps.drawBuffersExtension = true;
  12356. }
  12357. else {
  12358. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12359. if (drawBuffersExtension !== null) {
  12360. this._caps.drawBuffersExtension = true;
  12361. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12362. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12363. for (var i = 0; i < 16; i++) {
  12364. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12365. }
  12366. }
  12367. else {
  12368. this._caps.drawBuffersExtension = false;
  12369. }
  12370. }
  12371. // Depth Texture
  12372. if (this._webGLVersion > 1) {
  12373. this._caps.depthTextureExtension = true;
  12374. }
  12375. else {
  12376. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12377. if (depthTextureExtension != null) {
  12378. this._caps.depthTextureExtension = true;
  12379. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12380. }
  12381. }
  12382. // Vertex array object
  12383. if (this._webGLVersion > 1) {
  12384. this._caps.vertexArrayObject = true;
  12385. }
  12386. else {
  12387. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12388. if (vertexArrayObjectExtension != null) {
  12389. this._caps.vertexArrayObject = true;
  12390. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12391. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12392. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12393. }
  12394. else {
  12395. this._caps.vertexArrayObject = false;
  12396. }
  12397. }
  12398. // Instances count
  12399. if (this._webGLVersion > 1) {
  12400. this._caps.instancedArrays = true;
  12401. }
  12402. else {
  12403. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12404. if (instanceExtension != null) {
  12405. this._caps.instancedArrays = true;
  12406. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12407. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12408. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12409. }
  12410. else {
  12411. this._caps.instancedArrays = false;
  12412. }
  12413. }
  12414. // Intelligently add supported compressed formats in order to check for.
  12415. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12416. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12417. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12418. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12419. if (this._caps.astc)
  12420. this.texturesSupported.push('-astc.ktx');
  12421. if (this._caps.s3tc)
  12422. this.texturesSupported.push('-dxt.ktx');
  12423. if (this._caps.pvrtc)
  12424. this.texturesSupported.push('-pvrtc.ktx');
  12425. if (this._caps.etc2)
  12426. this.texturesSupported.push('-etc2.ktx');
  12427. if (this._caps.etc1)
  12428. this.texturesSupported.push('-etc1.ktx');
  12429. if (this._gl.getShaderPrecisionFormat) {
  12430. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12431. if (highp) {
  12432. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12433. }
  12434. }
  12435. // Depth buffer
  12436. this.setDepthBuffer(true);
  12437. this.setDepthFunctionToLessOrEqual();
  12438. this.setDepthWrite(true);
  12439. // Texture maps
  12440. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12441. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12442. this._nextFreeTextureSlots.push(slot);
  12443. }
  12444. };
  12445. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12446. /**
  12447. * Gets version of the current webGL context
  12448. */
  12449. get: function () {
  12450. return this._webGLVersion;
  12451. },
  12452. enumerable: true,
  12453. configurable: true
  12454. });
  12455. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12456. /**
  12457. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12458. */
  12459. get: function () {
  12460. return this._isStencilEnable;
  12461. },
  12462. enumerable: true,
  12463. configurable: true
  12464. });
  12465. Engine.prototype._prepareWorkingCanvas = function () {
  12466. if (this._workingCanvas) {
  12467. return;
  12468. }
  12469. this._workingCanvas = document.createElement("canvas");
  12470. var context = this._workingCanvas.getContext("2d");
  12471. if (context) {
  12472. this._workingContext = context;
  12473. }
  12474. };
  12475. /**
  12476. * Reset the texture cache to empty state
  12477. */
  12478. Engine.prototype.resetTextureCache = function () {
  12479. for (var key in this._boundTexturesCache) {
  12480. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12481. continue;
  12482. }
  12483. var boundTexture = this._boundTexturesCache[key];
  12484. if (boundTexture) {
  12485. this._removeDesignatedSlot(boundTexture);
  12486. }
  12487. this._boundTexturesCache[key] = null;
  12488. }
  12489. if (!this.disableTextureBindingOptimization) {
  12490. this._nextFreeTextureSlots = [];
  12491. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12492. this._nextFreeTextureSlots.push(slot);
  12493. }
  12494. }
  12495. this._currentTextureChannel = -1;
  12496. };
  12497. /**
  12498. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12499. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12500. * @returns true if engine is in deterministic lock step mode
  12501. */
  12502. Engine.prototype.isDeterministicLockStep = function () {
  12503. return this._deterministicLockstep;
  12504. };
  12505. /**
  12506. * Gets the max steps when engine is running in deterministic lock step
  12507. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12508. * @returns the max steps
  12509. */
  12510. Engine.prototype.getLockstepMaxSteps = function () {
  12511. return this._lockstepMaxSteps;
  12512. };
  12513. /**
  12514. * Gets an object containing information about the current webGL context
  12515. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12516. */
  12517. Engine.prototype.getGlInfo = function () {
  12518. return {
  12519. vendor: this._glVendor,
  12520. renderer: this._glRenderer,
  12521. version: this._glVersion
  12522. };
  12523. };
  12524. /**
  12525. * Gets current aspect ratio
  12526. * @param camera defines the camera to use to get the aspect ratio
  12527. * @param useScreen defines if screen size must be used (or the current render target if any)
  12528. * @returns a number defining the aspect ratio
  12529. */
  12530. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12531. if (useScreen === void 0) { useScreen = false; }
  12532. var viewport = camera.viewport;
  12533. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12534. };
  12535. /**
  12536. * Gets current screen aspect ratio
  12537. * @returns a number defining the aspect ratio
  12538. */
  12539. Engine.prototype.getScreenAspectRatio = function () {
  12540. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12541. };
  12542. /**
  12543. * Gets the current render width
  12544. * @param useScreen defines if screen size must be used (or the current render target if any)
  12545. * @returns a number defining the current render width
  12546. */
  12547. Engine.prototype.getRenderWidth = function (useScreen) {
  12548. if (useScreen === void 0) { useScreen = false; }
  12549. if (!useScreen && this._currentRenderTarget) {
  12550. return this._currentRenderTarget.width;
  12551. }
  12552. return this._gl.drawingBufferWidth;
  12553. };
  12554. /**
  12555. * Gets the current render height
  12556. * @param useScreen defines if screen size must be used (or the current render target if any)
  12557. * @returns a number defining the current render height
  12558. */
  12559. Engine.prototype.getRenderHeight = function (useScreen) {
  12560. if (useScreen === void 0) { useScreen = false; }
  12561. if (!useScreen && this._currentRenderTarget) {
  12562. return this._currentRenderTarget.height;
  12563. }
  12564. return this._gl.drawingBufferHeight;
  12565. };
  12566. /**
  12567. * Gets the HTML canvas attached with the current webGL context
  12568. * @returns a HTML canvas
  12569. */
  12570. Engine.prototype.getRenderingCanvas = function () {
  12571. return this._renderingCanvas;
  12572. };
  12573. /**
  12574. * Gets the client rect of the HTML canvas attached with the current webGL context
  12575. * @returns a client rectanglee
  12576. */
  12577. Engine.prototype.getRenderingCanvasClientRect = function () {
  12578. if (!this._renderingCanvas) {
  12579. return null;
  12580. }
  12581. return this._renderingCanvas.getBoundingClientRect();
  12582. };
  12583. /**
  12584. * Defines the hardware scaling level.
  12585. * By default the hardware scaling level is computed from the window device ratio.
  12586. * 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.
  12587. * @param level defines the level to use
  12588. */
  12589. Engine.prototype.setHardwareScalingLevel = function (level) {
  12590. this._hardwareScalingLevel = level;
  12591. this.resize();
  12592. };
  12593. /**
  12594. * Gets the current hardware scaling level.
  12595. * By default the hardware scaling level is computed from the window device ratio.
  12596. * 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.
  12597. * @returns a number indicating the current hardware scaling level
  12598. */
  12599. Engine.prototype.getHardwareScalingLevel = function () {
  12600. return this._hardwareScalingLevel;
  12601. };
  12602. /**
  12603. * Gets the list of loaded textures
  12604. * @returns an array containing all loaded textures
  12605. */
  12606. Engine.prototype.getLoadedTexturesCache = function () {
  12607. return this._internalTexturesCache;
  12608. };
  12609. /**
  12610. * Gets the object containing all engine capabilities
  12611. * @returns the EngineCapabilities object
  12612. */
  12613. Engine.prototype.getCaps = function () {
  12614. return this._caps;
  12615. };
  12616. Object.defineProperty(Engine.prototype, "drawCalls", {
  12617. /** @hidden */
  12618. get: function () {
  12619. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12620. return 0;
  12621. },
  12622. enumerable: true,
  12623. configurable: true
  12624. });
  12625. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12626. /** @hidden */
  12627. get: function () {
  12628. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12629. return null;
  12630. },
  12631. enumerable: true,
  12632. configurable: true
  12633. });
  12634. /**
  12635. * Gets the current depth function
  12636. * @returns a number defining the depth function
  12637. */
  12638. Engine.prototype.getDepthFunction = function () {
  12639. return this._depthCullingState.depthFunc;
  12640. };
  12641. /**
  12642. * Sets the current depth function
  12643. * @param depthFunc defines the function to use
  12644. */
  12645. Engine.prototype.setDepthFunction = function (depthFunc) {
  12646. this._depthCullingState.depthFunc = depthFunc;
  12647. };
  12648. /**
  12649. * Sets the current depth function to GREATER
  12650. */
  12651. Engine.prototype.setDepthFunctionToGreater = function () {
  12652. this._depthCullingState.depthFunc = this._gl.GREATER;
  12653. };
  12654. /**
  12655. * Sets the current depth function to GEQUAL
  12656. */
  12657. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12658. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12659. };
  12660. /**
  12661. * Sets the current depth function to LESS
  12662. */
  12663. Engine.prototype.setDepthFunctionToLess = function () {
  12664. this._depthCullingState.depthFunc = this._gl.LESS;
  12665. };
  12666. /**
  12667. * Sets the current depth function to LEQUAL
  12668. */
  12669. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12670. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12671. };
  12672. /**
  12673. * Gets a boolean indicating if stencil buffer is enabled
  12674. * @returns the current stencil buffer state
  12675. */
  12676. Engine.prototype.getStencilBuffer = function () {
  12677. return this._stencilState.stencilTest;
  12678. };
  12679. /**
  12680. * Enable or disable the stencil buffer
  12681. * @param enable defines if the stencil buffer must be enabled or disabled
  12682. */
  12683. Engine.prototype.setStencilBuffer = function (enable) {
  12684. this._stencilState.stencilTest = enable;
  12685. };
  12686. /**
  12687. * Gets the current stencil mask
  12688. * @returns a number defining the new stencil mask to use
  12689. */
  12690. Engine.prototype.getStencilMask = function () {
  12691. return this._stencilState.stencilMask;
  12692. };
  12693. /**
  12694. * Sets the current stencil mask
  12695. * @param mask defines the new stencil mask to use
  12696. */
  12697. Engine.prototype.setStencilMask = function (mask) {
  12698. this._stencilState.stencilMask = mask;
  12699. };
  12700. /**
  12701. * Gets the current stencil function
  12702. * @returns a number defining the stencil function to use
  12703. */
  12704. Engine.prototype.getStencilFunction = function () {
  12705. return this._stencilState.stencilFunc;
  12706. };
  12707. /**
  12708. * Gets the current stencil reference value
  12709. * @returns a number defining the stencil reference value to use
  12710. */
  12711. Engine.prototype.getStencilFunctionReference = function () {
  12712. return this._stencilState.stencilFuncRef;
  12713. };
  12714. /**
  12715. * Gets the current stencil mask
  12716. * @returns a number defining the stencil mask to use
  12717. */
  12718. Engine.prototype.getStencilFunctionMask = function () {
  12719. return this._stencilState.stencilFuncMask;
  12720. };
  12721. /**
  12722. * Sets the current stencil function
  12723. * @param stencilFunc defines the new stencil function to use
  12724. */
  12725. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12726. this._stencilState.stencilFunc = stencilFunc;
  12727. };
  12728. /**
  12729. * Sets the current stencil reference
  12730. * @param reference defines the new stencil reference to use
  12731. */
  12732. Engine.prototype.setStencilFunctionReference = function (reference) {
  12733. this._stencilState.stencilFuncRef = reference;
  12734. };
  12735. /**
  12736. * Sets the current stencil mask
  12737. * @param mask defines the new stencil mask to use
  12738. */
  12739. Engine.prototype.setStencilFunctionMask = function (mask) {
  12740. this._stencilState.stencilFuncMask = mask;
  12741. };
  12742. /**
  12743. * Gets the current stencil operation when stencil fails
  12744. * @returns a number defining stencil operation to use when stencil fails
  12745. */
  12746. Engine.prototype.getStencilOperationFail = function () {
  12747. return this._stencilState.stencilOpStencilFail;
  12748. };
  12749. /**
  12750. * Gets the current stencil operation when depth fails
  12751. * @returns a number defining stencil operation to use when depth fails
  12752. */
  12753. Engine.prototype.getStencilOperationDepthFail = function () {
  12754. return this._stencilState.stencilOpDepthFail;
  12755. };
  12756. /**
  12757. * Gets the current stencil operation when stencil passes
  12758. * @returns a number defining stencil operation to use when stencil passes
  12759. */
  12760. Engine.prototype.getStencilOperationPass = function () {
  12761. return this._stencilState.stencilOpStencilDepthPass;
  12762. };
  12763. /**
  12764. * Sets the stencil operation to use when stencil fails
  12765. * @param operation defines the stencil operation to use when stencil fails
  12766. */
  12767. Engine.prototype.setStencilOperationFail = function (operation) {
  12768. this._stencilState.stencilOpStencilFail = operation;
  12769. };
  12770. /**
  12771. * Sets the stencil operation to use when depth fails
  12772. * @param operation defines the stencil operation to use when depth fails
  12773. */
  12774. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12775. this._stencilState.stencilOpDepthFail = operation;
  12776. };
  12777. /**
  12778. * Sets the stencil operation to use when stencil passes
  12779. * @param operation defines the stencil operation to use when stencil passes
  12780. */
  12781. Engine.prototype.setStencilOperationPass = function (operation) {
  12782. this._stencilState.stencilOpStencilDepthPass = operation;
  12783. };
  12784. /**
  12785. * Sets a boolean indicating if the dithering state is enabled or disabled
  12786. * @param value defines the dithering state
  12787. */
  12788. Engine.prototype.setDitheringState = function (value) {
  12789. if (value) {
  12790. this._gl.enable(this._gl.DITHER);
  12791. }
  12792. else {
  12793. this._gl.disable(this._gl.DITHER);
  12794. }
  12795. };
  12796. /**
  12797. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12798. * @param value defines the rasterizer state
  12799. */
  12800. Engine.prototype.setRasterizerState = function (value) {
  12801. if (value) {
  12802. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12803. }
  12804. else {
  12805. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12806. }
  12807. };
  12808. /**
  12809. * stop executing a render loop function and remove it from the execution array
  12810. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12811. */
  12812. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12813. if (!renderFunction) {
  12814. this._activeRenderLoops = [];
  12815. return;
  12816. }
  12817. var index = this._activeRenderLoops.indexOf(renderFunction);
  12818. if (index >= 0) {
  12819. this._activeRenderLoops.splice(index, 1);
  12820. }
  12821. };
  12822. /** @hidden */
  12823. Engine.prototype._renderLoop = function () {
  12824. if (!this._contextWasLost) {
  12825. var shouldRender = true;
  12826. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12827. shouldRender = false;
  12828. }
  12829. if (shouldRender) {
  12830. // Start new frame
  12831. this.beginFrame();
  12832. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12833. var renderFunction = this._activeRenderLoops[index];
  12834. renderFunction();
  12835. }
  12836. // Present
  12837. this.endFrame();
  12838. }
  12839. }
  12840. if (this._activeRenderLoops.length > 0) {
  12841. // Register new frame
  12842. var requester = null;
  12843. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12844. requester = this._vrDisplay;
  12845. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12846. }
  12847. else {
  12848. this._renderingQueueLaunched = false;
  12849. }
  12850. };
  12851. /**
  12852. * Register and execute a render loop. The engine can have more than one render function
  12853. * @param renderFunction defines the function to continuously execute
  12854. */
  12855. Engine.prototype.runRenderLoop = function (renderFunction) {
  12856. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12857. return;
  12858. }
  12859. this._activeRenderLoops.push(renderFunction);
  12860. if (!this._renderingQueueLaunched) {
  12861. this._renderingQueueLaunched = true;
  12862. this._bindedRenderFunction = this._renderLoop.bind(this);
  12863. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12864. }
  12865. };
  12866. /**
  12867. * Toggle full screen mode
  12868. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12869. * @param options defines an option object to be sent to the requestFullscreen function
  12870. */
  12871. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12872. if (this.isFullscreen) {
  12873. BABYLON.Tools.ExitFullscreen();
  12874. }
  12875. else {
  12876. this._pointerLockRequested = requestPointerLock;
  12877. if (this._renderingCanvas) {
  12878. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12879. }
  12880. }
  12881. };
  12882. /**
  12883. * Clear the current render buffer or the current render target (if any is set up)
  12884. * @param color defines the color to use
  12885. * @param backBuffer defines if the back buffer must be cleared
  12886. * @param depth defines if the depth buffer must be cleared
  12887. * @param stencil defines if the stencil buffer must be cleared
  12888. */
  12889. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12890. if (stencil === void 0) { stencil = false; }
  12891. this.applyStates();
  12892. var mode = 0;
  12893. if (backBuffer && color) {
  12894. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12895. mode |= this._gl.COLOR_BUFFER_BIT;
  12896. }
  12897. if (depth) {
  12898. this._gl.clearDepth(1.0);
  12899. mode |= this._gl.DEPTH_BUFFER_BIT;
  12900. }
  12901. if (stencil) {
  12902. this._gl.clearStencil(0);
  12903. mode |= this._gl.STENCIL_BUFFER_BIT;
  12904. }
  12905. this._gl.clear(mode);
  12906. };
  12907. /**
  12908. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12909. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12910. * @param y defines the y-coordinate of the corner of the clear rectangle
  12911. * @param width defines the width of the clear rectangle
  12912. * @param height defines the height of the clear rectangle
  12913. * @param clearColor defines the clear color
  12914. */
  12915. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12916. var gl = this._gl;
  12917. // Save state
  12918. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12919. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12920. // Change state
  12921. gl.enable(gl.SCISSOR_TEST);
  12922. gl.scissor(x, y, width, height);
  12923. // Clear
  12924. this.clear(clearColor, true, true, true);
  12925. // Restore state
  12926. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12927. if (curScissor === true) {
  12928. gl.enable(gl.SCISSOR_TEST);
  12929. }
  12930. else {
  12931. gl.disable(gl.SCISSOR_TEST);
  12932. }
  12933. };
  12934. /**
  12935. * Set the WebGL's viewport
  12936. * @param viewport defines the viewport element to be used
  12937. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12938. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12939. */
  12940. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12941. var width = requiredWidth || this.getRenderWidth();
  12942. var height = requiredHeight || this.getRenderHeight();
  12943. var x = viewport.x || 0;
  12944. var y = viewport.y || 0;
  12945. this._cachedViewport = viewport;
  12946. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12947. };
  12948. /**
  12949. * Directly set the WebGL Viewport
  12950. * @param x defines the x coordinate of the viewport (in screen space)
  12951. * @param y defines the y coordinate of the viewport (in screen space)
  12952. * @param width defines the width of the viewport (in screen space)
  12953. * @param height defines the height of the viewport (in screen space)
  12954. * @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
  12955. */
  12956. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12957. var currentViewport = this._cachedViewport;
  12958. this._cachedViewport = null;
  12959. this._gl.viewport(x, y, width, height);
  12960. return currentViewport;
  12961. };
  12962. /**
  12963. * Begin a new frame
  12964. */
  12965. Engine.prototype.beginFrame = function () {
  12966. this.onBeginFrameObservable.notifyObservers(this);
  12967. this._measureFps();
  12968. };
  12969. /**
  12970. * Enf the current frame
  12971. */
  12972. Engine.prototype.endFrame = function () {
  12973. // Force a flush in case we are using a bad OS.
  12974. if (this._badOS) {
  12975. this.flushFramebuffer();
  12976. }
  12977. // Submit frame to the vr device, if enabled
  12978. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12979. // TODO: We should only submit the frame if we read frameData successfully.
  12980. this._vrDisplay.submitFrame();
  12981. }
  12982. this.onEndFrameObservable.notifyObservers(this);
  12983. };
  12984. /**
  12985. * Resize the view according to the canvas' size
  12986. */
  12987. Engine.prototype.resize = function () {
  12988. // We're not resizing the size of the canvas while in VR mode & presenting
  12989. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12990. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12991. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12992. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12993. }
  12994. };
  12995. /**
  12996. * Force a specific size of the canvas
  12997. * @param width defines the new canvas' width
  12998. * @param height defines the new canvas' height
  12999. */
  13000. Engine.prototype.setSize = function (width, height) {
  13001. if (!this._renderingCanvas) {
  13002. return;
  13003. }
  13004. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13005. return;
  13006. }
  13007. this._renderingCanvas.width = width;
  13008. this._renderingCanvas.height = height;
  13009. for (var index = 0; index < this.scenes.length; index++) {
  13010. var scene = this.scenes[index];
  13011. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13012. var cam = scene.cameras[camIndex];
  13013. cam._currentRenderId = 0;
  13014. }
  13015. }
  13016. if (this.onResizeObservable.hasObservers) {
  13017. this.onResizeObservable.notifyObservers(this);
  13018. }
  13019. };
  13020. // WebVR functions
  13021. /**
  13022. * Gets a boolean indicating if a webVR device was detected
  13023. * @returns true if a webVR device was detected
  13024. */
  13025. Engine.prototype.isVRDevicePresent = function () {
  13026. return !!this._vrDisplay;
  13027. };
  13028. /**
  13029. * Gets the current webVR device
  13030. * @returns the current webVR device (or null)
  13031. */
  13032. Engine.prototype.getVRDevice = function () {
  13033. return this._vrDisplay;
  13034. };
  13035. /**
  13036. * Initializes a webVR display and starts listening to display change events
  13037. * The onVRDisplayChangedObservable will be notified upon these changes
  13038. * @returns The onVRDisplayChangedObservable
  13039. */
  13040. Engine.prototype.initWebVR = function () {
  13041. this.initWebVRAsync();
  13042. return this.onVRDisplayChangedObservable;
  13043. };
  13044. /**
  13045. * Initializes a webVR display and starts listening to display change events
  13046. * The onVRDisplayChangedObservable will be notified upon these changes
  13047. * @returns A promise containing a VRDisplay and if vr is supported
  13048. */
  13049. Engine.prototype.initWebVRAsync = function () {
  13050. var _this = this;
  13051. var notifyObservers = function () {
  13052. var eventArgs = {
  13053. vrDisplay: _this._vrDisplay,
  13054. vrSupported: _this._vrSupported
  13055. };
  13056. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13057. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13058. };
  13059. if (!this._onVrDisplayConnect) {
  13060. this._onVrDisplayConnect = function (event) {
  13061. _this._vrDisplay = event.display;
  13062. notifyObservers();
  13063. };
  13064. this._onVrDisplayDisconnect = function () {
  13065. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13066. _this._vrDisplay = undefined;
  13067. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13068. notifyObservers();
  13069. };
  13070. this._onVrDisplayPresentChange = function () {
  13071. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13072. };
  13073. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13074. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13075. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13076. }
  13077. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13078. this._webVRInitPromise.then(notifyObservers);
  13079. return this._webVRInitPromise;
  13080. };
  13081. /**
  13082. * Call this function to switch to webVR mode
  13083. * Will do nothing if webVR is not supported or if there is no webVR device
  13084. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13085. */
  13086. Engine.prototype.enableVR = function () {
  13087. var _this = this;
  13088. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13089. var onResolved = function () {
  13090. _this.onVRRequestPresentComplete.notifyObservers(true);
  13091. _this._onVRFullScreenTriggered();
  13092. };
  13093. var onRejected = function () {
  13094. _this.onVRRequestPresentComplete.notifyObservers(false);
  13095. };
  13096. this.onVRRequestPresentStart.notifyObservers(this);
  13097. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13098. }
  13099. };
  13100. /**
  13101. * Call this function to leave webVR mode
  13102. * Will do nothing if webVR is not supported or if there is no webVR device
  13103. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13104. */
  13105. Engine.prototype.disableVR = function () {
  13106. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13107. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13108. }
  13109. };
  13110. Engine.prototype._getVRDisplaysAsync = function () {
  13111. var _this = this;
  13112. return new Promise(function (res, rej) {
  13113. if (navigator.getVRDisplays) {
  13114. navigator.getVRDisplays().then(function (devices) {
  13115. _this._vrSupported = true;
  13116. // note that devices may actually be an empty array. This is fine;
  13117. // we expect this._vrDisplay to be undefined in this case.
  13118. _this._vrDisplay = devices[0];
  13119. res({
  13120. vrDisplay: _this._vrDisplay,
  13121. vrSupported: _this._vrSupported
  13122. });
  13123. });
  13124. }
  13125. else {
  13126. _this._vrDisplay = undefined;
  13127. _this._vrSupported = false;
  13128. res({
  13129. vrDisplay: _this._vrDisplay,
  13130. vrSupported: _this._vrSupported
  13131. });
  13132. }
  13133. });
  13134. };
  13135. /**
  13136. * Binds the frame buffer to the specified texture.
  13137. * @param texture The texture to render to or null for the default canvas
  13138. * @param faceIndex The face of the texture to render to in case of cube texture
  13139. * @param requiredWidth The width of the target to render to
  13140. * @param requiredHeight The height of the target to render to
  13141. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13142. * @param depthStencilTexture The depth stencil texture to use to render
  13143. * @param lodLevel defines le lod level to bind to the frame buffer
  13144. */
  13145. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13146. if (lodLevel === void 0) { lodLevel = 0; }
  13147. if (this._currentRenderTarget) {
  13148. this.unBindFramebuffer(this._currentRenderTarget);
  13149. }
  13150. this._currentRenderTarget = texture;
  13151. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13152. var gl = this._gl;
  13153. if (texture.isCube) {
  13154. if (faceIndex === undefined) {
  13155. faceIndex = 0;
  13156. }
  13157. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13158. if (depthStencilTexture) {
  13159. if (depthStencilTexture._generateStencilBuffer) {
  13160. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13161. }
  13162. else {
  13163. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13164. }
  13165. }
  13166. }
  13167. if (this._cachedViewport && !forceFullscreenViewport) {
  13168. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13169. }
  13170. else {
  13171. if (!requiredWidth) {
  13172. requiredWidth = texture.width;
  13173. if (lodLevel) {
  13174. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13175. }
  13176. }
  13177. if (!requiredHeight) {
  13178. requiredHeight = texture.height;
  13179. if (lodLevel) {
  13180. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13181. }
  13182. }
  13183. gl.viewport(0, 0, requiredWidth, requiredHeight);
  13184. }
  13185. this.wipeCaches();
  13186. };
  13187. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13188. if (this._currentFramebuffer !== framebuffer) {
  13189. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13190. this._currentFramebuffer = framebuffer;
  13191. }
  13192. };
  13193. /**
  13194. * Unbind the current render target texture from the webGL context
  13195. * @param texture defines the render target texture to unbind
  13196. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13197. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13198. */
  13199. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13200. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13201. this._currentRenderTarget = null;
  13202. // If MSAA, we need to bitblt back to main texture
  13203. var gl = this._gl;
  13204. if (texture._MSAAFramebuffer) {
  13205. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13206. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13207. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13208. }
  13209. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13210. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13211. gl.generateMipmap(gl.TEXTURE_2D);
  13212. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13213. }
  13214. if (onBeforeUnbind) {
  13215. if (texture._MSAAFramebuffer) {
  13216. // Bind the correct framebuffer
  13217. this.bindUnboundFramebuffer(texture._framebuffer);
  13218. }
  13219. onBeforeUnbind();
  13220. }
  13221. this.bindUnboundFramebuffer(null);
  13222. };
  13223. /**
  13224. * Unbind a list of render target textures from the webGL context
  13225. * This is used only when drawBuffer extension or webGL2 are active
  13226. * @param textures defines the render target textures to unbind
  13227. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13228. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13229. */
  13230. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13231. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13232. this._currentRenderTarget = null;
  13233. // If MSAA, we need to bitblt back to main texture
  13234. var gl = this._gl;
  13235. if (textures[0]._MSAAFramebuffer) {
  13236. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13237. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13238. var attachments = textures[0]._attachments;
  13239. if (!attachments) {
  13240. attachments = new Array(textures.length);
  13241. textures[0]._attachments = attachments;
  13242. }
  13243. for (var i = 0; i < textures.length; i++) {
  13244. var texture = textures[i];
  13245. for (var j = 0; j < attachments.length; j++) {
  13246. attachments[j] = gl.NONE;
  13247. }
  13248. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13249. gl.readBuffer(attachments[i]);
  13250. gl.drawBuffers(attachments);
  13251. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13252. }
  13253. for (var i = 0; i < attachments.length; i++) {
  13254. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13255. }
  13256. gl.drawBuffers(attachments);
  13257. }
  13258. for (var i = 0; i < textures.length; i++) {
  13259. var texture = textures[i];
  13260. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13261. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13262. gl.generateMipmap(gl.TEXTURE_2D);
  13263. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13264. }
  13265. }
  13266. if (onBeforeUnbind) {
  13267. if (textures[0]._MSAAFramebuffer) {
  13268. // Bind the correct framebuffer
  13269. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13270. }
  13271. onBeforeUnbind();
  13272. }
  13273. this.bindUnboundFramebuffer(null);
  13274. };
  13275. /**
  13276. * Force the mipmap generation for the given render target texture
  13277. * @param texture defines the render target texture to use
  13278. */
  13279. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13280. if (texture.generateMipMaps) {
  13281. var gl = this._gl;
  13282. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13283. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13284. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13285. }
  13286. };
  13287. /**
  13288. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13289. */
  13290. Engine.prototype.flushFramebuffer = function () {
  13291. this._gl.flush();
  13292. };
  13293. /**
  13294. * Unbind the current render target and bind the default framebuffer
  13295. */
  13296. Engine.prototype.restoreDefaultFramebuffer = function () {
  13297. if (this._currentRenderTarget) {
  13298. this.unBindFramebuffer(this._currentRenderTarget);
  13299. }
  13300. else {
  13301. this.bindUnboundFramebuffer(null);
  13302. }
  13303. if (this._cachedViewport) {
  13304. this.setViewport(this._cachedViewport);
  13305. }
  13306. this.wipeCaches();
  13307. };
  13308. // UBOs
  13309. /**
  13310. * Create an uniform buffer
  13311. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13312. * @param elements defines the content of the uniform buffer
  13313. * @returns the webGL uniform buffer
  13314. */
  13315. Engine.prototype.createUniformBuffer = function (elements) {
  13316. var ubo = this._gl.createBuffer();
  13317. if (!ubo) {
  13318. throw new Error("Unable to create uniform buffer");
  13319. }
  13320. this.bindUniformBuffer(ubo);
  13321. if (elements instanceof Float32Array) {
  13322. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13323. }
  13324. else {
  13325. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13326. }
  13327. this.bindUniformBuffer(null);
  13328. ubo.references = 1;
  13329. return ubo;
  13330. };
  13331. /**
  13332. * Create a dynamic uniform buffer
  13333. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13334. * @param elements defines the content of the uniform buffer
  13335. * @returns the webGL uniform buffer
  13336. */
  13337. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13338. var ubo = this._gl.createBuffer();
  13339. if (!ubo) {
  13340. throw new Error("Unable to create dynamic uniform buffer");
  13341. }
  13342. this.bindUniformBuffer(ubo);
  13343. if (elements instanceof Float32Array) {
  13344. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13345. }
  13346. else {
  13347. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13348. }
  13349. this.bindUniformBuffer(null);
  13350. ubo.references = 1;
  13351. return ubo;
  13352. };
  13353. /**
  13354. * Update an existing uniform buffer
  13355. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13356. * @param uniformBuffer defines the target uniform buffer
  13357. * @param elements defines the content to update
  13358. * @param offset defines the offset in the uniform buffer where update should start
  13359. * @param count defines the size of the data to update
  13360. */
  13361. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13362. this.bindUniformBuffer(uniformBuffer);
  13363. if (offset === undefined) {
  13364. offset = 0;
  13365. }
  13366. if (count === undefined) {
  13367. if (elements instanceof Float32Array) {
  13368. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13369. }
  13370. else {
  13371. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13372. }
  13373. }
  13374. else {
  13375. if (elements instanceof Float32Array) {
  13376. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13377. }
  13378. else {
  13379. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13380. }
  13381. }
  13382. this.bindUniformBuffer(null);
  13383. };
  13384. // VBOs
  13385. Engine.prototype._resetVertexBufferBinding = function () {
  13386. this.bindArrayBuffer(null);
  13387. this._cachedVertexBuffers = null;
  13388. };
  13389. /**
  13390. * Creates a vertex buffer
  13391. * @param data the data for the vertex buffer
  13392. * @returns the new WebGL static buffer
  13393. */
  13394. Engine.prototype.createVertexBuffer = function (data) {
  13395. var vbo = this._gl.createBuffer();
  13396. if (!vbo) {
  13397. throw new Error("Unable to create vertex buffer");
  13398. }
  13399. this.bindArrayBuffer(vbo);
  13400. if (data instanceof Array) {
  13401. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13402. }
  13403. else {
  13404. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13405. }
  13406. this._resetVertexBufferBinding();
  13407. vbo.references = 1;
  13408. return vbo;
  13409. };
  13410. /**
  13411. * Creates a dynamic vertex buffer
  13412. * @param data the data for the dynamic vertex buffer
  13413. * @returns the new WebGL dynamic buffer
  13414. */
  13415. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13416. var vbo = this._gl.createBuffer();
  13417. if (!vbo) {
  13418. throw new Error("Unable to create dynamic vertex buffer");
  13419. }
  13420. this.bindArrayBuffer(vbo);
  13421. if (data instanceof Array) {
  13422. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13423. }
  13424. else {
  13425. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13426. }
  13427. this._resetVertexBufferBinding();
  13428. vbo.references = 1;
  13429. return vbo;
  13430. };
  13431. /**
  13432. * Update a dynamic index buffer
  13433. * @param indexBuffer defines the target index buffer
  13434. * @param indices defines the data to update
  13435. * @param offset defines the offset in the target index buffer where update should start
  13436. */
  13437. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13438. if (offset === void 0) { offset = 0; }
  13439. // Force cache update
  13440. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13441. this.bindIndexBuffer(indexBuffer);
  13442. var arrayBuffer;
  13443. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13444. arrayBuffer = indices;
  13445. }
  13446. else {
  13447. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13448. }
  13449. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13450. this._resetIndexBufferBinding();
  13451. };
  13452. /**
  13453. * Updates a dynamic vertex buffer.
  13454. * @param vertexBuffer the vertex buffer to update
  13455. * @param data the data used to update the vertex buffer
  13456. * @param byteOffset the byte offset of the data
  13457. * @param byteLength the byte length of the data
  13458. */
  13459. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13460. this.bindArrayBuffer(vertexBuffer);
  13461. if (byteOffset === undefined) {
  13462. byteOffset = 0;
  13463. }
  13464. if (byteLength === undefined) {
  13465. if (data instanceof Array) {
  13466. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13467. }
  13468. else {
  13469. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13470. }
  13471. }
  13472. else {
  13473. if (data instanceof Array) {
  13474. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13475. }
  13476. else {
  13477. if (data instanceof ArrayBuffer) {
  13478. data = new Uint8Array(data, byteOffset, byteLength);
  13479. }
  13480. else {
  13481. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13482. }
  13483. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13484. }
  13485. }
  13486. this._resetVertexBufferBinding();
  13487. };
  13488. Engine.prototype._resetIndexBufferBinding = function () {
  13489. this.bindIndexBuffer(null);
  13490. this._cachedIndexBuffer = null;
  13491. };
  13492. /**
  13493. * Creates a new index buffer
  13494. * @param indices defines the content of the index buffer
  13495. * @param updatable defines if the index buffer must be updatable
  13496. * @returns a new webGL buffer
  13497. */
  13498. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13499. var vbo = this._gl.createBuffer();
  13500. if (!vbo) {
  13501. throw new Error("Unable to create index buffer");
  13502. }
  13503. this.bindIndexBuffer(vbo);
  13504. // Check for 32 bits indices
  13505. var arrayBuffer;
  13506. var need32Bits = false;
  13507. if (indices instanceof Uint16Array) {
  13508. arrayBuffer = indices;
  13509. }
  13510. else {
  13511. //check 32 bit support
  13512. if (this._caps.uintIndices) {
  13513. if (indices instanceof Uint32Array) {
  13514. arrayBuffer = indices;
  13515. need32Bits = true;
  13516. }
  13517. else {
  13518. //number[] or Int32Array, check if 32 bit is necessary
  13519. for (var index = 0; index < indices.length; index++) {
  13520. if (indices[index] > 65535) {
  13521. need32Bits = true;
  13522. break;
  13523. }
  13524. }
  13525. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13526. }
  13527. }
  13528. else {
  13529. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13530. arrayBuffer = new Uint16Array(indices);
  13531. }
  13532. }
  13533. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13534. this._resetIndexBufferBinding();
  13535. vbo.references = 1;
  13536. vbo.is32Bits = need32Bits;
  13537. return vbo;
  13538. };
  13539. /**
  13540. * Bind a webGL buffer to the webGL context
  13541. * @param buffer defines the buffer to bind
  13542. */
  13543. Engine.prototype.bindArrayBuffer = function (buffer) {
  13544. if (!this._vaoRecordInProgress) {
  13545. this._unbindVertexArrayObject();
  13546. }
  13547. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13548. };
  13549. /**
  13550. * Bind an uniform buffer to the current webGL context
  13551. * @param buffer defines the buffer to bind
  13552. */
  13553. Engine.prototype.bindUniformBuffer = function (buffer) {
  13554. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13555. };
  13556. /**
  13557. * Bind a buffer to the current webGL context at a given location
  13558. * @param buffer defines the buffer to bind
  13559. * @param location defines the index where to bind the buffer
  13560. */
  13561. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13562. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13563. };
  13564. /**
  13565. * Bind a specific block at a given index in a specific shader program
  13566. * @param shaderProgram defines the shader program
  13567. * @param blockName defines the block name
  13568. * @param index defines the index where to bind the block
  13569. */
  13570. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13571. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13572. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13573. };
  13574. ;
  13575. Engine.prototype.bindIndexBuffer = function (buffer) {
  13576. if (!this._vaoRecordInProgress) {
  13577. this._unbindVertexArrayObject();
  13578. }
  13579. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13580. };
  13581. Engine.prototype.bindBuffer = function (buffer, target) {
  13582. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13583. this._gl.bindBuffer(target, buffer);
  13584. this._currentBoundBuffer[target] = buffer;
  13585. }
  13586. };
  13587. /**
  13588. * update the bound buffer with the given data
  13589. * @param data defines the data to update
  13590. */
  13591. Engine.prototype.updateArrayBuffer = function (data) {
  13592. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13593. };
  13594. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13595. var pointer = this._currentBufferPointers[indx];
  13596. var changed = false;
  13597. if (!pointer.active) {
  13598. changed = true;
  13599. pointer.active = true;
  13600. pointer.index = indx;
  13601. pointer.size = size;
  13602. pointer.type = type;
  13603. pointer.normalized = normalized;
  13604. pointer.stride = stride;
  13605. pointer.offset = offset;
  13606. pointer.buffer = buffer;
  13607. }
  13608. else {
  13609. if (pointer.buffer !== buffer) {
  13610. pointer.buffer = buffer;
  13611. changed = true;
  13612. }
  13613. if (pointer.size !== size) {
  13614. pointer.size = size;
  13615. changed = true;
  13616. }
  13617. if (pointer.type !== type) {
  13618. pointer.type = type;
  13619. changed = true;
  13620. }
  13621. if (pointer.normalized !== normalized) {
  13622. pointer.normalized = normalized;
  13623. changed = true;
  13624. }
  13625. if (pointer.stride !== stride) {
  13626. pointer.stride = stride;
  13627. changed = true;
  13628. }
  13629. if (pointer.offset !== offset) {
  13630. pointer.offset = offset;
  13631. changed = true;
  13632. }
  13633. }
  13634. if (changed || this._vaoRecordInProgress) {
  13635. this.bindArrayBuffer(buffer);
  13636. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13637. }
  13638. };
  13639. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13640. if (indexBuffer == null) {
  13641. return;
  13642. }
  13643. if (this._cachedIndexBuffer !== indexBuffer) {
  13644. this._cachedIndexBuffer = indexBuffer;
  13645. this.bindIndexBuffer(indexBuffer);
  13646. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13647. }
  13648. };
  13649. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13650. var attributes = effect.getAttributesNames();
  13651. if (!this._vaoRecordInProgress) {
  13652. this._unbindVertexArrayObject();
  13653. }
  13654. this.unbindAllAttributes();
  13655. for (var index = 0; index < attributes.length; index++) {
  13656. var order = effect.getAttributeLocation(index);
  13657. if (order >= 0) {
  13658. var vertexBuffer = vertexBuffers[attributes[index]];
  13659. if (!vertexBuffer) {
  13660. continue;
  13661. }
  13662. this._gl.enableVertexAttribArray(order);
  13663. if (!this._vaoRecordInProgress) {
  13664. this._vertexAttribArraysEnabled[order] = true;
  13665. }
  13666. var buffer = vertexBuffer.getBuffer();
  13667. if (buffer) {
  13668. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13669. if (vertexBuffer.getIsInstanced()) {
  13670. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13671. if (!this._vaoRecordInProgress) {
  13672. this._currentInstanceLocations.push(order);
  13673. this._currentInstanceBuffers.push(buffer);
  13674. }
  13675. }
  13676. }
  13677. }
  13678. }
  13679. };
  13680. /**
  13681. * Records a vertex array object
  13682. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13683. * @param vertexBuffers defines the list of vertex buffers to store
  13684. * @param indexBuffer defines the index buffer to store
  13685. * @param effect defines the effect to store
  13686. * @returns the new vertex array object
  13687. */
  13688. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13689. var vao = this._gl.createVertexArray();
  13690. this._vaoRecordInProgress = true;
  13691. this._gl.bindVertexArray(vao);
  13692. this._mustWipeVertexAttributes = true;
  13693. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13694. this.bindIndexBuffer(indexBuffer);
  13695. this._vaoRecordInProgress = false;
  13696. this._gl.bindVertexArray(null);
  13697. return vao;
  13698. };
  13699. /**
  13700. * Bind a specific vertex array object
  13701. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13702. * @param vertexArrayObject defines the vertex array object to bind
  13703. * @param indexBuffer defines the index buffer to bind
  13704. */
  13705. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13706. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13707. this._cachedVertexArrayObject = vertexArrayObject;
  13708. this._gl.bindVertexArray(vertexArrayObject);
  13709. this._cachedVertexBuffers = null;
  13710. this._cachedIndexBuffer = null;
  13711. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13712. this._mustWipeVertexAttributes = true;
  13713. }
  13714. };
  13715. /**
  13716. * Bind webGl buffers directly to the webGL context
  13717. * @param vertexBuffer defines the vertex buffer to bind
  13718. * @param indexBuffer defines the index buffer to bind
  13719. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13720. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13721. * @param effect defines the effect associated with the vertex buffer
  13722. */
  13723. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13724. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13725. this._cachedVertexBuffers = vertexBuffer;
  13726. this._cachedEffectForVertexBuffers = effect;
  13727. var attributesCount = effect.getAttributesCount();
  13728. this._unbindVertexArrayObject();
  13729. this.unbindAllAttributes();
  13730. var offset = 0;
  13731. for (var index = 0; index < attributesCount; index++) {
  13732. if (index < vertexDeclaration.length) {
  13733. var order = effect.getAttributeLocation(index);
  13734. if (order >= 0) {
  13735. this._gl.enableVertexAttribArray(order);
  13736. this._vertexAttribArraysEnabled[order] = true;
  13737. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13738. }
  13739. offset += vertexDeclaration[index] * 4;
  13740. }
  13741. }
  13742. }
  13743. this._bindIndexBufferWithCache(indexBuffer);
  13744. };
  13745. Engine.prototype._unbindVertexArrayObject = function () {
  13746. if (!this._cachedVertexArrayObject) {
  13747. return;
  13748. }
  13749. this._cachedVertexArrayObject = null;
  13750. this._gl.bindVertexArray(null);
  13751. };
  13752. /**
  13753. * Bind a list of vertex buffers to the webGL context
  13754. * @param vertexBuffers defines the list of vertex buffers to bind
  13755. * @param indexBuffer defines the index buffer to bind
  13756. * @param effect defines the effect associated with the vertex buffers
  13757. */
  13758. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13759. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13760. this._cachedVertexBuffers = vertexBuffers;
  13761. this._cachedEffectForVertexBuffers = effect;
  13762. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13763. }
  13764. this._bindIndexBufferWithCache(indexBuffer);
  13765. };
  13766. /**
  13767. * Unbind all instance attributes
  13768. */
  13769. Engine.prototype.unbindInstanceAttributes = function () {
  13770. var boundBuffer;
  13771. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13772. var instancesBuffer = this._currentInstanceBuffers[i];
  13773. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13774. boundBuffer = instancesBuffer;
  13775. this.bindArrayBuffer(instancesBuffer);
  13776. }
  13777. var offsetLocation = this._currentInstanceLocations[i];
  13778. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13779. }
  13780. this._currentInstanceBuffers.length = 0;
  13781. this._currentInstanceLocations.length = 0;
  13782. };
  13783. /**
  13784. * Release and free the memory of a vertex array object
  13785. * @param vao defines the vertex array object to delete
  13786. */
  13787. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13788. this._gl.deleteVertexArray(vao);
  13789. };
  13790. /** @hidden */
  13791. Engine.prototype._releaseBuffer = function (buffer) {
  13792. buffer.references--;
  13793. if (buffer.references === 0) {
  13794. this._gl.deleteBuffer(buffer);
  13795. return true;
  13796. }
  13797. return false;
  13798. };
  13799. /**
  13800. * Creates a webGL buffer to use with instanciation
  13801. * @param capacity defines the size of the buffer
  13802. * @returns the webGL buffer
  13803. */
  13804. Engine.prototype.createInstancesBuffer = function (capacity) {
  13805. var buffer = this._gl.createBuffer();
  13806. if (!buffer) {
  13807. throw new Error("Unable to create instance buffer");
  13808. }
  13809. buffer.capacity = capacity;
  13810. this.bindArrayBuffer(buffer);
  13811. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13812. return buffer;
  13813. };
  13814. /**
  13815. * Delete a webGL buffer used with instanciation
  13816. * @param buffer defines the webGL buffer to delete
  13817. */
  13818. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13819. this._gl.deleteBuffer(buffer);
  13820. };
  13821. /**
  13822. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13823. * @param instancesBuffer defines the webGL buffer to update and bind
  13824. * @param data defines the data to store in the buffer
  13825. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13826. */
  13827. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13828. this.bindArrayBuffer(instancesBuffer);
  13829. if (data) {
  13830. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13831. }
  13832. if (offsetLocations[0].index !== undefined) {
  13833. var stride = 0;
  13834. for (var i = 0; i < offsetLocations.length; i++) {
  13835. var ai = offsetLocations[i];
  13836. stride += ai.attributeSize * 4;
  13837. }
  13838. for (var i = 0; i < offsetLocations.length; i++) {
  13839. var ai = offsetLocations[i];
  13840. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13841. this._gl.enableVertexAttribArray(ai.index);
  13842. this._vertexAttribArraysEnabled[ai.index] = true;
  13843. }
  13844. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13845. this._gl.vertexAttribDivisor(ai.index, 1);
  13846. this._currentInstanceLocations.push(ai.index);
  13847. this._currentInstanceBuffers.push(instancesBuffer);
  13848. }
  13849. }
  13850. else {
  13851. for (var index = 0; index < 4; index++) {
  13852. var offsetLocation = offsetLocations[index];
  13853. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13854. this._gl.enableVertexAttribArray(offsetLocation);
  13855. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13856. }
  13857. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13858. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13859. this._currentInstanceLocations.push(offsetLocation);
  13860. this._currentInstanceBuffers.push(instancesBuffer);
  13861. }
  13862. }
  13863. };
  13864. /**
  13865. * Apply all cached states (depth, culling, stencil and alpha)
  13866. */
  13867. Engine.prototype.applyStates = function () {
  13868. this._depthCullingState.apply(this._gl);
  13869. this._stencilState.apply(this._gl);
  13870. this._alphaState.apply(this._gl);
  13871. };
  13872. /**
  13873. * Send a draw order
  13874. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13875. * @param indexStart defines the starting index
  13876. * @param indexCount defines the number of index to draw
  13877. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13878. */
  13879. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13880. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13881. };
  13882. /**
  13883. * Draw a list of points
  13884. * @param verticesStart defines the index of first vertex to draw
  13885. * @param verticesCount defines the count of vertices to draw
  13886. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13887. */
  13888. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13889. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13890. };
  13891. /**
  13892. * Draw a list of unindexed primitives
  13893. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13894. * @param verticesStart defines the index of first vertex to draw
  13895. * @param verticesCount defines the count of vertices to draw
  13896. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13897. */
  13898. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13899. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13900. };
  13901. /**
  13902. * Draw a list of indexed primitives
  13903. * @param fillMode defines the primitive to use
  13904. * @param indexStart defines the starting index
  13905. * @param indexCount defines the number of index to draw
  13906. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13907. */
  13908. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13909. // Apply states
  13910. this.applyStates();
  13911. this._drawCalls.addCount(1, false);
  13912. // Render
  13913. var drawMode = this._drawMode(fillMode);
  13914. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13915. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13916. if (instancesCount) {
  13917. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13918. }
  13919. else {
  13920. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13921. }
  13922. };
  13923. /**
  13924. * Draw a list of unindexed primitives
  13925. * @param fillMode defines the primitive to use
  13926. * @param verticesStart defines the index of first vertex to draw
  13927. * @param verticesCount defines the count of vertices to draw
  13928. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13929. */
  13930. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13931. // Apply states
  13932. this.applyStates();
  13933. this._drawCalls.addCount(1, false);
  13934. var drawMode = this._drawMode(fillMode);
  13935. if (instancesCount) {
  13936. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13937. }
  13938. else {
  13939. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13940. }
  13941. };
  13942. Engine.prototype._drawMode = function (fillMode) {
  13943. switch (fillMode) {
  13944. // Triangle views
  13945. case BABYLON.Material.TriangleFillMode:
  13946. return this._gl.TRIANGLES;
  13947. case BABYLON.Material.PointFillMode:
  13948. return this._gl.POINTS;
  13949. case BABYLON.Material.WireFrameFillMode:
  13950. return this._gl.LINES;
  13951. // Draw modes
  13952. case BABYLON.Material.PointListDrawMode:
  13953. return this._gl.POINTS;
  13954. case BABYLON.Material.LineListDrawMode:
  13955. return this._gl.LINES;
  13956. case BABYLON.Material.LineLoopDrawMode:
  13957. return this._gl.LINE_LOOP;
  13958. case BABYLON.Material.LineStripDrawMode:
  13959. return this._gl.LINE_STRIP;
  13960. case BABYLON.Material.TriangleStripDrawMode:
  13961. return this._gl.TRIANGLE_STRIP;
  13962. case BABYLON.Material.TriangleFanDrawMode:
  13963. return this._gl.TRIANGLE_FAN;
  13964. default:
  13965. return this._gl.TRIANGLES;
  13966. }
  13967. };
  13968. // Shaders
  13969. /** @hidden */
  13970. Engine.prototype._releaseEffect = function (effect) {
  13971. if (this._compiledEffects[effect._key]) {
  13972. delete this._compiledEffects[effect._key];
  13973. this._deleteProgram(effect.getProgram());
  13974. }
  13975. };
  13976. /** @hidden */
  13977. Engine.prototype._deleteProgram = function (program) {
  13978. if (program) {
  13979. program.__SPECTOR_rebuildProgram = null;
  13980. if (program.transformFeedback) {
  13981. this.deleteTransformFeedback(program.transformFeedback);
  13982. program.transformFeedback = null;
  13983. }
  13984. this._gl.deleteProgram(program);
  13985. }
  13986. };
  13987. /**
  13988. * Create a new effect (used to store vertex/fragment shaders)
  13989. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13990. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13991. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13992. * @param samplers defines an array of string used to represent textures
  13993. * @param defines defines the string containing the defines to use to compile the shaders
  13994. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13995. * @param onCompiled defines a function to call when the effect creation is successful
  13996. * @param onError defines a function to call when the effect creation has failed
  13997. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13998. * @returns the new Effect
  13999. */
  14000. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14001. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14002. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14003. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14004. if (this._compiledEffects[name]) {
  14005. var compiledEffect = this._compiledEffects[name];
  14006. if (onCompiled && compiledEffect.isReady()) {
  14007. onCompiled(compiledEffect);
  14008. }
  14009. return compiledEffect;
  14010. }
  14011. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14012. effect._key = name;
  14013. this._compiledEffects[name] = effect;
  14014. return effect;
  14015. };
  14016. /**
  14017. * Create an effect to use with particle systems
  14018. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  14019. * @param uniformsNames defines a list of attribute names
  14020. * @param samplers defines an array of string used to represent textures
  14021. * @param defines defines the string containing the defines to use to compile the shaders
  14022. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14023. * @param onCompiled defines a function to call when the effect creation is successful
  14024. * @param onError defines a function to call when the effect creation has failed
  14025. * @returns the new Effect
  14026. */
  14027. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  14028. if (uniformsNames === void 0) { uniformsNames = []; }
  14029. if (samplers === void 0) { samplers = []; }
  14030. if (defines === void 0) { defines = ""; }
  14031. return this.createEffect({
  14032. vertex: "particles",
  14033. fragmentElement: fragmentName
  14034. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  14035. };
  14036. /**
  14037. * Directly creates a webGL program
  14038. * @param vertexCode defines the vertex shader code to use
  14039. * @param fragmentCode defines the fragment shader code to use
  14040. * @param context defines the webGL context to use (if not set, the current one will be used)
  14041. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14042. * @returns the new webGL program
  14043. */
  14044. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14045. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14046. context = context || this._gl;
  14047. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  14048. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  14049. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14050. };
  14051. /**
  14052. * Creates a webGL program
  14053. * @param vertexCode defines the vertex shader code to use
  14054. * @param fragmentCode defines the fragment shader code to use
  14055. * @param defines defines the string containing the defines to use to compile the shaders
  14056. * @param context defines the webGL context to use (if not set, the current one will be used)
  14057. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14058. * @returns the new webGL program
  14059. */
  14060. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14061. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14062. context = context || this._gl;
  14063. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14064. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14065. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  14066. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  14067. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14068. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14069. return program;
  14070. };
  14071. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14072. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14073. var shaderProgram = context.createProgram();
  14074. if (!shaderProgram) {
  14075. throw new Error("Unable to create program");
  14076. }
  14077. context.attachShader(shaderProgram, vertexShader);
  14078. context.attachShader(shaderProgram, fragmentShader);
  14079. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14080. var transformFeedback = this.createTransformFeedback();
  14081. this.bindTransformFeedback(transformFeedback);
  14082. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14083. shaderProgram.transformFeedback = transformFeedback;
  14084. }
  14085. context.linkProgram(shaderProgram);
  14086. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14087. this.bindTransformFeedback(null);
  14088. }
  14089. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14090. if (!linked) {
  14091. context.validateProgram(shaderProgram);
  14092. var error = context.getProgramInfoLog(shaderProgram);
  14093. if (error) {
  14094. throw new Error(error);
  14095. }
  14096. }
  14097. context.deleteShader(vertexShader);
  14098. context.deleteShader(fragmentShader);
  14099. return shaderProgram;
  14100. };
  14101. /**
  14102. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14103. * @param shaderProgram defines the webGL program to use
  14104. * @param uniformsNames defines the list of uniform names
  14105. * @returns an array of webGL uniform locations
  14106. */
  14107. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14108. var results = new Array();
  14109. for (var index = 0; index < uniformsNames.length; index++) {
  14110. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14111. }
  14112. return results;
  14113. };
  14114. /**
  14115. * Gets the lsit of active attributes for a given webGL program
  14116. * @param shaderProgram defines the webGL program to use
  14117. * @param attributesNames defines the list of attribute names to get
  14118. * @returns an array of indices indicating the offset of each attribute
  14119. */
  14120. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14121. var results = [];
  14122. for (var index = 0; index < attributesNames.length; index++) {
  14123. try {
  14124. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14125. }
  14126. catch (e) {
  14127. results.push(-1);
  14128. }
  14129. }
  14130. return results;
  14131. };
  14132. /**
  14133. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14134. * @param effect defines the effect to activate
  14135. */
  14136. Engine.prototype.enableEffect = function (effect) {
  14137. if (!effect) {
  14138. return;
  14139. }
  14140. // Use program
  14141. this.bindSamplers(effect);
  14142. this._currentEffect = effect;
  14143. if (effect.onBind) {
  14144. effect.onBind(effect);
  14145. }
  14146. effect.onBindObservable.notifyObservers(effect);
  14147. };
  14148. /**
  14149. * Set the value of an uniform to an array of int32
  14150. * @param uniform defines the webGL uniform location where to store the value
  14151. * @param array defines the array of int32 to store
  14152. */
  14153. Engine.prototype.setIntArray = function (uniform, array) {
  14154. if (!uniform)
  14155. return;
  14156. this._gl.uniform1iv(uniform, array);
  14157. };
  14158. /**
  14159. * Set the value of an uniform to an array of int32 (stored as vec2)
  14160. * @param uniform defines the webGL uniform location where to store the value
  14161. * @param array defines the array of int32 to store
  14162. */
  14163. Engine.prototype.setIntArray2 = function (uniform, array) {
  14164. if (!uniform || array.length % 2 !== 0)
  14165. return;
  14166. this._gl.uniform2iv(uniform, array);
  14167. };
  14168. /**
  14169. * Set the value of an uniform to an array of int32 (stored as vec3)
  14170. * @param uniform defines the webGL uniform location where to store the value
  14171. * @param array defines the array of int32 to store
  14172. */
  14173. Engine.prototype.setIntArray3 = function (uniform, array) {
  14174. if (!uniform || array.length % 3 !== 0)
  14175. return;
  14176. this._gl.uniform3iv(uniform, array);
  14177. };
  14178. /**
  14179. * Set the value of an uniform to an array of int32 (stored as vec4)
  14180. * @param uniform defines the webGL uniform location where to store the value
  14181. * @param array defines the array of int32 to store
  14182. */
  14183. Engine.prototype.setIntArray4 = function (uniform, array) {
  14184. if (!uniform || array.length % 4 !== 0)
  14185. return;
  14186. this._gl.uniform4iv(uniform, array);
  14187. };
  14188. /**
  14189. * Set the value of an uniform to an array of float32
  14190. * @param uniform defines the webGL uniform location where to store the value
  14191. * @param array defines the array of float32 to store
  14192. */
  14193. Engine.prototype.setFloatArray = function (uniform, array) {
  14194. if (!uniform)
  14195. return;
  14196. this._gl.uniform1fv(uniform, array);
  14197. };
  14198. /**
  14199. * Set the value of an uniform to an array of float32 (stored as vec2)
  14200. * @param uniform defines the webGL uniform location where to store the value
  14201. * @param array defines the array of float32 to store
  14202. */
  14203. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14204. if (!uniform || array.length % 2 !== 0)
  14205. return;
  14206. this._gl.uniform2fv(uniform, array);
  14207. };
  14208. /**
  14209. * Set the value of an uniform to an array of float32 (stored as vec3)
  14210. * @param uniform defines the webGL uniform location where to store the value
  14211. * @param array defines the array of float32 to store
  14212. */
  14213. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14214. if (!uniform || array.length % 3 !== 0)
  14215. return;
  14216. this._gl.uniform3fv(uniform, array);
  14217. };
  14218. /**
  14219. * Set the value of an uniform to an array of float32 (stored as vec4)
  14220. * @param uniform defines the webGL uniform location where to store the value
  14221. * @param array defines the array of float32 to store
  14222. */
  14223. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14224. if (!uniform || array.length % 4 !== 0)
  14225. return;
  14226. this._gl.uniform4fv(uniform, array);
  14227. };
  14228. /**
  14229. * Set the value of an uniform to an array of number
  14230. * @param uniform defines the webGL uniform location where to store the value
  14231. * @param array defines the array of number to store
  14232. */
  14233. Engine.prototype.setArray = function (uniform, array) {
  14234. if (!uniform)
  14235. return;
  14236. this._gl.uniform1fv(uniform, array);
  14237. };
  14238. /**
  14239. * Set the value of an uniform to an array of number (stored as vec2)
  14240. * @param uniform defines the webGL uniform location where to store the value
  14241. * @param array defines the array of number to store
  14242. */
  14243. Engine.prototype.setArray2 = function (uniform, array) {
  14244. if (!uniform || array.length % 2 !== 0)
  14245. return;
  14246. this._gl.uniform2fv(uniform, array);
  14247. };
  14248. /**
  14249. * Set the value of an uniform to an array of number (stored as vec3)
  14250. * @param uniform defines the webGL uniform location where to store the value
  14251. * @param array defines the array of number to store
  14252. */
  14253. Engine.prototype.setArray3 = function (uniform, array) {
  14254. if (!uniform || array.length % 3 !== 0)
  14255. return;
  14256. this._gl.uniform3fv(uniform, array);
  14257. };
  14258. /**
  14259. * Set the value of an uniform to an array of number (stored as vec4)
  14260. * @param uniform defines the webGL uniform location where to store the value
  14261. * @param array defines the array of number to store
  14262. */
  14263. Engine.prototype.setArray4 = function (uniform, array) {
  14264. if (!uniform || array.length % 4 !== 0)
  14265. return;
  14266. this._gl.uniform4fv(uniform, array);
  14267. };
  14268. /**
  14269. * Set the value of an uniform to an array of float32 (stored as matrices)
  14270. * @param uniform defines the webGL uniform location where to store the value
  14271. * @param matrices defines the array of float32 to store
  14272. */
  14273. Engine.prototype.setMatrices = function (uniform, matrices) {
  14274. if (!uniform)
  14275. return;
  14276. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14277. };
  14278. /**
  14279. * Set the value of an uniform to a matrix
  14280. * @param uniform defines the webGL uniform location where to store the value
  14281. * @param matrix defines the matrix to store
  14282. */
  14283. Engine.prototype.setMatrix = function (uniform, matrix) {
  14284. if (!uniform)
  14285. return;
  14286. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14287. };
  14288. /**
  14289. * Set the value of an uniform to a matrix (3x3)
  14290. * @param uniform defines the webGL uniform location where to store the value
  14291. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14292. */
  14293. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14294. if (!uniform)
  14295. return;
  14296. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14297. };
  14298. /**
  14299. * Set the value of an uniform to a matrix (2x2)
  14300. * @param uniform defines the webGL uniform location where to store the value
  14301. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14302. */
  14303. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14304. if (!uniform)
  14305. return;
  14306. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14307. };
  14308. /**
  14309. * Set the value of an uniform to a number (int)
  14310. * @param uniform defines the webGL uniform location where to store the value
  14311. * @param value defines the int number to store
  14312. */
  14313. Engine.prototype.setInt = function (uniform, value) {
  14314. if (!uniform)
  14315. return;
  14316. this._gl.uniform1i(uniform, value);
  14317. };
  14318. /**
  14319. * Set the value of an uniform to a number (float)
  14320. * @param uniform defines the webGL uniform location where to store the value
  14321. * @param value defines the float number to store
  14322. */
  14323. Engine.prototype.setFloat = function (uniform, value) {
  14324. if (!uniform)
  14325. return;
  14326. this._gl.uniform1f(uniform, value);
  14327. };
  14328. /**
  14329. * Set the value of an uniform to a vec2
  14330. * @param uniform defines the webGL uniform location where to store the value
  14331. * @param x defines the 1st component of the value
  14332. * @param y defines the 2nd component of the value
  14333. */
  14334. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14335. if (!uniform)
  14336. return;
  14337. this._gl.uniform2f(uniform, x, y);
  14338. };
  14339. /**
  14340. * Set the value of an uniform to a vec3
  14341. * @param uniform defines the webGL uniform location where to store the value
  14342. * @param x defines the 1st component of the value
  14343. * @param y defines the 2nd component of the value
  14344. * @param z defines the 3rd component of the value
  14345. */
  14346. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14347. if (!uniform)
  14348. return;
  14349. this._gl.uniform3f(uniform, x, y, z);
  14350. };
  14351. /**
  14352. * Set the value of an uniform to a boolean
  14353. * @param uniform defines the webGL uniform location where to store the value
  14354. * @param bool defines the boolean to store
  14355. */
  14356. Engine.prototype.setBool = function (uniform, bool) {
  14357. if (!uniform)
  14358. return;
  14359. this._gl.uniform1i(uniform, bool);
  14360. };
  14361. /**
  14362. * Set the value of an uniform to a vec4
  14363. * @param uniform defines the webGL uniform location where to store the value
  14364. * @param x defines the 1st component of the value
  14365. * @param y defines the 2nd component of the value
  14366. * @param z defines the 3rd component of the value
  14367. * @param w defines the 4th component of the value
  14368. */
  14369. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14370. if (!uniform)
  14371. return;
  14372. this._gl.uniform4f(uniform, x, y, z, w);
  14373. };
  14374. /**
  14375. * Set the value of an uniform to a Color3
  14376. * @param uniform defines the webGL uniform location where to store the value
  14377. * @param color3 defines the color to store
  14378. */
  14379. Engine.prototype.setColor3 = function (uniform, color3) {
  14380. if (!uniform)
  14381. return;
  14382. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14383. };
  14384. /**
  14385. * Set the value of an uniform to a Color3 and an alpha value
  14386. * @param uniform defines the webGL uniform location where to store the value
  14387. * @param color3 defines the color to store
  14388. * @param alpha defines the alpha component to store
  14389. */
  14390. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14391. if (!uniform)
  14392. return;
  14393. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14394. };
  14395. /**
  14396. * Sets a Color4 on a uniform variable
  14397. * @param uniform defines the uniform location
  14398. * @param color4 defines the value to be set
  14399. */
  14400. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14401. if (!uniform)
  14402. return;
  14403. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14404. };
  14405. // States
  14406. /**
  14407. * Set various states to the webGL context
  14408. * @param culling defines backface culling state
  14409. * @param zOffset defines the value to apply to zOffset (0 by default)
  14410. * @param force defines if states must be applied even if cache is up to date
  14411. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14412. */
  14413. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14414. if (zOffset === void 0) { zOffset = 0; }
  14415. if (reverseSide === void 0) { reverseSide = false; }
  14416. // Culling
  14417. if (this._depthCullingState.cull !== culling || force) {
  14418. this._depthCullingState.cull = culling;
  14419. }
  14420. // Cull face
  14421. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14422. if (this._depthCullingState.cullFace !== cullFace || force) {
  14423. this._depthCullingState.cullFace = cullFace;
  14424. }
  14425. // Z offset
  14426. this.setZOffset(zOffset);
  14427. // Front face
  14428. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14429. if (this._depthCullingState.frontFace !== frontFace || force) {
  14430. this._depthCullingState.frontFace = frontFace;
  14431. }
  14432. };
  14433. /**
  14434. * Set the z offset to apply to current rendering
  14435. * @param value defines the offset to apply
  14436. */
  14437. Engine.prototype.setZOffset = function (value) {
  14438. this._depthCullingState.zOffset = value;
  14439. };
  14440. /**
  14441. * Gets the current value of the zOffset
  14442. * @returns the current zOffset state
  14443. */
  14444. Engine.prototype.getZOffset = function () {
  14445. return this._depthCullingState.zOffset;
  14446. };
  14447. /**
  14448. * Enable or disable depth buffering
  14449. * @param enable defines the state to set
  14450. */
  14451. Engine.prototype.setDepthBuffer = function (enable) {
  14452. this._depthCullingState.depthTest = enable;
  14453. };
  14454. /**
  14455. * Gets a boolean indicating if depth writing is enabled
  14456. * @returns the current depth writing state
  14457. */
  14458. Engine.prototype.getDepthWrite = function () {
  14459. return this._depthCullingState.depthMask;
  14460. };
  14461. /**
  14462. * Enable or disable depth writing
  14463. * @param enable defines the state to set
  14464. */
  14465. Engine.prototype.setDepthWrite = function (enable) {
  14466. this._depthCullingState.depthMask = enable;
  14467. };
  14468. /**
  14469. * Enable or disable color writing
  14470. * @param enable defines the state to set
  14471. */
  14472. Engine.prototype.setColorWrite = function (enable) {
  14473. this._gl.colorMask(enable, enable, enable, enable);
  14474. this._colorWrite = enable;
  14475. };
  14476. /**
  14477. * Gets a boolean indicating if color writing is enabled
  14478. * @returns the current color writing state
  14479. */
  14480. Engine.prototype.getColorWrite = function () {
  14481. return this._colorWrite;
  14482. };
  14483. /**
  14484. * Sets alpha constants used by some alpha blending modes
  14485. * @param r defines the red component
  14486. * @param g defines the green component
  14487. * @param b defines the blue component
  14488. * @param a defines the alpha component
  14489. */
  14490. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14491. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14492. };
  14493. /**
  14494. * Sets the current alpha mode
  14495. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14496. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14497. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14498. */
  14499. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14500. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14501. if (this._alphaMode === mode) {
  14502. return;
  14503. }
  14504. switch (mode) {
  14505. case Engine.ALPHA_DISABLE:
  14506. this._alphaState.alphaBlend = false;
  14507. break;
  14508. case Engine.ALPHA_PREMULTIPLIED:
  14509. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14510. this._alphaState.alphaBlend = true;
  14511. break;
  14512. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14513. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14514. this._alphaState.alphaBlend = true;
  14515. break;
  14516. case Engine.ALPHA_COMBINE:
  14517. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14518. this._alphaState.alphaBlend = true;
  14519. break;
  14520. case Engine.ALPHA_ONEONE:
  14521. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14522. this._alphaState.alphaBlend = true;
  14523. break;
  14524. case Engine.ALPHA_ADD:
  14525. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14526. this._alphaState.alphaBlend = true;
  14527. break;
  14528. case Engine.ALPHA_SUBTRACT:
  14529. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14530. this._alphaState.alphaBlend = true;
  14531. break;
  14532. case Engine.ALPHA_MULTIPLY:
  14533. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14534. this._alphaState.alphaBlend = true;
  14535. break;
  14536. case Engine.ALPHA_MAXIMIZED:
  14537. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14538. this._alphaState.alphaBlend = true;
  14539. break;
  14540. case Engine.ALPHA_INTERPOLATE:
  14541. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14542. this._alphaState.alphaBlend = true;
  14543. break;
  14544. case Engine.ALPHA_SCREENMODE:
  14545. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14546. this._alphaState.alphaBlend = true;
  14547. break;
  14548. }
  14549. if (!noDepthWriteChange) {
  14550. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14551. }
  14552. this._alphaMode = mode;
  14553. };
  14554. /**
  14555. * Gets the current alpha mode
  14556. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14557. * @returns the current alpha mode
  14558. */
  14559. Engine.prototype.getAlphaMode = function () {
  14560. return this._alphaMode;
  14561. };
  14562. // Textures
  14563. /**
  14564. * Force the entire cache to be cleared
  14565. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14566. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14567. */
  14568. Engine.prototype.wipeCaches = function (bruteForce) {
  14569. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14570. return;
  14571. }
  14572. this._currentEffect = null;
  14573. if (bruteForce) {
  14574. this.resetTextureCache();
  14575. this._currentProgram = null;
  14576. this._stencilState.reset();
  14577. this._depthCullingState.reset();
  14578. this.setDepthFunctionToLessOrEqual();
  14579. this._alphaState.reset();
  14580. }
  14581. this._resetVertexBufferBinding();
  14582. this._cachedIndexBuffer = null;
  14583. this._cachedEffectForVertexBuffers = null;
  14584. this._unbindVertexArrayObject();
  14585. this.bindIndexBuffer(null);
  14586. };
  14587. /**
  14588. * Set the compressed texture format to use, based on the formats you have, and the formats
  14589. * supported by the hardware / browser.
  14590. *
  14591. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14592. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14593. * to API arguments needed to compressed textures. This puts the burden on the container
  14594. * generator to house the arcane code for determining these for current & future formats.
  14595. *
  14596. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14597. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14598. *
  14599. * Note: The result of this call is not taken into account when a texture is base64.
  14600. *
  14601. * @param formatsAvailable defines the list of those format families you have created
  14602. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14603. *
  14604. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14605. * @returns The extension selected.
  14606. */
  14607. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14608. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14609. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14610. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14611. return this._textureFormatInUse = this._texturesSupported[i];
  14612. }
  14613. }
  14614. }
  14615. // actively set format to nothing, to allow this to be called more than once
  14616. // and possibly fail the 2nd time
  14617. this._textureFormatInUse = null;
  14618. return null;
  14619. };
  14620. /** @hidden */
  14621. Engine.prototype._createTexture = function () {
  14622. var texture = this._gl.createTexture();
  14623. if (!texture) {
  14624. throw new Error("Unable to create texture");
  14625. }
  14626. return texture;
  14627. };
  14628. /**
  14629. * Usually called from BABYLON.Texture.ts.
  14630. * Passed information to create a WebGLTexture
  14631. * @param urlArg defines a value which contains one of the following:
  14632. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14633. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14634. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14635. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14636. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14637. * @param scene needed for loading to the correct scene
  14638. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14639. * @param onLoad optional callback to be called upon successful completion
  14640. * @param onError optional callback to be called upon failure
  14641. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14642. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14643. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14644. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14645. */
  14646. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14647. var _this = this;
  14648. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14649. if (onLoad === void 0) { onLoad = null; }
  14650. if (onError === void 0) { onError = null; }
  14651. if (buffer === void 0) { buffer = null; }
  14652. if (fallback === void 0) { fallback = null; }
  14653. if (format === void 0) { format = null; }
  14654. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14655. var fromData = url.substr(0, 5) === "data:";
  14656. var fromBlob = url.substr(0, 5) === "blob:";
  14657. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14658. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14659. // establish the file extension, if possible
  14660. var lastDot = url.lastIndexOf('.');
  14661. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14662. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14663. var isTGA = (extension.indexOf(".tga") === 0);
  14664. // determine if a ktx file should be substituted
  14665. var isKTX = false;
  14666. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14667. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14668. isKTX = true;
  14669. }
  14670. if (scene) {
  14671. scene._addPendingData(texture);
  14672. }
  14673. texture.url = url;
  14674. texture.generateMipMaps = !noMipmap;
  14675. texture.samplingMode = samplingMode;
  14676. texture.invertY = invertY;
  14677. if (!this._doNotHandleContextLost) {
  14678. // Keep a link to the buffer only if we plan to handle context lost
  14679. texture._buffer = buffer;
  14680. }
  14681. var onLoadObserver = null;
  14682. if (onLoad && !fallback) {
  14683. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14684. }
  14685. if (!fallback)
  14686. this._internalTexturesCache.push(texture);
  14687. var onerror = function (message, exception) {
  14688. if (scene) {
  14689. scene._removePendingData(texture);
  14690. }
  14691. if (onLoadObserver) {
  14692. texture.onLoadedObservable.remove(onLoadObserver);
  14693. }
  14694. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14695. if (isKTX) {
  14696. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14697. }
  14698. else if (BABYLON.Tools.UseFallbackTexture) {
  14699. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14700. }
  14701. if (onError) {
  14702. onError(message || "Unknown error", exception);
  14703. }
  14704. };
  14705. var callback = null;
  14706. // processing for non-image formats
  14707. if (isKTX || isTGA || isDDS) {
  14708. if (isKTX) {
  14709. callback = function (data) {
  14710. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14711. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14712. ktx.uploadLevels(_this._gl, !noMipmap);
  14713. return false;
  14714. }, samplingMode);
  14715. };
  14716. }
  14717. else if (isTGA) {
  14718. callback = function (arrayBuffer) {
  14719. var data = new Uint8Array(arrayBuffer);
  14720. var header = BABYLON.TGATools.GetTGAHeader(data);
  14721. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14722. BABYLON.TGATools.UploadContent(_this._gl, data);
  14723. return false;
  14724. }, samplingMode);
  14725. };
  14726. }
  14727. else if (isDDS) {
  14728. callback = function (data) {
  14729. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14730. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14731. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14732. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14733. return false;
  14734. }, samplingMode);
  14735. };
  14736. }
  14737. if (!buffer) {
  14738. this._loadFile(url, function (data) {
  14739. if (callback) {
  14740. callback(data);
  14741. }
  14742. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14743. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14744. });
  14745. }
  14746. else {
  14747. if (callback) {
  14748. callback(buffer);
  14749. }
  14750. }
  14751. // image format processing
  14752. }
  14753. else {
  14754. var onload = function (img) {
  14755. if (fromBlob && !_this._doNotHandleContextLost) {
  14756. // We need to store the image if we need to rebuild the texture
  14757. // in case of a webgl context lost
  14758. texture._buffer = img;
  14759. }
  14760. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14761. var gl = _this._gl;
  14762. var isPot = (img.width === potWidth && img.height === potHeight);
  14763. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14764. if (isPot) {
  14765. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14766. return false;
  14767. }
  14768. // Using shaders to rescale because canvas.drawImage is lossy
  14769. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14770. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14771. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14772. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14773. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14774. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14775. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14776. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14777. _this._releaseTexture(source);
  14778. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14779. continuationCallback();
  14780. });
  14781. return true;
  14782. }, samplingMode);
  14783. };
  14784. if (!fromData || isBase64) {
  14785. if (buffer instanceof HTMLImageElement) {
  14786. onload(buffer);
  14787. }
  14788. else {
  14789. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14790. }
  14791. }
  14792. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14793. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14794. }
  14795. else {
  14796. onload(buffer);
  14797. }
  14798. }
  14799. return texture;
  14800. };
  14801. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14802. var _this = this;
  14803. var rtt = this.createRenderTargetTexture({
  14804. width: destination.width,
  14805. height: destination.height,
  14806. }, {
  14807. generateMipMaps: false,
  14808. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14809. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14810. generateDepthBuffer: false,
  14811. generateStencilBuffer: false
  14812. });
  14813. if (!this._rescalePostProcess) {
  14814. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14815. }
  14816. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14817. _this._rescalePostProcess.onApply = function (effect) {
  14818. effect._bindTexture("textureSampler", source);
  14819. };
  14820. var hostingScene = scene;
  14821. if (!hostingScene) {
  14822. hostingScene = _this.scenes[_this.scenes.length - 1];
  14823. }
  14824. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14825. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14826. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14827. _this.unBindFramebuffer(rtt);
  14828. _this._releaseTexture(rtt);
  14829. if (onComplete) {
  14830. onComplete();
  14831. }
  14832. });
  14833. };
  14834. /**
  14835. * Update a raw texture
  14836. * @param texture defines the texture to update
  14837. * @param data defines the data to store in the texture
  14838. * @param format defines the format of the data
  14839. * @param invertY defines if data must be stored with Y axis inverted
  14840. * @param compression defines the compression used (null by default)
  14841. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14842. */
  14843. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14844. if (compression === void 0) { compression = null; }
  14845. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14846. if (!texture) {
  14847. return;
  14848. }
  14849. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14850. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14851. // babylon's internalFormat but gl's texImage2D format
  14852. var internalFormat = this._getInternalFormat(format);
  14853. var textureType = this._getWebGLTextureType(type);
  14854. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14855. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14856. if (!this._doNotHandleContextLost) {
  14857. texture._bufferView = data;
  14858. texture.format = format;
  14859. texture.type = type;
  14860. texture.invertY = invertY;
  14861. texture._compression = compression;
  14862. }
  14863. if (texture.width % 4 !== 0) {
  14864. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14865. }
  14866. if (compression && data) {
  14867. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14868. }
  14869. else {
  14870. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14871. }
  14872. if (texture.generateMipMaps) {
  14873. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14874. }
  14875. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14876. // this.resetTextureCache();
  14877. texture.isReady = true;
  14878. };
  14879. /**
  14880. * Creates a raw texture
  14881. * @param data defines the data to store in the texture
  14882. * @param width defines the width of the texture
  14883. * @param height defines the height of the texture
  14884. * @param format defines the format of the data
  14885. * @param generateMipMaps defines if the engine should generate the mip levels
  14886. * @param invertY defines if data must be stored with Y axis inverted
  14887. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14888. * @param compression defines the compression used (null by default)
  14889. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14890. * @returns the raw texture inside an InternalTexture
  14891. */
  14892. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14893. if (compression === void 0) { compression = null; }
  14894. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14895. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14896. texture.baseWidth = width;
  14897. texture.baseHeight = height;
  14898. texture.width = width;
  14899. texture.height = height;
  14900. texture.format = format;
  14901. texture.generateMipMaps = generateMipMaps;
  14902. texture.samplingMode = samplingMode;
  14903. texture.invertY = invertY;
  14904. texture._compression = compression;
  14905. texture.type = type;
  14906. if (!this._doNotHandleContextLost) {
  14907. texture._bufferView = data;
  14908. }
  14909. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14910. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14911. // Filters
  14912. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14913. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14914. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14915. if (generateMipMaps) {
  14916. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14917. }
  14918. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14919. this._internalTexturesCache.push(texture);
  14920. return texture;
  14921. };
  14922. /**
  14923. * Creates a dynamic texture
  14924. * @param width defines the width of the texture
  14925. * @param height defines the height of the texture
  14926. * @param generateMipMaps defines if the engine should generate the mip levels
  14927. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14928. * @returns the dynamic texture inside an InternalTexture
  14929. */
  14930. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14931. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14932. texture.baseWidth = width;
  14933. texture.baseHeight = height;
  14934. if (generateMipMaps) {
  14935. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14936. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14937. }
  14938. // this.resetTextureCache();
  14939. texture.width = width;
  14940. texture.height = height;
  14941. texture.isReady = false;
  14942. texture.generateMipMaps = generateMipMaps;
  14943. texture.samplingMode = samplingMode;
  14944. this.updateTextureSamplingMode(samplingMode, texture);
  14945. this._internalTexturesCache.push(texture);
  14946. return texture;
  14947. };
  14948. /**
  14949. * Update the sampling mode of a given texture
  14950. * @param samplingMode defines the required sampling mode
  14951. * @param texture defines the texture to update
  14952. */
  14953. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14954. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14955. if (texture.isCube) {
  14956. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14957. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14958. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14959. }
  14960. else if (texture.is3D) {
  14961. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14962. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14963. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14964. }
  14965. else {
  14966. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14967. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14968. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14969. }
  14970. texture.samplingMode = samplingMode;
  14971. };
  14972. /**
  14973. * Update the content of a dynamic texture
  14974. * @param texture defines the texture to update
  14975. * @param canvas defines the canvas containing the source
  14976. * @param invertY defines if data must be stored with Y axis inverted
  14977. * @param premulAlpha defines if alpha is stored as premultiplied
  14978. * @param format defines the format of the data
  14979. */
  14980. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14981. if (premulAlpha === void 0) { premulAlpha = false; }
  14982. if (!texture) {
  14983. return;
  14984. }
  14985. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14986. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14987. if (premulAlpha) {
  14988. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14989. }
  14990. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14991. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14992. if (texture.generateMipMaps) {
  14993. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14994. }
  14995. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14996. if (premulAlpha) {
  14997. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14998. }
  14999. texture.isReady = true;
  15000. };
  15001. /**
  15002. * Update a video texture
  15003. * @param texture defines the texture to update
  15004. * @param video defines the video element to use
  15005. * @param invertY defines if data must be stored with Y axis inverted
  15006. */
  15007. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15008. if (!texture || texture._isDisabled) {
  15009. return;
  15010. }
  15011. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15012. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  15013. try {
  15014. // Testing video texture support
  15015. if (this._videoTextureSupported === undefined) {
  15016. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15017. if (this._gl.getError() !== 0) {
  15018. this._videoTextureSupported = false;
  15019. }
  15020. else {
  15021. this._videoTextureSupported = true;
  15022. }
  15023. }
  15024. // Copy video through the current working canvas if video texture is not supported
  15025. if (!this._videoTextureSupported) {
  15026. if (!texture._workingCanvas) {
  15027. texture._workingCanvas = document.createElement("canvas");
  15028. var context = texture._workingCanvas.getContext("2d");
  15029. if (!context) {
  15030. throw new Error("Unable to get 2d context");
  15031. }
  15032. texture._workingContext = context;
  15033. texture._workingCanvas.width = texture.width;
  15034. texture._workingCanvas.height = texture.height;
  15035. }
  15036. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15037. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15038. }
  15039. else {
  15040. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15041. }
  15042. if (texture.generateMipMaps) {
  15043. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15044. }
  15045. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15046. // this.resetTextureCache();
  15047. texture.isReady = true;
  15048. }
  15049. catch (ex) {
  15050. // Something unexpected
  15051. // Let's disable the texture
  15052. texture._isDisabled = true;
  15053. }
  15054. };
  15055. /**
  15056. * Updates a depth texture Comparison Mode and Function.
  15057. * If the comparison Function is equal to 0, the mode will be set to none.
  15058. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15059. * @param texture The texture to set the comparison function for
  15060. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15061. */
  15062. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15063. if (this.webGLVersion === 1) {
  15064. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15065. return;
  15066. }
  15067. var gl = this._gl;
  15068. if (texture.isCube) {
  15069. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15070. if (comparisonFunction === 0) {
  15071. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15072. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15073. }
  15074. else {
  15075. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15076. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15077. }
  15078. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15079. }
  15080. else {
  15081. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15082. if (comparisonFunction === 0) {
  15083. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15084. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15085. }
  15086. else {
  15087. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15088. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15089. }
  15090. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15091. }
  15092. texture._comparisonFunction = comparisonFunction;
  15093. };
  15094. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15095. var width = size.width || size;
  15096. var height = size.height || size;
  15097. internalTexture.baseWidth = width;
  15098. internalTexture.baseHeight = height;
  15099. internalTexture.width = width;
  15100. internalTexture.height = height;
  15101. internalTexture.isReady = true;
  15102. internalTexture.samples = 1;
  15103. internalTexture.generateMipMaps = false;
  15104. internalTexture._generateDepthBuffer = true;
  15105. internalTexture._generateStencilBuffer = generateStencil;
  15106. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15107. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15108. internalTexture._comparisonFunction = comparisonFunction;
  15109. var gl = this._gl;
  15110. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15111. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15112. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15113. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15114. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15115. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15116. if (comparisonFunction === 0) {
  15117. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15118. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15119. }
  15120. else {
  15121. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15122. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15123. }
  15124. };
  15125. /**
  15126. * Creates a depth stencil texture.
  15127. * This is only available in WebGL 2 or with the depth texture extension available.
  15128. * @param size The size of face edge in the texture.
  15129. * @param options The options defining the texture.
  15130. * @returns The texture
  15131. */
  15132. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15133. if (options.isCube) {
  15134. var width = size.width || size;
  15135. return this._createDepthStencilCubeTexture(width, options);
  15136. }
  15137. else {
  15138. return this._createDepthStencilTexture(size, options);
  15139. }
  15140. };
  15141. /**
  15142. * Creates a depth stencil texture.
  15143. * This is only available in WebGL 2 or with the depth texture extension available.
  15144. * @param size The size of face edge in the texture.
  15145. * @param options The options defining the texture.
  15146. * @returns The texture
  15147. */
  15148. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15149. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15150. if (!this._caps.depthTextureExtension) {
  15151. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15152. return internalTexture;
  15153. }
  15154. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15155. var gl = this._gl;
  15156. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15157. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15158. if (this.webGLVersion > 1) {
  15159. if (internalOptions.generateStencil) {
  15160. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15161. }
  15162. else {
  15163. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15164. }
  15165. }
  15166. else {
  15167. if (internalOptions.generateStencil) {
  15168. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15169. }
  15170. else {
  15171. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15172. }
  15173. }
  15174. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15175. return internalTexture;
  15176. };
  15177. /**
  15178. * Creates a depth stencil cube texture.
  15179. * This is only available in WebGL 2.
  15180. * @param size The size of face edge in the cube texture.
  15181. * @param options The options defining the cube texture.
  15182. * @returns The cube texture
  15183. */
  15184. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15185. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15186. internalTexture.isCube = true;
  15187. if (this.webGLVersion === 1) {
  15188. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15189. return internalTexture;
  15190. }
  15191. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15192. var gl = this._gl;
  15193. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15194. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15195. // Create the depth/stencil buffer
  15196. for (var face = 0; face < 6; face++) {
  15197. if (internalOptions.generateStencil) {
  15198. 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);
  15199. }
  15200. else {
  15201. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15202. }
  15203. }
  15204. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15205. return internalTexture;
  15206. };
  15207. /**
  15208. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15209. * @param renderTarget The render target to set the frame buffer for
  15210. */
  15211. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15212. // Create the framebuffer
  15213. var internalTexture = renderTarget.getInternalTexture();
  15214. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15215. return;
  15216. }
  15217. var gl = this._gl;
  15218. var depthStencilTexture = renderTarget.depthStencilTexture;
  15219. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15220. if (depthStencilTexture.isCube) {
  15221. if (depthStencilTexture._generateStencilBuffer) {
  15222. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15223. }
  15224. else {
  15225. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15226. }
  15227. }
  15228. else {
  15229. if (depthStencilTexture._generateStencilBuffer) {
  15230. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15231. }
  15232. else {
  15233. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15234. }
  15235. }
  15236. this.bindUnboundFramebuffer(null);
  15237. };
  15238. /**
  15239. * Creates a new render target texture
  15240. * @param size defines the size of the texture
  15241. * @param options defines the options used to create the texture
  15242. * @returns a new render target texture stored in an InternalTexture
  15243. */
  15244. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15245. var fullOptions = new RenderTargetCreationOptions();
  15246. if (options !== undefined && typeof options === "object") {
  15247. fullOptions.generateMipMaps = options.generateMipMaps;
  15248. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15249. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15250. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15251. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15252. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15253. }
  15254. else {
  15255. fullOptions.generateMipMaps = options;
  15256. fullOptions.generateDepthBuffer = true;
  15257. fullOptions.generateStencilBuffer = false;
  15258. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15259. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15260. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15261. }
  15262. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15263. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15264. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15265. }
  15266. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15267. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15268. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15269. }
  15270. var gl = this._gl;
  15271. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15272. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15273. var width = size.width || size;
  15274. var height = size.height || size;
  15275. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15276. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15277. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15278. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15279. }
  15280. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15281. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15282. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15283. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15284. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15285. // Create the framebuffer
  15286. var currentFrameBuffer = this._currentFramebuffer;
  15287. var framebuffer = gl.createFramebuffer();
  15288. this.bindUnboundFramebuffer(framebuffer);
  15289. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15290. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15291. if (fullOptions.generateMipMaps) {
  15292. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15293. }
  15294. // Unbind
  15295. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15296. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15297. this.bindUnboundFramebuffer(currentFrameBuffer);
  15298. texture._framebuffer = framebuffer;
  15299. texture.baseWidth = width;
  15300. texture.baseHeight = height;
  15301. texture.width = width;
  15302. texture.height = height;
  15303. texture.isReady = true;
  15304. texture.samples = 1;
  15305. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15306. texture.samplingMode = fullOptions.samplingMode;
  15307. texture.type = fullOptions.type;
  15308. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15309. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15310. // this.resetTextureCache();
  15311. this._internalTexturesCache.push(texture);
  15312. return texture;
  15313. };
  15314. /**
  15315. * Create a multi render target texture
  15316. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15317. * @param size defines the size of the texture
  15318. * @param options defines the creation options
  15319. * @returns the cube texture as an InternalTexture
  15320. */
  15321. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15322. var generateMipMaps = false;
  15323. var generateDepthBuffer = true;
  15324. var generateStencilBuffer = false;
  15325. var generateDepthTexture = false;
  15326. var textureCount = 1;
  15327. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15328. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15329. var types = new Array();
  15330. var samplingModes = new Array();
  15331. if (options !== undefined) {
  15332. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15333. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15334. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15335. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15336. textureCount = options.textureCount || 1;
  15337. if (options.types) {
  15338. types = options.types;
  15339. }
  15340. if (options.samplingModes) {
  15341. samplingModes = options.samplingModes;
  15342. }
  15343. }
  15344. var gl = this._gl;
  15345. // Create the framebuffer
  15346. var framebuffer = gl.createFramebuffer();
  15347. this.bindUnboundFramebuffer(framebuffer);
  15348. var width = size.width || size;
  15349. var height = size.height || size;
  15350. var textures = [];
  15351. var attachments = [];
  15352. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15353. for (var i = 0; i < textureCount; i++) {
  15354. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15355. var type = types[i] || defaultType;
  15356. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15357. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15358. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15359. }
  15360. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15361. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15362. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15363. }
  15364. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15365. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15366. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15367. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15368. }
  15369. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15370. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15371. textures.push(texture);
  15372. attachments.push(attachment);
  15373. gl.activeTexture(gl["TEXTURE" + i]);
  15374. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15375. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15376. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15377. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15378. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15379. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15380. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15381. if (generateMipMaps) {
  15382. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15383. }
  15384. // Unbind
  15385. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15386. texture._framebuffer = framebuffer;
  15387. texture._depthStencilBuffer = depthStencilBuffer;
  15388. texture.baseWidth = width;
  15389. texture.baseHeight = height;
  15390. texture.width = width;
  15391. texture.height = height;
  15392. texture.isReady = true;
  15393. texture.samples = 1;
  15394. texture.generateMipMaps = generateMipMaps;
  15395. texture.samplingMode = samplingMode;
  15396. texture.type = type;
  15397. texture._generateDepthBuffer = generateDepthBuffer;
  15398. texture._generateStencilBuffer = generateStencilBuffer;
  15399. texture._attachments = attachments;
  15400. this._internalTexturesCache.push(texture);
  15401. }
  15402. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15403. // Depth texture
  15404. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15405. gl.activeTexture(gl.TEXTURE0);
  15406. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15407. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15408. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15409. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15410. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15411. 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);
  15412. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15413. depthTexture._framebuffer = framebuffer;
  15414. depthTexture.baseWidth = width;
  15415. depthTexture.baseHeight = height;
  15416. depthTexture.width = width;
  15417. depthTexture.height = height;
  15418. depthTexture.isReady = true;
  15419. depthTexture.samples = 1;
  15420. depthTexture.generateMipMaps = generateMipMaps;
  15421. depthTexture.samplingMode = gl.NEAREST;
  15422. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15423. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15424. textures.push(depthTexture);
  15425. this._internalTexturesCache.push(depthTexture);
  15426. }
  15427. gl.drawBuffers(attachments);
  15428. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15429. this.bindUnboundFramebuffer(null);
  15430. this.resetTextureCache();
  15431. return textures;
  15432. };
  15433. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15434. if (samples === void 0) { samples = 1; }
  15435. var depthStencilBuffer = null;
  15436. var gl = this._gl;
  15437. // Create the depth/stencil buffer
  15438. if (generateStencilBuffer) {
  15439. depthStencilBuffer = gl.createRenderbuffer();
  15440. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15441. if (samples > 1) {
  15442. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15443. }
  15444. else {
  15445. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15446. }
  15447. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15448. }
  15449. else if (generateDepthBuffer) {
  15450. depthStencilBuffer = gl.createRenderbuffer();
  15451. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15452. if (samples > 1) {
  15453. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15454. }
  15455. else {
  15456. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15457. }
  15458. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15459. }
  15460. return depthStencilBuffer;
  15461. };
  15462. /**
  15463. * Updates the sample count of a render target texture
  15464. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15465. * @param texture defines the texture to update
  15466. * @param samples defines the sample count to set
  15467. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15468. */
  15469. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15470. if (this.webGLVersion < 2 || !texture) {
  15471. return 1;
  15472. }
  15473. if (texture.samples === samples) {
  15474. return samples;
  15475. }
  15476. var gl = this._gl;
  15477. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15478. // Dispose previous render buffers
  15479. if (texture._depthStencilBuffer) {
  15480. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15481. texture._depthStencilBuffer = null;
  15482. }
  15483. if (texture._MSAAFramebuffer) {
  15484. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15485. texture._MSAAFramebuffer = null;
  15486. }
  15487. if (texture._MSAARenderBuffer) {
  15488. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15489. texture._MSAARenderBuffer = null;
  15490. }
  15491. if (samples > 1) {
  15492. var framebuffer = gl.createFramebuffer();
  15493. if (!framebuffer) {
  15494. throw new Error("Unable to create multi sampled framebuffer");
  15495. }
  15496. texture._MSAAFramebuffer = framebuffer;
  15497. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15498. var colorRenderbuffer = gl.createRenderbuffer();
  15499. if (!colorRenderbuffer) {
  15500. throw new Error("Unable to create multi sampled framebuffer");
  15501. }
  15502. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15503. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15504. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15505. texture._MSAARenderBuffer = colorRenderbuffer;
  15506. }
  15507. else {
  15508. this.bindUnboundFramebuffer(texture._framebuffer);
  15509. }
  15510. texture.samples = samples;
  15511. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15512. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15513. this.bindUnboundFramebuffer(null);
  15514. return samples;
  15515. };
  15516. /**
  15517. * Update the sample count for a given multiple render target texture
  15518. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15519. * @param textures defines the textures to update
  15520. * @param samples defines the sample count to set
  15521. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15522. */
  15523. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15524. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15525. return 1;
  15526. }
  15527. if (textures[0].samples === samples) {
  15528. return samples;
  15529. }
  15530. var gl = this._gl;
  15531. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15532. // Dispose previous render buffers
  15533. if (textures[0]._depthStencilBuffer) {
  15534. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15535. textures[0]._depthStencilBuffer = null;
  15536. }
  15537. if (textures[0]._MSAAFramebuffer) {
  15538. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15539. textures[0]._MSAAFramebuffer = null;
  15540. }
  15541. for (var i = 0; i < textures.length; i++) {
  15542. if (textures[i]._MSAARenderBuffer) {
  15543. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15544. textures[i]._MSAARenderBuffer = null;
  15545. }
  15546. }
  15547. if (samples > 1) {
  15548. var framebuffer = gl.createFramebuffer();
  15549. if (!framebuffer) {
  15550. throw new Error("Unable to create multi sampled framebuffer");
  15551. }
  15552. this.bindUnboundFramebuffer(framebuffer);
  15553. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15554. var attachments = [];
  15555. for (var i = 0; i < textures.length; i++) {
  15556. var texture = textures[i];
  15557. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15558. var colorRenderbuffer = gl.createRenderbuffer();
  15559. if (!colorRenderbuffer) {
  15560. throw new Error("Unable to create multi sampled framebuffer");
  15561. }
  15562. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15563. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15564. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15565. texture._MSAAFramebuffer = framebuffer;
  15566. texture._MSAARenderBuffer = colorRenderbuffer;
  15567. texture.samples = samples;
  15568. texture._depthStencilBuffer = depthStencilBuffer;
  15569. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15570. attachments.push(attachment);
  15571. }
  15572. gl.drawBuffers(attachments);
  15573. }
  15574. else {
  15575. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15576. }
  15577. this.bindUnboundFramebuffer(null);
  15578. return samples;
  15579. };
  15580. /** @hidden */
  15581. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15582. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15583. };
  15584. /** @hidden */
  15585. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15586. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15587. };
  15588. /** @hidden */
  15589. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15590. var gl = this._gl;
  15591. var textureType = this._getWebGLTextureType(texture.type);
  15592. var format = this._getInternalFormat(texture.format);
  15593. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15594. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15595. this._bindTextureDirectly(bindTarget, texture, true);
  15596. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, texture.invertY ? 1 : 0);
  15597. var target = gl.TEXTURE_2D;
  15598. if (texture.isCube) {
  15599. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15600. }
  15601. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15602. this._bindTextureDirectly(bindTarget, null, true);
  15603. };
  15604. /**
  15605. * Creates a new render target cube texture
  15606. * @param size defines the size of the texture
  15607. * @param options defines the options used to create the texture
  15608. * @returns a new render target cube texture stored in an InternalTexture
  15609. */
  15610. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15611. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15612. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15613. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15614. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15615. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15616. }
  15617. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15618. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15619. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15620. }
  15621. var gl = this._gl;
  15622. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15623. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15624. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15625. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15626. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15627. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15628. }
  15629. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15630. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15631. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15632. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15633. for (var face = 0; face < 6; face++) {
  15634. 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);
  15635. }
  15636. // Create the framebuffer
  15637. var framebuffer = gl.createFramebuffer();
  15638. this.bindUnboundFramebuffer(framebuffer);
  15639. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15640. // MipMaps
  15641. if (fullOptions.generateMipMaps) {
  15642. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15643. }
  15644. // Unbind
  15645. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15646. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15647. this.bindUnboundFramebuffer(null);
  15648. texture._framebuffer = framebuffer;
  15649. texture.width = size;
  15650. texture.height = size;
  15651. texture.isReady = true;
  15652. texture.isCube = true;
  15653. texture.samples = 1;
  15654. texture.generateMipMaps = fullOptions.generateMipMaps;
  15655. texture.samplingMode = fullOptions.samplingMode;
  15656. texture.type = fullOptions.type;
  15657. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15658. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15659. this._internalTexturesCache.push(texture);
  15660. return texture;
  15661. };
  15662. /**
  15663. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15664. * @param rootUrl defines the url where the file to load is located
  15665. * @param scene defines the current scene
  15666. * @param lodScale defines scale to apply to the mip map selection
  15667. * @param lodOffset defines offset to apply to the mip map selection
  15668. * @param onLoad defines an optional callback raised when the texture is loaded
  15669. * @param onError defines an optional callback raised if there is an issue to load the texture
  15670. * @param format defines the format of the data
  15671. * @param forcedExtension defines the extension to use to pick the right loader
  15672. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15673. * @returns the cube texture as an InternalTexture
  15674. */
  15675. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15676. var _this = this;
  15677. if (onLoad === void 0) { onLoad = null; }
  15678. if (onError === void 0) { onError = null; }
  15679. if (forcedExtension === void 0) { forcedExtension = null; }
  15680. if (createPolynomials === void 0) { createPolynomials = true; }
  15681. var callback = function (loadData) {
  15682. if (!loadData) {
  15683. if (onLoad) {
  15684. onLoad(null);
  15685. }
  15686. return;
  15687. }
  15688. var texture = loadData.texture;
  15689. if (!createPolynomials) {
  15690. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15691. }
  15692. else if (loadData.info.sphericalPolynomial) {
  15693. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15694. }
  15695. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15696. if (_this._caps.textureLOD) {
  15697. // Do not add extra process if texture lod is supported.
  15698. if (onLoad) {
  15699. onLoad(texture);
  15700. }
  15701. return;
  15702. }
  15703. var mipSlices = 3;
  15704. var gl = _this._gl;
  15705. var width = loadData.width;
  15706. if (!width) {
  15707. return;
  15708. }
  15709. var textures = [];
  15710. for (var i = 0; i < mipSlices; i++) {
  15711. //compute LOD from even spacing in smoothness (matching shader calculation)
  15712. var smoothness = i / (mipSlices - 1);
  15713. var roughness = 1 - smoothness;
  15714. var minLODIndex = lodOffset; // roughness = 0
  15715. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15716. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15717. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15718. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15719. glTextureFromLod.isCube = true;
  15720. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15721. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15722. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15723. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15724. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15725. if (loadData.isDDS) {
  15726. var info = loadData.info;
  15727. var data = loadData.data;
  15728. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15729. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15730. }
  15731. else {
  15732. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15733. }
  15734. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15735. // Wrap in a base texture for easy binding.
  15736. var lodTexture = new BABYLON.BaseTexture(scene);
  15737. lodTexture.isCube = true;
  15738. lodTexture._texture = glTextureFromLod;
  15739. glTextureFromLod.isReady = true;
  15740. textures.push(lodTexture);
  15741. }
  15742. texture._lodTextureHigh = textures[2];
  15743. texture._lodTextureMid = textures[1];
  15744. texture._lodTextureLow = textures[0];
  15745. if (onLoad) {
  15746. onLoad(texture);
  15747. }
  15748. };
  15749. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15750. };
  15751. /**
  15752. * Creates a cube texture
  15753. * @param rootUrl defines the url where the files to load is located
  15754. * @param scene defines the current scene
  15755. * @param files defines the list of files to load (1 per face)
  15756. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15757. * @param onLoad defines an optional callback raised when the texture is loaded
  15758. * @param onError defines an optional callback raised if there is an issue to load the texture
  15759. * @param format defines the format of the data
  15760. * @param forcedExtension defines the extension to use to pick the right loader
  15761. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15762. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15763. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15764. * @returns the cube texture as an InternalTexture
  15765. */
  15766. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset) {
  15767. var _this = this;
  15768. if (onLoad === void 0) { onLoad = null; }
  15769. if (onError === void 0) { onError = null; }
  15770. if (forcedExtension === void 0) { forcedExtension = null; }
  15771. if (createPolynomials === void 0) { createPolynomials = false; }
  15772. if (lodScale === void 0) { lodScale = 0; }
  15773. if (lodOffset === void 0) { lodOffset = 0; }
  15774. var gl = this._gl;
  15775. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15776. texture.isCube = true;
  15777. texture.url = rootUrl;
  15778. texture.generateMipMaps = !noMipmap;
  15779. texture._lodGenerationScale = lodScale;
  15780. texture._lodGenerationOffset = lodOffset;
  15781. if (!this._doNotHandleContextLost) {
  15782. texture._extension = forcedExtension;
  15783. texture._files = files;
  15784. }
  15785. var isKTX = false;
  15786. var isDDS = false;
  15787. var isEnv = false;
  15788. var lastDot = rootUrl.lastIndexOf('.');
  15789. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15790. if (this._textureFormatInUse) {
  15791. extension = this._textureFormatInUse;
  15792. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15793. isKTX = true;
  15794. }
  15795. else {
  15796. isDDS = (extension === ".dds");
  15797. isEnv = (extension === ".env");
  15798. }
  15799. var onerror = function (request, exception) {
  15800. if (onError && request) {
  15801. onError(request.status + " " + request.statusText, exception);
  15802. }
  15803. };
  15804. if (isKTX) {
  15805. this._loadFile(rootUrl, function (data) {
  15806. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15807. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15808. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15809. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15810. ktx.uploadLevels(_this._gl, !noMipmap);
  15811. _this.setCubeMapTextureParams(gl, loadMipmap);
  15812. texture.width = ktx.pixelWidth;
  15813. texture.height = ktx.pixelHeight;
  15814. texture.isReady = true;
  15815. }, undefined, undefined, true, onerror);
  15816. }
  15817. else if (isEnv) {
  15818. this._loadFile(rootUrl, function (data) {
  15819. data = data;
  15820. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15821. if (info) {
  15822. texture.width = info.width;
  15823. texture.height = info.width;
  15824. BABYLON.EnvironmentTextureTools.UploadPolynomials(texture, data, info);
  15825. BABYLON.EnvironmentTextureTools.UploadLevelsAsync(texture, data, info).then(function () {
  15826. texture.isReady = true;
  15827. if (onLoad) {
  15828. onLoad();
  15829. }
  15830. });
  15831. }
  15832. else if (onError) {
  15833. onError("Can not parse the environment file", null);
  15834. }
  15835. }, undefined, undefined, true, onerror);
  15836. }
  15837. else if (isDDS) {
  15838. if (files && files.length === 6) {
  15839. this._cascadeLoadFiles(scene, function (imgs) {
  15840. var info;
  15841. var loadMipmap = false;
  15842. var width = 0;
  15843. for (var index = 0; index < imgs.length; index++) {
  15844. var data = imgs[index];
  15845. info = BABYLON.DDSTools.GetDDSInfo(data);
  15846. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15847. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15848. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15849. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15850. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15851. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15852. }
  15853. texture.width = info.width;
  15854. texture.height = info.height;
  15855. texture.type = info.textureType;
  15856. width = info.width;
  15857. }
  15858. _this.setCubeMapTextureParams(gl, loadMipmap);
  15859. texture.isReady = true;
  15860. if (onLoad) {
  15861. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15862. }
  15863. }, files, onError);
  15864. }
  15865. else {
  15866. this._loadFile(rootUrl, function (data) {
  15867. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15868. if (createPolynomials) {
  15869. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15870. }
  15871. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15872. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15873. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15874. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15875. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15876. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15877. }
  15878. _this.setCubeMapTextureParams(gl, loadMipmap);
  15879. texture.width = info.width;
  15880. texture.height = info.height;
  15881. texture.isReady = true;
  15882. texture.type = info.textureType;
  15883. if (onLoad) {
  15884. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15885. }
  15886. }, undefined, undefined, true, onerror);
  15887. }
  15888. }
  15889. else {
  15890. if (!files) {
  15891. throw new Error("Cannot load cubemap because files were not defined");
  15892. }
  15893. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15894. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15895. var height = width;
  15896. _this._prepareWorkingCanvas();
  15897. if (!_this._workingCanvas || !_this._workingContext) {
  15898. return;
  15899. }
  15900. _this._workingCanvas.width = width;
  15901. _this._workingCanvas.height = height;
  15902. var faces = [
  15903. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15904. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15905. ];
  15906. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15907. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15908. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15909. for (var index = 0; index < faces.length; index++) {
  15910. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15911. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15912. }
  15913. if (!noMipmap) {
  15914. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15915. }
  15916. _this.setCubeMapTextureParams(gl, !noMipmap);
  15917. texture.width = width;
  15918. texture.height = height;
  15919. texture.isReady = true;
  15920. if (format) {
  15921. texture.format = format;
  15922. }
  15923. texture.onLoadedObservable.notifyObservers(texture);
  15924. texture.onLoadedObservable.clear();
  15925. if (onLoad) {
  15926. onLoad();
  15927. }
  15928. }, files, onError);
  15929. }
  15930. this._internalTexturesCache.push(texture);
  15931. return texture;
  15932. };
  15933. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15934. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15935. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15936. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15937. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15938. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15939. // this.resetTextureCache();
  15940. };
  15941. /**
  15942. * Update a raw cube texture
  15943. * @param texture defines the texture to udpdate
  15944. * @param data defines the data to store
  15945. * @param format defines the data format
  15946. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15947. * @param invertY defines if data must be stored with Y axis inverted
  15948. * @param compression defines the compression used (null by default)
  15949. * @param level defines which level of the texture to update
  15950. */
  15951. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15952. if (compression === void 0) { compression = null; }
  15953. if (level === void 0) { level = 0; }
  15954. texture._bufferViewArray = data;
  15955. texture.format = format;
  15956. texture.type = type;
  15957. texture.invertY = invertY;
  15958. texture._compression = compression;
  15959. var gl = this._gl;
  15960. var textureType = this._getWebGLTextureType(type);
  15961. var internalFormat = this._getInternalFormat(format);
  15962. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15963. var needConversion = false;
  15964. if (internalFormat === gl.RGB) {
  15965. internalFormat = gl.RGBA;
  15966. needConversion = true;
  15967. }
  15968. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15969. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15970. if (texture.width % 4 !== 0) {
  15971. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15972. }
  15973. // Data are known to be in +X +Y +Z -X -Y -Z
  15974. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15975. var faceData = data[faceIndex];
  15976. if (compression) {
  15977. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15978. }
  15979. else {
  15980. if (needConversion) {
  15981. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15982. }
  15983. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15984. }
  15985. }
  15986. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15987. if (isPot && texture.generateMipMaps && level === 0) {
  15988. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15989. }
  15990. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15991. // this.resetTextureCache();
  15992. texture.isReady = true;
  15993. };
  15994. /**
  15995. * Creates a new raw cube texture
  15996. * @param data defines the array of data to use to create each face
  15997. * @param size defines the size of the textures
  15998. * @param format defines the format of the data
  15999. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16000. * @param generateMipMaps defines if the engine should generate the mip levels
  16001. * @param invertY defines if data must be stored with Y axis inverted
  16002. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16003. * @param compression defines the compression used (null by default)
  16004. * @returns the cube texture as an InternalTexture
  16005. */
  16006. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16007. if (compression === void 0) { compression = null; }
  16008. var gl = this._gl;
  16009. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16010. texture.isCube = true;
  16011. texture.generateMipMaps = generateMipMaps;
  16012. texture.format = format;
  16013. texture.type = type;
  16014. if (!this._doNotHandleContextLost) {
  16015. texture._bufferViewArray = data;
  16016. }
  16017. var textureType = this._getWebGLTextureType(type);
  16018. var internalFormat = this._getInternalFormat(format);
  16019. if (internalFormat === gl.RGB) {
  16020. internalFormat = gl.RGBA;
  16021. }
  16022. var width = size;
  16023. var height = width;
  16024. texture.width = width;
  16025. texture.height = height;
  16026. // Double check on POT to generate Mips.
  16027. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16028. if (!isPot) {
  16029. generateMipMaps = false;
  16030. }
  16031. // Upload data if needed. The texture won't be ready until then.
  16032. if (data) {
  16033. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16034. }
  16035. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16036. // Filters
  16037. if (data && generateMipMaps) {
  16038. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16039. }
  16040. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16041. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16042. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16043. }
  16044. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16045. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16046. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16047. }
  16048. else {
  16049. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  16050. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16051. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16052. }
  16053. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16054. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16055. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16056. return texture;
  16057. };
  16058. /**
  16059. * Creates a new raw cube texture from a specified url
  16060. * @param url defines the url where the data is located
  16061. * @param scene defines the current scene
  16062. * @param size defines the size of the textures
  16063. * @param format defines the format of the data
  16064. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16065. * @param noMipmap defines if the engine should avoid generating the mip levels
  16066. * @param callback defines a callback used to extract texture data from loaded data
  16067. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16068. * @param onLoad defines a callback called when texture is loaded
  16069. * @param onError defines a callback called if there is an error
  16070. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16071. * @param invertY defines if data must be stored with Y axis inverted
  16072. * @returns the cube texture as an InternalTexture
  16073. */
  16074. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16075. var _this = this;
  16076. if (onLoad === void 0) { onLoad = null; }
  16077. if (onError === void 0) { onError = null; }
  16078. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16079. if (invertY === void 0) { invertY = false; }
  16080. var gl = this._gl;
  16081. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16082. scene._addPendingData(texture);
  16083. texture.url = url;
  16084. this._internalTexturesCache.push(texture);
  16085. var onerror = function (request, exception) {
  16086. scene._removePendingData(texture);
  16087. if (onError && request) {
  16088. onError(request.status + " " + request.statusText, exception);
  16089. }
  16090. };
  16091. var internalCallback = function (data) {
  16092. var width = texture.width;
  16093. var faceDataArrays = callback(data);
  16094. if (!faceDataArrays) {
  16095. return;
  16096. }
  16097. if (mipmapGenerator) {
  16098. var textureType = _this._getWebGLTextureType(type);
  16099. var internalFormat = _this._getInternalFormat(format);
  16100. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16101. var needConversion = false;
  16102. if (internalFormat === gl.RGB) {
  16103. internalFormat = gl.RGBA;
  16104. needConversion = true;
  16105. }
  16106. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16107. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  16108. var mipData = mipmapGenerator(faceDataArrays);
  16109. for (var level = 0; level < mipData.length; level++) {
  16110. var mipSize = width >> level;
  16111. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16112. var mipFaceData = mipData[level][faceIndex];
  16113. if (needConversion) {
  16114. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16115. }
  16116. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16117. }
  16118. }
  16119. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16120. }
  16121. else {
  16122. texture.generateMipMaps = !noMipmap;
  16123. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16124. }
  16125. texture.isReady = true;
  16126. // this.resetTextureCache();
  16127. scene._removePendingData(texture);
  16128. if (onLoad) {
  16129. onLoad();
  16130. }
  16131. };
  16132. this._loadFile(url, function (data) {
  16133. internalCallback(data);
  16134. }, undefined, scene.database, true, onerror);
  16135. return texture;
  16136. };
  16137. ;
  16138. /**
  16139. * Update a raw 3D texture
  16140. * @param texture defines the texture to update
  16141. * @param data defines the data to store
  16142. * @param format defines the data format
  16143. * @param invertY defines if data must be stored with Y axis inverted
  16144. * @param compression defines the used compression (can be null)
  16145. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16146. */
  16147. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16148. if (compression === void 0) { compression = null; }
  16149. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16150. var internalType = this._getWebGLTextureType(textureType);
  16151. var internalFormat = this._getInternalFormat(format);
  16152. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16153. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16154. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16155. if (!this._doNotHandleContextLost) {
  16156. texture._bufferView = data;
  16157. texture.format = format;
  16158. texture.invertY = invertY;
  16159. texture._compression = compression;
  16160. }
  16161. if (texture.width % 4 !== 0) {
  16162. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16163. }
  16164. if (compression && data) {
  16165. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16166. }
  16167. else {
  16168. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16169. }
  16170. if (texture.generateMipMaps) {
  16171. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16172. }
  16173. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16174. // this.resetTextureCache();
  16175. texture.isReady = true;
  16176. };
  16177. /**
  16178. * Creates a new raw 3D texture
  16179. * @param data defines the data used to create the texture
  16180. * @param width defines the width of the texture
  16181. * @param height defines the height of the texture
  16182. * @param depth defines the depth of the texture
  16183. * @param format defines the format of the texture
  16184. * @param generateMipMaps defines if the engine must generate mip levels
  16185. * @param invertY defines if data must be stored with Y axis inverted
  16186. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16187. * @param compression defines the compressed used (can be null)
  16188. * @param textureType defines the compressed used (can be null)
  16189. * @returns a new raw 3D texture (stored in an InternalTexture)
  16190. */
  16191. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16192. if (compression === void 0) { compression = null; }
  16193. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16194. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16195. texture.baseWidth = width;
  16196. texture.baseHeight = height;
  16197. texture.baseDepth = depth;
  16198. texture.width = width;
  16199. texture.height = height;
  16200. texture.depth = depth;
  16201. texture.format = format;
  16202. texture.type = textureType;
  16203. texture.generateMipMaps = generateMipMaps;
  16204. texture.samplingMode = samplingMode;
  16205. texture.is3D = true;
  16206. if (!this._doNotHandleContextLost) {
  16207. texture._bufferView = data;
  16208. }
  16209. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16210. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16211. // Filters
  16212. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16213. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16214. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16215. if (generateMipMaps) {
  16216. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16217. }
  16218. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16219. this._internalTexturesCache.push(texture);
  16220. return texture;
  16221. };
  16222. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16223. var gl = this._gl;
  16224. if (!gl) {
  16225. return;
  16226. }
  16227. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16228. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16229. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16230. if (!noMipmap && !isCompressed) {
  16231. gl.generateMipmap(gl.TEXTURE_2D);
  16232. }
  16233. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16234. // this.resetTextureCache();
  16235. if (scene) {
  16236. scene._removePendingData(texture);
  16237. }
  16238. texture.onLoadedObservable.notifyObservers(texture);
  16239. texture.onLoadedObservable.clear();
  16240. };
  16241. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16242. var _this = this;
  16243. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16244. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16245. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16246. var gl = this._gl;
  16247. if (!gl) {
  16248. return;
  16249. }
  16250. if (!texture._webGLTexture) {
  16251. // this.resetTextureCache();
  16252. if (scene) {
  16253. scene._removePendingData(texture);
  16254. }
  16255. return;
  16256. }
  16257. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16258. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16259. texture.baseWidth = width;
  16260. texture.baseHeight = height;
  16261. texture.width = potWidth;
  16262. texture.height = potHeight;
  16263. texture.isReady = true;
  16264. if (processFunction(potWidth, potHeight, function () {
  16265. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16266. })) {
  16267. // Returning as texture needs extra async steps
  16268. return;
  16269. }
  16270. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16271. };
  16272. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16273. // Create new RGBA data container.
  16274. var rgbaData;
  16275. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16276. rgbaData = new Float32Array(width * height * 4);
  16277. }
  16278. else {
  16279. rgbaData = new Uint32Array(width * height * 4);
  16280. }
  16281. // Convert each pixel.
  16282. for (var x = 0; x < width; x++) {
  16283. for (var y = 0; y < height; y++) {
  16284. var index = (y * width + x) * 3;
  16285. var newIndex = (y * width + x) * 4;
  16286. // Map Old Value to new value.
  16287. rgbaData[newIndex + 0] = rgbData[index + 0];
  16288. rgbaData[newIndex + 1] = rgbData[index + 1];
  16289. rgbaData[newIndex + 2] = rgbData[index + 2];
  16290. // Add fully opaque alpha channel.
  16291. rgbaData[newIndex + 3] = 1;
  16292. }
  16293. }
  16294. return rgbaData;
  16295. };
  16296. /** @hidden */
  16297. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16298. var gl = this._gl;
  16299. if (texture._framebuffer) {
  16300. gl.deleteFramebuffer(texture._framebuffer);
  16301. texture._framebuffer = null;
  16302. }
  16303. if (texture._depthStencilBuffer) {
  16304. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16305. texture._depthStencilBuffer = null;
  16306. }
  16307. if (texture._MSAAFramebuffer) {
  16308. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16309. texture._MSAAFramebuffer = null;
  16310. }
  16311. if (texture._MSAARenderBuffer) {
  16312. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16313. texture._MSAARenderBuffer = null;
  16314. }
  16315. };
  16316. /** @hidden */
  16317. Engine.prototype._releaseTexture = function (texture) {
  16318. var gl = this._gl;
  16319. this._releaseFramebufferObjects(texture);
  16320. gl.deleteTexture(texture._webGLTexture);
  16321. // Unbind channels
  16322. this.unbindAllTextures();
  16323. var index = this._internalTexturesCache.indexOf(texture);
  16324. if (index !== -1) {
  16325. this._internalTexturesCache.splice(index, 1);
  16326. }
  16327. // Integrated fixed lod samplers.
  16328. if (texture._lodTextureHigh) {
  16329. texture._lodTextureHigh.dispose();
  16330. }
  16331. if (texture._lodTextureMid) {
  16332. texture._lodTextureMid.dispose();
  16333. }
  16334. if (texture._lodTextureLow) {
  16335. texture._lodTextureLow.dispose();
  16336. }
  16337. // Set output texture of post process to null if the texture has been released/disposed
  16338. this.scenes.forEach(function (scene) {
  16339. scene.postProcesses.forEach(function (postProcess) {
  16340. if (postProcess._outputTexture == texture) {
  16341. postProcess._outputTexture = null;
  16342. }
  16343. });
  16344. scene.cameras.forEach(function (camera) {
  16345. camera._postProcesses.forEach(function (postProcess) {
  16346. if (postProcess) {
  16347. if (postProcess._outputTexture == texture) {
  16348. postProcess._outputTexture = null;
  16349. }
  16350. }
  16351. });
  16352. });
  16353. });
  16354. };
  16355. Engine.prototype.setProgram = function (program) {
  16356. if (this._currentProgram !== program) {
  16357. this._gl.useProgram(program);
  16358. this._currentProgram = program;
  16359. }
  16360. };
  16361. /**
  16362. * Binds an effect to the webGL context
  16363. * @param effect defines the effect to bind
  16364. */
  16365. Engine.prototype.bindSamplers = function (effect) {
  16366. this.setProgram(effect.getProgram());
  16367. var samplers = effect.getSamplers();
  16368. for (var index = 0; index < samplers.length; index++) {
  16369. var uniform = effect.getUniform(samplers[index]);
  16370. if (uniform) {
  16371. this._boundUniforms[index] = uniform;
  16372. }
  16373. }
  16374. this._currentEffect = null;
  16375. };
  16376. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16377. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16378. return;
  16379. }
  16380. // Remove
  16381. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16382. // Bind last to it
  16383. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16384. // Bind to dummy
  16385. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16386. };
  16387. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16388. if (!internalTexture) {
  16389. return -1;
  16390. }
  16391. internalTexture._initialSlot = channel;
  16392. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16393. if (channel !== internalTexture._designatedSlot) {
  16394. this._textureCollisions.addCount(1, false);
  16395. }
  16396. }
  16397. else {
  16398. if (channel !== internalTexture._designatedSlot) {
  16399. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16400. return internalTexture._designatedSlot;
  16401. }
  16402. else {
  16403. // No slot for this texture, let's pick a new one (if we find a free slot)
  16404. if (this._nextFreeTextureSlots.length) {
  16405. return this._nextFreeTextureSlots[0];
  16406. }
  16407. // We need to recycle the oldest bound texture, sorry.
  16408. this._textureCollisions.addCount(1, false);
  16409. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16410. }
  16411. }
  16412. }
  16413. return channel;
  16414. };
  16415. Engine.prototype._linkTrackers = function (previous, next) {
  16416. previous.next = next;
  16417. next.previous = previous;
  16418. };
  16419. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16420. var currentSlot = internalTexture._designatedSlot;
  16421. if (currentSlot === -1) {
  16422. return -1;
  16423. }
  16424. internalTexture._designatedSlot = -1;
  16425. if (this.disableTextureBindingOptimization) {
  16426. return -1;
  16427. }
  16428. // Remove from bound list
  16429. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16430. // Free the slot
  16431. this._boundTexturesCache[currentSlot] = null;
  16432. this._nextFreeTextureSlots.push(currentSlot);
  16433. return currentSlot;
  16434. };
  16435. Engine.prototype._activateCurrentTexture = function () {
  16436. if (this._currentTextureChannel !== this._activeChannel) {
  16437. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16438. this._currentTextureChannel = this._activeChannel;
  16439. }
  16440. };
  16441. /** @hidden */
  16442. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16443. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16444. if (force === void 0) { force = false; }
  16445. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16446. this._activeChannel = texture._designatedSlot;
  16447. }
  16448. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16449. var isTextureForRendering = texture && texture._initialSlot > -1;
  16450. if (currentTextureBound !== texture || force) {
  16451. if (currentTextureBound) {
  16452. this._removeDesignatedSlot(currentTextureBound);
  16453. }
  16454. this._activateCurrentTexture();
  16455. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16456. this._boundTexturesCache[this._activeChannel] = texture;
  16457. if (texture) {
  16458. if (!this.disableTextureBindingOptimization) {
  16459. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16460. if (slotIndex > -1) {
  16461. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16462. }
  16463. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16464. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16465. }
  16466. texture._designatedSlot = this._activeChannel;
  16467. }
  16468. }
  16469. else if (forTextureDataUpdate) {
  16470. this._activateCurrentTexture();
  16471. }
  16472. if (isTextureForRendering && !forTextureDataUpdate) {
  16473. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16474. }
  16475. };
  16476. /** @hidden */
  16477. Engine.prototype._bindTexture = function (channel, texture) {
  16478. if (channel < 0) {
  16479. return;
  16480. }
  16481. if (texture) {
  16482. channel = this._getCorrectTextureChannel(channel, texture);
  16483. }
  16484. this._activeChannel = channel;
  16485. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16486. };
  16487. /**
  16488. * Sets a texture to the webGL context from a postprocess
  16489. * @param channel defines the channel to use
  16490. * @param postProcess defines the source postprocess
  16491. */
  16492. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16493. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16494. };
  16495. /**
  16496. * Binds the output of the passed in post process to the texture channel specified
  16497. * @param channel The channel the texture should be bound to
  16498. * @param postProcess The post process which's output should be bound
  16499. */
  16500. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16501. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16502. };
  16503. /**
  16504. * Unbind all textures from the webGL context
  16505. */
  16506. Engine.prototype.unbindAllTextures = function () {
  16507. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16508. this._activeChannel = channel;
  16509. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16510. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16511. if (this.webGLVersion > 1) {
  16512. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16513. }
  16514. }
  16515. };
  16516. /**
  16517. * Sets a texture to the according uniform.
  16518. * @param channel The texture channel
  16519. * @param uniform The uniform to set
  16520. * @param texture The texture to apply
  16521. */
  16522. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16523. if (channel < 0) {
  16524. return;
  16525. }
  16526. if (uniform) {
  16527. this._boundUniforms[channel] = uniform;
  16528. }
  16529. this._setTexture(channel, texture);
  16530. };
  16531. /**
  16532. * Sets a depth stencil texture from a render target to the according uniform.
  16533. * @param channel The texture channel
  16534. * @param uniform The uniform to set
  16535. * @param texture The render target texture containing the depth stencil texture to apply
  16536. */
  16537. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16538. if (channel < 0) {
  16539. return;
  16540. }
  16541. if (uniform) {
  16542. this._boundUniforms[channel] = uniform;
  16543. }
  16544. if (!texture || !texture.depthStencilTexture) {
  16545. this._setTexture(channel, null);
  16546. }
  16547. else {
  16548. this._setTexture(channel, texture, false, true);
  16549. }
  16550. };
  16551. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16552. var uniform = this._boundUniforms[sourceSlot];
  16553. if (uniform._currentState === destination) {
  16554. return;
  16555. }
  16556. this._gl.uniform1i(uniform, destination);
  16557. uniform._currentState = destination;
  16558. };
  16559. Engine.prototype._getTextureWrapMode = function (mode) {
  16560. switch (mode) {
  16561. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16562. return this._gl.REPEAT;
  16563. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16564. return this._gl.CLAMP_TO_EDGE;
  16565. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16566. return this._gl.MIRRORED_REPEAT;
  16567. }
  16568. return this._gl.REPEAT;
  16569. };
  16570. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16571. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16572. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16573. // Not ready?
  16574. if (!texture) {
  16575. if (this._boundTexturesCache[channel] != null) {
  16576. this._activeChannel = channel;
  16577. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16578. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16579. if (this.webGLVersion > 1) {
  16580. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16581. }
  16582. }
  16583. return false;
  16584. }
  16585. // Video
  16586. if (texture.video) {
  16587. this._activeChannel = channel;
  16588. texture.update();
  16589. }
  16590. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16591. texture.delayLoad();
  16592. return false;
  16593. }
  16594. var internalTexture;
  16595. if (depthStencilTexture) {
  16596. internalTexture = texture.depthStencilTexture;
  16597. }
  16598. else if (texture.isReady()) {
  16599. internalTexture = texture.getInternalTexture();
  16600. }
  16601. else if (texture.isCube) {
  16602. internalTexture = this.emptyCubeTexture;
  16603. }
  16604. else if (texture.is3D) {
  16605. internalTexture = this.emptyTexture3D;
  16606. }
  16607. else {
  16608. internalTexture = this.emptyTexture;
  16609. }
  16610. if (!isPartOfTextureArray) {
  16611. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16612. }
  16613. var needToBind = true;
  16614. if (this._boundTexturesCache[channel] === internalTexture) {
  16615. this._moveBoundTextureOnTop(internalTexture);
  16616. if (!isPartOfTextureArray) {
  16617. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16618. }
  16619. needToBind = false;
  16620. }
  16621. this._activeChannel = channel;
  16622. if (internalTexture && internalTexture.is3D) {
  16623. if (needToBind) {
  16624. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16625. }
  16626. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16627. internalTexture._cachedWrapU = texture.wrapU;
  16628. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16629. }
  16630. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16631. internalTexture._cachedWrapV = texture.wrapV;
  16632. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16633. }
  16634. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16635. internalTexture._cachedWrapR = texture.wrapR;
  16636. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16637. }
  16638. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16639. }
  16640. else if (internalTexture && internalTexture.isCube) {
  16641. if (needToBind) {
  16642. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16643. }
  16644. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16645. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16646. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16647. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16648. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16649. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16650. }
  16651. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16652. }
  16653. else {
  16654. if (needToBind) {
  16655. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16656. }
  16657. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16658. internalTexture._cachedWrapU = texture.wrapU;
  16659. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16660. }
  16661. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16662. internalTexture._cachedWrapV = texture.wrapV;
  16663. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16664. }
  16665. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16666. }
  16667. return true;
  16668. };
  16669. /**
  16670. * Sets an array of texture to the webGL context
  16671. * @param channel defines the channel where the texture array must be set
  16672. * @param uniform defines the associated uniform location
  16673. * @param textures defines the array of textures to bind
  16674. */
  16675. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16676. if (channel < 0 || !uniform) {
  16677. return;
  16678. }
  16679. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16680. this._textureUnits = new Int32Array(textures.length);
  16681. }
  16682. for (var i = 0; i < textures.length; i++) {
  16683. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16684. }
  16685. this._gl.uniform1iv(uniform, this._textureUnits);
  16686. for (var index = 0; index < textures.length; index++) {
  16687. this._setTexture(this._textureUnits[index], textures[index], true);
  16688. }
  16689. };
  16690. /** @hidden */
  16691. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16692. var internalTexture = texture.getInternalTexture();
  16693. if (!internalTexture) {
  16694. return;
  16695. }
  16696. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16697. var value = texture.anisotropicFilteringLevel;
  16698. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16699. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16700. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16701. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16702. }
  16703. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16704. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16705. internalTexture._cachedAnisotropicFilteringLevel = value;
  16706. }
  16707. };
  16708. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16709. this._bindTextureDirectly(target, texture, true, true);
  16710. this._gl.texParameterf(target, parameter, value);
  16711. };
  16712. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16713. if (texture) {
  16714. this._bindTextureDirectly(target, texture, true, true);
  16715. }
  16716. this._gl.texParameteri(target, parameter, value);
  16717. };
  16718. /**
  16719. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16720. * @param x defines the x coordinate of the rectangle where pixels must be read
  16721. * @param y defines the y coordinate of the rectangle where pixels must be read
  16722. * @param width defines the width of the rectangle where pixels must be read
  16723. * @param height defines the height of the rectangle where pixels must be read
  16724. * @returns a Uint8Array containing RGBA colors
  16725. */
  16726. Engine.prototype.readPixels = function (x, y, width, height) {
  16727. var data = new Uint8Array(height * width * 4);
  16728. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16729. return data;
  16730. };
  16731. /**
  16732. * Add an externaly attached data from its key.
  16733. * This method call will fail and return false, if such key already exists.
  16734. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16735. * @param key the unique key that identifies the data
  16736. * @param data the data object to associate to the key for this Engine instance
  16737. * @return true if no such key were already present and the data was added successfully, false otherwise
  16738. */
  16739. Engine.prototype.addExternalData = function (key, data) {
  16740. if (!this._externalData) {
  16741. this._externalData = new BABYLON.StringDictionary();
  16742. }
  16743. return this._externalData.add(key, data);
  16744. };
  16745. /**
  16746. * Get an externaly attached data from its key
  16747. * @param key the unique key that identifies the data
  16748. * @return the associated data, if present (can be null), or undefined if not present
  16749. */
  16750. Engine.prototype.getExternalData = function (key) {
  16751. if (!this._externalData) {
  16752. this._externalData = new BABYLON.StringDictionary();
  16753. }
  16754. return this._externalData.get(key);
  16755. };
  16756. /**
  16757. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16758. * @param key the unique key that identifies the data
  16759. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16760. * @return the associated data, can be null if the factory returned null.
  16761. */
  16762. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16763. if (!this._externalData) {
  16764. this._externalData = new BABYLON.StringDictionary();
  16765. }
  16766. return this._externalData.getOrAddWithFactory(key, factory);
  16767. };
  16768. /**
  16769. * Remove an externaly attached data from the Engine instance
  16770. * @param key the unique key that identifies the data
  16771. * @return true if the data was successfully removed, false if it doesn't exist
  16772. */
  16773. Engine.prototype.removeExternalData = function (key) {
  16774. if (!this._externalData) {
  16775. this._externalData = new BABYLON.StringDictionary();
  16776. }
  16777. return this._externalData.remove(key);
  16778. };
  16779. /**
  16780. * Unbind all vertex attributes from the webGL context
  16781. */
  16782. Engine.prototype.unbindAllAttributes = function () {
  16783. if (this._mustWipeVertexAttributes) {
  16784. this._mustWipeVertexAttributes = false;
  16785. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16786. this._gl.disableVertexAttribArray(i);
  16787. this._vertexAttribArraysEnabled[i] = false;
  16788. this._currentBufferPointers[i].active = false;
  16789. }
  16790. return;
  16791. }
  16792. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16793. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16794. continue;
  16795. }
  16796. this._gl.disableVertexAttribArray(i);
  16797. this._vertexAttribArraysEnabled[i] = false;
  16798. this._currentBufferPointers[i].active = false;
  16799. }
  16800. };
  16801. /**
  16802. * 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
  16803. */
  16804. Engine.prototype.releaseEffects = function () {
  16805. for (var name in this._compiledEffects) {
  16806. this._deleteProgram(this._compiledEffects[name]._program);
  16807. }
  16808. this._compiledEffects = {};
  16809. };
  16810. /**
  16811. * Dispose and release all associated resources
  16812. */
  16813. Engine.prototype.dispose = function () {
  16814. this.hideLoadingUI();
  16815. this.stopRenderLoop();
  16816. // Release postProcesses
  16817. while (this.postProcesses.length) {
  16818. this.postProcesses[0].dispose();
  16819. }
  16820. // Empty texture
  16821. if (this._emptyTexture) {
  16822. this._releaseTexture(this._emptyTexture);
  16823. this._emptyTexture = null;
  16824. }
  16825. if (this._emptyCubeTexture) {
  16826. this._releaseTexture(this._emptyCubeTexture);
  16827. this._emptyCubeTexture = null;
  16828. }
  16829. // Rescale PP
  16830. if (this._rescalePostProcess) {
  16831. this._rescalePostProcess.dispose();
  16832. }
  16833. // Release scenes
  16834. while (this.scenes.length) {
  16835. this.scenes[0].dispose();
  16836. }
  16837. // Release audio engine
  16838. if (Engine.audioEngine) {
  16839. Engine.audioEngine.dispose();
  16840. }
  16841. // Release effects
  16842. this.releaseEffects();
  16843. // Unbind
  16844. this.unbindAllAttributes();
  16845. this._boundUniforms = [];
  16846. if (this._dummyFramebuffer) {
  16847. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16848. }
  16849. //WebVR
  16850. this.disableVR();
  16851. // Events
  16852. if (BABYLON.Tools.IsWindowObjectExist()) {
  16853. window.removeEventListener("blur", this._onBlur);
  16854. window.removeEventListener("focus", this._onFocus);
  16855. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16856. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16857. if (this._renderingCanvas) {
  16858. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16859. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16860. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16861. if (!this._doNotHandleContextLost) {
  16862. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16863. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16864. }
  16865. }
  16866. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16867. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16868. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16869. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16870. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16871. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16872. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16873. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16874. if (this._onVrDisplayConnect) {
  16875. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16876. if (this._onVrDisplayDisconnect) {
  16877. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16878. }
  16879. if (this._onVrDisplayPresentChange) {
  16880. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16881. }
  16882. this._onVrDisplayConnect = null;
  16883. this._onVrDisplayDisconnect = null;
  16884. }
  16885. }
  16886. // Remove from Instances
  16887. var index = Engine.Instances.indexOf(this);
  16888. if (index >= 0) {
  16889. Engine.Instances.splice(index, 1);
  16890. }
  16891. this._workingCanvas = null;
  16892. this._workingContext = null;
  16893. this._currentBufferPointers = [];
  16894. this._renderingCanvas = null;
  16895. this._currentProgram = null;
  16896. this._bindedRenderFunction = null;
  16897. this.onResizeObservable.clear();
  16898. this.onCanvasBlurObservable.clear();
  16899. this.onCanvasFocusObservable.clear();
  16900. this.onCanvasPointerOutObservable.clear();
  16901. this.onBeginFrameObservable.clear();
  16902. this.onEndFrameObservable.clear();
  16903. BABYLON.Effect.ResetCache();
  16904. // Abort active requests
  16905. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16906. var request = _a[_i];
  16907. request.abort();
  16908. }
  16909. };
  16910. // Loading screen
  16911. /**
  16912. * Display the loading screen
  16913. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16914. */
  16915. Engine.prototype.displayLoadingUI = function () {
  16916. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16917. return;
  16918. }
  16919. var loadingScreen = this.loadingScreen;
  16920. if (loadingScreen) {
  16921. loadingScreen.displayLoadingUI();
  16922. }
  16923. };
  16924. /**
  16925. * Hide the loading screen
  16926. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16927. */
  16928. Engine.prototype.hideLoadingUI = function () {
  16929. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16930. return;
  16931. }
  16932. var loadingScreen = this.loadingScreen;
  16933. if (loadingScreen) {
  16934. loadingScreen.hideLoadingUI();
  16935. }
  16936. };
  16937. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16938. /**
  16939. * Gets the current loading screen object
  16940. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16941. */
  16942. get: function () {
  16943. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16944. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16945. return this._loadingScreen;
  16946. },
  16947. /**
  16948. * Sets the current loading screen object
  16949. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16950. */
  16951. set: function (loadingScreen) {
  16952. this._loadingScreen = loadingScreen;
  16953. },
  16954. enumerable: true,
  16955. configurable: true
  16956. });
  16957. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16958. /**
  16959. * Sets the current loading screen text
  16960. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16961. */
  16962. set: function (text) {
  16963. this.loadingScreen.loadingUIText = text;
  16964. },
  16965. enumerable: true,
  16966. configurable: true
  16967. });
  16968. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16969. /**
  16970. * Sets the current loading screen background color
  16971. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16972. */
  16973. set: function (color) {
  16974. this.loadingScreen.loadingUIBackgroundColor = color;
  16975. },
  16976. enumerable: true,
  16977. configurable: true
  16978. });
  16979. /**
  16980. * Attach a new callback raised when context lost event is fired
  16981. * @param callback defines the callback to call
  16982. */
  16983. Engine.prototype.attachContextLostEvent = function (callback) {
  16984. if (this._renderingCanvas) {
  16985. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16986. }
  16987. };
  16988. /**
  16989. * Attach a new callback raised when context restored event is fired
  16990. * @param callback defines the callback to call
  16991. */
  16992. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16993. if (this._renderingCanvas) {
  16994. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16995. }
  16996. };
  16997. /**
  16998. * Gets the source code of the vertex shader associated with a specific webGL program
  16999. * @param program defines the program to use
  17000. * @returns a string containing the source code of the vertex shader associated with the program
  17001. */
  17002. Engine.prototype.getVertexShaderSource = function (program) {
  17003. var shaders = this._gl.getAttachedShaders(program);
  17004. if (!shaders) {
  17005. return null;
  17006. }
  17007. return this._gl.getShaderSource(shaders[0]);
  17008. };
  17009. /**
  17010. * Gets the source code of the fragment shader associated with a specific webGL program
  17011. * @param program defines the program to use
  17012. * @returns a string containing the source code of the fragment shader associated with the program
  17013. */
  17014. Engine.prototype.getFragmentShaderSource = function (program) {
  17015. var shaders = this._gl.getAttachedShaders(program);
  17016. if (!shaders) {
  17017. return null;
  17018. }
  17019. return this._gl.getShaderSource(shaders[1]);
  17020. };
  17021. /**
  17022. * Get the current error code of the webGL context
  17023. * @returns the error code
  17024. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17025. */
  17026. Engine.prototype.getError = function () {
  17027. return this._gl.getError();
  17028. };
  17029. // FPS
  17030. /**
  17031. * Gets the current framerate
  17032. * @returns a number representing the framerate
  17033. */
  17034. Engine.prototype.getFps = function () {
  17035. return this._fps;
  17036. };
  17037. /**
  17038. * Gets the time spent between current and previous frame
  17039. * @returns a number representing the delta time in ms
  17040. */
  17041. Engine.prototype.getDeltaTime = function () {
  17042. return this._deltaTime;
  17043. };
  17044. Engine.prototype._measureFps = function () {
  17045. this._performanceMonitor.sampleFrame();
  17046. this._fps = this._performanceMonitor.averageFPS;
  17047. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17048. };
  17049. /** @hidden */
  17050. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  17051. if (faceIndex === void 0) { faceIndex = -1; }
  17052. if (level === void 0) { level = 0; }
  17053. var gl = this._gl;
  17054. if (!this._dummyFramebuffer) {
  17055. var dummy = gl.createFramebuffer();
  17056. if (!dummy) {
  17057. throw new Error("Unable to create dummy framebuffer");
  17058. }
  17059. this._dummyFramebuffer = dummy;
  17060. }
  17061. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17062. if (faceIndex > -1) {
  17063. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17064. }
  17065. else {
  17066. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17067. }
  17068. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17069. var buffer;
  17070. switch (readType) {
  17071. case gl.UNSIGNED_BYTE:
  17072. buffer = new Uint8Array(4 * width * height);
  17073. readType = gl.UNSIGNED_BYTE;
  17074. break;
  17075. default:
  17076. buffer = new Float32Array(4 * width * height);
  17077. readType = gl.FLOAT;
  17078. break;
  17079. }
  17080. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17081. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17082. return buffer;
  17083. };
  17084. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17085. if (this._webGLVersion > 1) {
  17086. return this._caps.colorBufferFloat;
  17087. }
  17088. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17089. };
  17090. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17091. if (this._webGLVersion > 1) {
  17092. return this._caps.colorBufferFloat;
  17093. }
  17094. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17095. };
  17096. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17097. Engine.prototype._canRenderToFramebuffer = function (type) {
  17098. var gl = this._gl;
  17099. //clear existing errors
  17100. while (gl.getError() !== gl.NO_ERROR) { }
  17101. var successful = true;
  17102. var texture = gl.createTexture();
  17103. gl.bindTexture(gl.TEXTURE_2D, texture);
  17104. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17105. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17106. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17107. var fb = gl.createFramebuffer();
  17108. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17109. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17110. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17111. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17112. successful = successful && (gl.getError() === gl.NO_ERROR);
  17113. //try render by clearing frame buffer's color buffer
  17114. if (successful) {
  17115. gl.clear(gl.COLOR_BUFFER_BIT);
  17116. successful = successful && (gl.getError() === gl.NO_ERROR);
  17117. }
  17118. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17119. if (successful) {
  17120. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17121. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17122. var readFormat = gl.RGBA;
  17123. var readType = gl.UNSIGNED_BYTE;
  17124. var buffer = new Uint8Array(4);
  17125. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17126. successful = successful && (gl.getError() === gl.NO_ERROR);
  17127. }
  17128. //clean up
  17129. gl.deleteTexture(texture);
  17130. gl.deleteFramebuffer(fb);
  17131. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17132. //clear accumulated errors
  17133. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17134. return successful;
  17135. };
  17136. /** @hidden */
  17137. Engine.prototype._getWebGLTextureType = function (type) {
  17138. if (type === Engine.TEXTURETYPE_FLOAT) {
  17139. return this._gl.FLOAT;
  17140. }
  17141. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17142. // Add Half Float Constant.
  17143. return this._gl.HALF_FLOAT_OES;
  17144. }
  17145. return this._gl.UNSIGNED_BYTE;
  17146. };
  17147. ;
  17148. Engine.prototype._getInternalFormat = function (format) {
  17149. var internalFormat = this._gl.RGBA;
  17150. switch (format) {
  17151. case Engine.TEXTUREFORMAT_ALPHA:
  17152. internalFormat = this._gl.ALPHA;
  17153. break;
  17154. case Engine.TEXTUREFORMAT_LUMINANCE:
  17155. internalFormat = this._gl.LUMINANCE;
  17156. break;
  17157. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17158. internalFormat = this._gl.LUMINANCE_ALPHA;
  17159. break;
  17160. case Engine.TEXTUREFORMAT_RGB:
  17161. internalFormat = this._gl.RGB;
  17162. break;
  17163. case Engine.TEXTUREFORMAT_RGBA:
  17164. internalFormat = this._gl.RGBA;
  17165. break;
  17166. case Engine.TEXTUREFORMAT_R:
  17167. internalFormat = this._gl.RED;
  17168. break;
  17169. case Engine.TEXTUREFORMAT_RG:
  17170. internalFormat = this._gl.RG;
  17171. break;
  17172. }
  17173. return internalFormat;
  17174. };
  17175. /** @hidden */
  17176. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17177. if (this._webGLVersion === 1) {
  17178. if (format !== undefined) {
  17179. switch (format) {
  17180. case Engine.TEXTUREFORMAT_LUMINANCE:
  17181. return this._gl.LUMINANCE;
  17182. case Engine.TEXTUREFORMAT_ALPHA:
  17183. return this._gl.ALPHA;
  17184. }
  17185. }
  17186. return this._gl.RGBA;
  17187. }
  17188. if (type === Engine.TEXTURETYPE_FLOAT) {
  17189. if (format !== undefined) {
  17190. switch (format) {
  17191. case Engine.TEXTUREFORMAT_R:
  17192. return this._gl.R32F;
  17193. case Engine.TEXTUREFORMAT_RG:
  17194. return this._gl.RG32F;
  17195. case Engine.TEXTUREFORMAT_RGB:
  17196. return this._gl.RGB32F;
  17197. }
  17198. }
  17199. return this._gl.RGBA32F;
  17200. }
  17201. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17202. if (format) {
  17203. switch (format) {
  17204. case Engine.TEXTUREFORMAT_R:
  17205. return this._gl.R16F;
  17206. case Engine.TEXTUREFORMAT_RG:
  17207. return this._gl.RG16F;
  17208. case Engine.TEXTUREFORMAT_RGB:
  17209. return this._gl.RGB16F;
  17210. }
  17211. }
  17212. return this._gl.RGBA16F;
  17213. }
  17214. if (format !== undefined) {
  17215. switch (format) {
  17216. case Engine.TEXTUREFORMAT_LUMINANCE:
  17217. return this._gl.LUMINANCE;
  17218. case Engine.TEXTUREFORMAT_RGB:
  17219. return this._gl.RGB;
  17220. case Engine.TEXTUREFORMAT_R:
  17221. return this._gl.R8;
  17222. case Engine.TEXTUREFORMAT_RG:
  17223. return this._gl.RG8;
  17224. case Engine.TEXTUREFORMAT_ALPHA:
  17225. return this._gl.ALPHA;
  17226. }
  17227. }
  17228. return this._gl.RGBA;
  17229. };
  17230. ;
  17231. /** @hidden */
  17232. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17233. if (type === Engine.TEXTURETYPE_FLOAT) {
  17234. return this._gl.RGBA32F;
  17235. }
  17236. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17237. return this._gl.RGBA16F;
  17238. }
  17239. return this._gl.RGBA8;
  17240. };
  17241. ;
  17242. /**
  17243. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17244. * @return the new query
  17245. */
  17246. Engine.prototype.createQuery = function () {
  17247. return this._gl.createQuery();
  17248. };
  17249. /**
  17250. * Delete and release a webGL query
  17251. * @param query defines the query to delete
  17252. * @return the current engine
  17253. */
  17254. Engine.prototype.deleteQuery = function (query) {
  17255. this._gl.deleteQuery(query);
  17256. return this;
  17257. };
  17258. /**
  17259. * Check if a given query has resolved and got its value
  17260. * @param query defines the query to check
  17261. * @returns true if the query got its value
  17262. */
  17263. Engine.prototype.isQueryResultAvailable = function (query) {
  17264. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17265. };
  17266. /**
  17267. * Gets the value of a given query
  17268. * @param query defines the query to check
  17269. * @returns the value of the query
  17270. */
  17271. Engine.prototype.getQueryResult = function (query) {
  17272. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17273. };
  17274. /**
  17275. * Initiates an occlusion query
  17276. * @param algorithmType defines the algorithm to use
  17277. * @param query defines the query to use
  17278. * @returns the current engine
  17279. * @see http://doc.babylonjs.com/features/occlusionquery
  17280. */
  17281. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17282. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17283. this._gl.beginQuery(glAlgorithm, query);
  17284. return this;
  17285. };
  17286. /**
  17287. * Ends an occlusion query
  17288. * @see http://doc.babylonjs.com/features/occlusionquery
  17289. * @param algorithmType defines the algorithm to use
  17290. * @returns the current engine
  17291. */
  17292. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17293. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17294. this._gl.endQuery(glAlgorithm);
  17295. return this;
  17296. };
  17297. /* Time queries */
  17298. Engine.prototype._createTimeQuery = function () {
  17299. var timerQuery = this._caps.timerQuery;
  17300. if (timerQuery.createQueryEXT) {
  17301. return timerQuery.createQueryEXT();
  17302. }
  17303. return this.createQuery();
  17304. };
  17305. Engine.prototype._deleteTimeQuery = function (query) {
  17306. var timerQuery = this._caps.timerQuery;
  17307. if (timerQuery.deleteQueryEXT) {
  17308. timerQuery.deleteQueryEXT(query);
  17309. return;
  17310. }
  17311. this.deleteQuery(query);
  17312. };
  17313. Engine.prototype._getTimeQueryResult = function (query) {
  17314. var timerQuery = this._caps.timerQuery;
  17315. if (timerQuery.getQueryObjectEXT) {
  17316. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17317. }
  17318. return this.getQueryResult(query);
  17319. };
  17320. Engine.prototype._getTimeQueryAvailability = function (query) {
  17321. var timerQuery = this._caps.timerQuery;
  17322. if (timerQuery.getQueryObjectEXT) {
  17323. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17324. }
  17325. return this.isQueryResultAvailable(query);
  17326. };
  17327. /**
  17328. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17329. * Please note that only one query can be issued at a time
  17330. * @returns a time token used to track the time span
  17331. */
  17332. Engine.prototype.startTimeQuery = function () {
  17333. var timerQuery = this._caps.timerQuery;
  17334. if (!timerQuery) {
  17335. return null;
  17336. }
  17337. var token = new BABYLON._TimeToken();
  17338. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17339. if (this._caps.canUseTimestampForTimerQuery) {
  17340. token._startTimeQuery = this._createTimeQuery();
  17341. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17342. }
  17343. else {
  17344. if (this._currentNonTimestampToken) {
  17345. return this._currentNonTimestampToken;
  17346. }
  17347. token._timeElapsedQuery = this._createTimeQuery();
  17348. if (timerQuery.beginQueryEXT) {
  17349. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17350. }
  17351. else {
  17352. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17353. }
  17354. this._currentNonTimestampToken = token;
  17355. }
  17356. return token;
  17357. };
  17358. /**
  17359. * Ends a time query
  17360. * @param token defines the token used to measure the time span
  17361. * @returns the time spent (in ns)
  17362. */
  17363. Engine.prototype.endTimeQuery = function (token) {
  17364. var timerQuery = this._caps.timerQuery;
  17365. if (!timerQuery || !token) {
  17366. return -1;
  17367. }
  17368. if (this._caps.canUseTimestampForTimerQuery) {
  17369. if (!token._startTimeQuery) {
  17370. return -1;
  17371. }
  17372. if (!token._endTimeQuery) {
  17373. token._endTimeQuery = this._createTimeQuery();
  17374. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17375. }
  17376. }
  17377. else if (!token._timeElapsedQueryEnded) {
  17378. if (!token._timeElapsedQuery) {
  17379. return -1;
  17380. }
  17381. if (timerQuery.endQueryEXT) {
  17382. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17383. }
  17384. else {
  17385. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17386. }
  17387. token._timeElapsedQueryEnded = true;
  17388. }
  17389. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17390. var available = false;
  17391. if (token._endTimeQuery) {
  17392. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17393. }
  17394. else if (token._timeElapsedQuery) {
  17395. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17396. }
  17397. if (available && !disjoint) {
  17398. var result = 0;
  17399. if (this._caps.canUseTimestampForTimerQuery) {
  17400. if (!token._startTimeQuery || !token._endTimeQuery) {
  17401. return -1;
  17402. }
  17403. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17404. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17405. result = timeEnd - timeStart;
  17406. this._deleteTimeQuery(token._startTimeQuery);
  17407. this._deleteTimeQuery(token._endTimeQuery);
  17408. token._startTimeQuery = null;
  17409. token._endTimeQuery = null;
  17410. }
  17411. else {
  17412. if (!token._timeElapsedQuery) {
  17413. return -1;
  17414. }
  17415. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17416. this._deleteTimeQuery(token._timeElapsedQuery);
  17417. token._timeElapsedQuery = null;
  17418. token._timeElapsedQueryEnded = false;
  17419. this._currentNonTimestampToken = null;
  17420. }
  17421. return result;
  17422. }
  17423. return -1;
  17424. };
  17425. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17426. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17427. };
  17428. // Transform feedback
  17429. /**
  17430. * Creates a webGL transform feedback object
  17431. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17432. * @returns the webGL transform feedback object
  17433. */
  17434. Engine.prototype.createTransformFeedback = function () {
  17435. return this._gl.createTransformFeedback();
  17436. };
  17437. /**
  17438. * Delete a webGL transform feedback object
  17439. * @param value defines the webGL transform feedback object to delete
  17440. */
  17441. Engine.prototype.deleteTransformFeedback = function (value) {
  17442. this._gl.deleteTransformFeedback(value);
  17443. };
  17444. /**
  17445. * Bind a webGL transform feedback object to the webgl context
  17446. * @param value defines the webGL transform feedback object to bind
  17447. */
  17448. Engine.prototype.bindTransformFeedback = function (value) {
  17449. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17450. };
  17451. /**
  17452. * Begins a transform feedback operation
  17453. * @param usePoints defines if points or triangles must be used
  17454. */
  17455. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17456. if (usePoints === void 0) { usePoints = true; }
  17457. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17458. };
  17459. /**
  17460. * Ends a transform feedback operation
  17461. */
  17462. Engine.prototype.endTransformFeedback = function () {
  17463. this._gl.endTransformFeedback();
  17464. };
  17465. /**
  17466. * Specify the varyings to use with transform feedback
  17467. * @param program defines the associated webGL program
  17468. * @param value defines the list of strings representing the varying names
  17469. */
  17470. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17471. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17472. };
  17473. /**
  17474. * Bind a webGL buffer for a transform feedback operation
  17475. * @param value defines the webGL buffer to bind
  17476. */
  17477. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17478. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17479. };
  17480. /** @hidden */
  17481. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17482. var _this = this;
  17483. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17484. this._activeRequests.push(request);
  17485. request.onCompleteObservable.add(function (request) {
  17486. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17487. });
  17488. return request;
  17489. };
  17490. /** @hidden */
  17491. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17492. var _this = this;
  17493. return new Promise(function (resolve, reject) {
  17494. _this._loadFile(url, function (data) {
  17495. resolve(data);
  17496. }, undefined, database, useArrayBuffer, function (request, exception) {
  17497. reject(exception);
  17498. });
  17499. });
  17500. };
  17501. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17502. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17503. var onload = function (data) {
  17504. loadedFiles[index] = data;
  17505. loadedFiles._internalCount++;
  17506. if (loadedFiles._internalCount === 6) {
  17507. onfinish(loadedFiles);
  17508. }
  17509. };
  17510. var onerror = function (request, exception) {
  17511. if (onErrorCallBack && request) {
  17512. onErrorCallBack(request.status + " " + request.statusText, exception);
  17513. }
  17514. };
  17515. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17516. };
  17517. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17518. if (onError === void 0) { onError = null; }
  17519. var loadedFiles = [];
  17520. loadedFiles._internalCount = 0;
  17521. for (var index = 0; index < 6; index++) {
  17522. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17523. }
  17524. };
  17525. // Statics
  17526. /**
  17527. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17528. * @returns true if the engine can be created
  17529. * @ignorenaming
  17530. */
  17531. Engine.isSupported = function () {
  17532. try {
  17533. var tempcanvas = document.createElement("canvas");
  17534. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17535. return gl != null && !!window.WebGLRenderingContext;
  17536. }
  17537. catch (e) {
  17538. return false;
  17539. }
  17540. };
  17541. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17542. Engine.ExceptionList = [
  17543. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17544. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17545. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17546. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17547. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17548. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17549. ];
  17550. /** Gets the list of created engines */
  17551. Engine.Instances = new Array();
  17552. // Const statics
  17553. Engine._ALPHA_DISABLE = 0;
  17554. Engine._ALPHA_ADD = 1;
  17555. Engine._ALPHA_COMBINE = 2;
  17556. Engine._ALPHA_SUBTRACT = 3;
  17557. Engine._ALPHA_MULTIPLY = 4;
  17558. Engine._ALPHA_MAXIMIZED = 5;
  17559. Engine._ALPHA_ONEONE = 6;
  17560. Engine._ALPHA_PREMULTIPLIED = 7;
  17561. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17562. Engine._ALPHA_INTERPOLATE = 9;
  17563. Engine._ALPHA_SCREENMODE = 10;
  17564. Engine._DELAYLOADSTATE_NONE = 0;
  17565. Engine._DELAYLOADSTATE_LOADED = 1;
  17566. Engine._DELAYLOADSTATE_LOADING = 2;
  17567. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17568. Engine._TEXTUREFORMAT_ALPHA = 0;
  17569. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17570. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17571. Engine._TEXTUREFORMAT_RGB = 4;
  17572. Engine._TEXTUREFORMAT_RGBA = 5;
  17573. Engine._TEXTUREFORMAT_R = 6;
  17574. Engine._TEXTUREFORMAT_RG = 7;
  17575. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17576. Engine._TEXTURETYPE_FLOAT = 1;
  17577. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17578. // Depht or Stencil test Constants.
  17579. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17580. 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.
  17581. 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.
  17582. 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.
  17583. 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.
  17584. 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.
  17585. 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.
  17586. 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.
  17587. // Stencil Actions Constants.
  17588. Engine._KEEP = 0x1E00;
  17589. Engine._REPLACE = 0x1E01;
  17590. Engine._INCR = 0x1E02;
  17591. Engine._DECR = 0x1E03;
  17592. Engine._INVERT = 0x150A;
  17593. Engine._INCR_WRAP = 0x8507;
  17594. Engine._DECR_WRAP = 0x8508;
  17595. // Texture rescaling mode
  17596. Engine._SCALEMODE_FLOOR = 1;
  17597. Engine._SCALEMODE_NEAREST = 2;
  17598. Engine._SCALEMODE_CEILING = 3;
  17599. // Updatable statics so stick with vars here
  17600. /**
  17601. * Gets or sets the epsilon value used by collision engine
  17602. */
  17603. Engine.CollisionsEpsilon = 0.001;
  17604. /**
  17605. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17606. */
  17607. Engine.CodeRepository = "src/";
  17608. /**
  17609. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17610. */
  17611. Engine.ShadersRepository = "src/Shaders/";
  17612. return Engine;
  17613. }());
  17614. BABYLON.Engine = Engine;
  17615. })(BABYLON || (BABYLON = {}));
  17616. //# sourceMappingURL=babylon.engine.js.map
  17617. var BABYLON;
  17618. (function (BABYLON) {
  17619. /**
  17620. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17621. */
  17622. var Node = /** @class */ (function () {
  17623. /**
  17624. * Creates a new Node
  17625. * @param {string} name - the name and id to be given to this node
  17626. * @param {BABYLON.Scene} the scene this node will be added to
  17627. */
  17628. function Node(name, scene) {
  17629. if (scene === void 0) { scene = null; }
  17630. /**
  17631. * Gets or sets a string used to store user defined state for the node
  17632. */
  17633. this.state = "";
  17634. /**
  17635. * Gets or sets an object used to store user defined information for the node
  17636. */
  17637. this.metadata = null;
  17638. /**
  17639. * Gets or sets a boolean used to define if the node must be serialized
  17640. */
  17641. this.doNotSerialize = false;
  17642. /** @hidden */
  17643. this._isDisposed = false;
  17644. /**
  17645. * Gets a list of Animations associated with the node
  17646. */
  17647. this.animations = new Array();
  17648. this._ranges = {};
  17649. this._isEnabled = true;
  17650. this._isReady = true;
  17651. /** @hidden */
  17652. this._currentRenderId = -1;
  17653. this._parentRenderId = -1;
  17654. this._childRenderId = -1;
  17655. this._animationPropertiesOverride = null;
  17656. /**
  17657. * An event triggered when the mesh is disposed
  17658. */
  17659. this.onDisposeObservable = new BABYLON.Observable();
  17660. // Behaviors
  17661. this._behaviors = new Array();
  17662. this.name = name;
  17663. this.id = name;
  17664. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17665. this.uniqueId = this._scene.getUniqueId();
  17666. this._initCache();
  17667. }
  17668. /**
  17669. * Gets a boolean indicating if the node has been disposed
  17670. * @returns true if the node was disposed
  17671. */
  17672. Node.prototype.isDisposed = function () {
  17673. return this._isDisposed;
  17674. };
  17675. Object.defineProperty(Node.prototype, "parent", {
  17676. get: function () {
  17677. return this._parentNode;
  17678. },
  17679. /**
  17680. * Gets or sets the parent of the node
  17681. */
  17682. set: function (parent) {
  17683. if (this._parentNode === parent) {
  17684. return;
  17685. }
  17686. // Remove self from list of children of parent
  17687. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17688. var index = this._parentNode._children.indexOf(this);
  17689. if (index !== -1) {
  17690. this._parentNode._children.splice(index, 1);
  17691. }
  17692. }
  17693. // Store new parent
  17694. this._parentNode = parent;
  17695. // Add as child to new parent
  17696. if (this._parentNode) {
  17697. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17698. this._parentNode._children = new Array();
  17699. }
  17700. this._parentNode._children.push(this);
  17701. }
  17702. },
  17703. enumerable: true,
  17704. configurable: true
  17705. });
  17706. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17707. /**
  17708. * Gets or sets the animation properties override
  17709. */
  17710. get: function () {
  17711. if (!this._animationPropertiesOverride) {
  17712. return this._scene.animationPropertiesOverride;
  17713. }
  17714. return this._animationPropertiesOverride;
  17715. },
  17716. set: function (value) {
  17717. this._animationPropertiesOverride = value;
  17718. },
  17719. enumerable: true,
  17720. configurable: true
  17721. });
  17722. /**
  17723. * Gets a string idenfifying the name of the class
  17724. * @returns "Node" string
  17725. */
  17726. Node.prototype.getClassName = function () {
  17727. return "Node";
  17728. };
  17729. Object.defineProperty(Node.prototype, "onDispose", {
  17730. /**
  17731. * Sets a callback that will be raised when the node will be disposed
  17732. */
  17733. set: function (callback) {
  17734. if (this._onDisposeObserver) {
  17735. this.onDisposeObservable.remove(this._onDisposeObserver);
  17736. }
  17737. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17738. },
  17739. enumerable: true,
  17740. configurable: true
  17741. });
  17742. /**
  17743. * Gets the scene of the node
  17744. * @returns a {BABYLON.Scene}
  17745. */
  17746. Node.prototype.getScene = function () {
  17747. return this._scene;
  17748. };
  17749. /**
  17750. * Gets the engine of the node
  17751. * @returns a {BABYLON.Engine}
  17752. */
  17753. Node.prototype.getEngine = function () {
  17754. return this._scene.getEngine();
  17755. };
  17756. /**
  17757. * Attach a behavior to the node
  17758. * @see http://doc.babylonjs.com/features/behaviour
  17759. * @param behavior defines the behavior to attach
  17760. * @returns the current Node
  17761. */
  17762. Node.prototype.addBehavior = function (behavior) {
  17763. var _this = this;
  17764. var index = this._behaviors.indexOf(behavior);
  17765. if (index !== -1) {
  17766. return this;
  17767. }
  17768. behavior.init();
  17769. if (this._scene.isLoading) {
  17770. // We defer the attach when the scene will be loaded
  17771. this._scene.onDataLoadedObservable.addOnce(function () {
  17772. behavior.attach(_this);
  17773. });
  17774. }
  17775. else {
  17776. behavior.attach(this);
  17777. }
  17778. this._behaviors.push(behavior);
  17779. return this;
  17780. };
  17781. /**
  17782. * Remove an attached behavior
  17783. * @see http://doc.babylonjs.com/features/behaviour
  17784. * @param behavior defines the behavior to attach
  17785. * @returns the current Node
  17786. */
  17787. Node.prototype.removeBehavior = function (behavior) {
  17788. var index = this._behaviors.indexOf(behavior);
  17789. if (index === -1) {
  17790. return this;
  17791. }
  17792. this._behaviors[index].detach();
  17793. this._behaviors.splice(index, 1);
  17794. return this;
  17795. };
  17796. Object.defineProperty(Node.prototype, "behaviors", {
  17797. /**
  17798. * Gets the list of attached behaviors
  17799. * @see http://doc.babylonjs.com/features/behaviour
  17800. */
  17801. get: function () {
  17802. return this._behaviors;
  17803. },
  17804. enumerable: true,
  17805. configurable: true
  17806. });
  17807. /**
  17808. * Gets an attached behavior by name
  17809. * @param name defines the name of the behavior to look for
  17810. * @see http://doc.babylonjs.com/features/behaviour
  17811. * @returns null if behavior was not found else the requested behavior
  17812. */
  17813. Node.prototype.getBehaviorByName = function (name) {
  17814. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17815. var behavior = _a[_i];
  17816. if (behavior.name === name) {
  17817. return behavior;
  17818. }
  17819. }
  17820. return null;
  17821. };
  17822. /**
  17823. * Returns the world matrix of the node
  17824. * @returns a matrix containing the node's world matrix
  17825. */
  17826. Node.prototype.getWorldMatrix = function () {
  17827. return BABYLON.Matrix.Identity();
  17828. };
  17829. /** @hidden */
  17830. Node.prototype._getWorldMatrixDeterminant = function () {
  17831. return 1;
  17832. };
  17833. // override it in derived class if you add new variables to the cache
  17834. // and call the parent class method
  17835. /** @hidden */
  17836. Node.prototype._initCache = function () {
  17837. this._cache = {};
  17838. this._cache.parent = undefined;
  17839. };
  17840. /** @hidden */
  17841. Node.prototype.updateCache = function (force) {
  17842. if (!force && this.isSynchronized())
  17843. return;
  17844. this._cache.parent = this.parent;
  17845. this._updateCache();
  17846. };
  17847. // override it in derived class if you add new variables to the cache
  17848. // and call the parent class method if !ignoreParentClass
  17849. /** @hidden */
  17850. Node.prototype._updateCache = function (ignoreParentClass) {
  17851. };
  17852. // override it in derived class if you add new variables to the cache
  17853. /** @hidden */
  17854. Node.prototype._isSynchronized = function () {
  17855. return true;
  17856. };
  17857. /** @hidden */
  17858. Node.prototype._markSyncedWithParent = function () {
  17859. if (this.parent) {
  17860. this._parentRenderId = this.parent._childRenderId;
  17861. }
  17862. };
  17863. /** @hidden */
  17864. Node.prototype.isSynchronizedWithParent = function () {
  17865. if (!this.parent) {
  17866. return true;
  17867. }
  17868. if (this._parentRenderId !== this.parent._childRenderId) {
  17869. return false;
  17870. }
  17871. return this.parent.isSynchronized();
  17872. };
  17873. /** @hidden */
  17874. Node.prototype.isSynchronized = function (updateCache) {
  17875. var check = this.hasNewParent();
  17876. check = check || !this.isSynchronizedWithParent();
  17877. check = check || !this._isSynchronized();
  17878. if (updateCache)
  17879. this.updateCache(true);
  17880. return !check;
  17881. };
  17882. /** @hidden */
  17883. Node.prototype.hasNewParent = function (update) {
  17884. if (this._cache.parent === this.parent)
  17885. return false;
  17886. if (update)
  17887. this._cache.parent = this.parent;
  17888. return true;
  17889. };
  17890. /**
  17891. * Is this node ready to be used/rendered
  17892. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17893. * @return true if the node is ready
  17894. */
  17895. Node.prototype.isReady = function (completeCheck) {
  17896. if (completeCheck === void 0) { completeCheck = false; }
  17897. return this._isReady;
  17898. };
  17899. /**
  17900. * Is this node enabled?
  17901. * 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
  17902. * @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
  17903. * @return whether this node (and its parent) is enabled
  17904. */
  17905. Node.prototype.isEnabled = function (checkAncestors) {
  17906. if (checkAncestors === void 0) { checkAncestors = true; }
  17907. if (checkAncestors === false) {
  17908. return this._isEnabled;
  17909. }
  17910. if (this._isEnabled === false) {
  17911. return false;
  17912. }
  17913. if (this.parent !== undefined && this.parent !== null) {
  17914. return this.parent.isEnabled(checkAncestors);
  17915. }
  17916. return true;
  17917. };
  17918. /**
  17919. * Set the enabled state of this node
  17920. * @param value defines the new enabled state
  17921. */
  17922. Node.prototype.setEnabled = function (value) {
  17923. this._isEnabled = value;
  17924. };
  17925. /**
  17926. * Is this node a descendant of the given node?
  17927. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17928. * @param ancestor defines the parent node to inspect
  17929. * @returns a boolean indicating if this node is a descendant of the given node
  17930. */
  17931. Node.prototype.isDescendantOf = function (ancestor) {
  17932. if (this.parent) {
  17933. if (this.parent === ancestor) {
  17934. return true;
  17935. }
  17936. return this.parent.isDescendantOf(ancestor);
  17937. }
  17938. return false;
  17939. };
  17940. /** @hidden */
  17941. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17942. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17943. if (!this._children) {
  17944. return;
  17945. }
  17946. for (var index = 0; index < this._children.length; index++) {
  17947. var item = this._children[index];
  17948. if (!predicate || predicate(item)) {
  17949. results.push(item);
  17950. }
  17951. if (!directDescendantsOnly) {
  17952. item._getDescendants(results, false, predicate);
  17953. }
  17954. }
  17955. };
  17956. /**
  17957. * Will return all nodes that have this node as ascendant
  17958. * @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
  17959. * @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
  17960. * @return all children nodes of all types
  17961. */
  17962. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17963. var results = new Array();
  17964. this._getDescendants(results, directDescendantsOnly, predicate);
  17965. return results;
  17966. };
  17967. /**
  17968. * Get all child-meshes of this node
  17969. * @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
  17970. * @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
  17971. * @returns an array of {BABYLON.AbstractMesh}
  17972. */
  17973. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17974. var results = [];
  17975. this._getDescendants(results, directDescendantsOnly, function (node) {
  17976. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17977. });
  17978. return results;
  17979. };
  17980. /**
  17981. * Get all child-transformNodes of this node
  17982. * @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
  17983. * @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
  17984. * @returns an array of {BABYLON.TransformNode}
  17985. */
  17986. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17987. var results = [];
  17988. this._getDescendants(results, directDescendantsOnly, function (node) {
  17989. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17990. });
  17991. return results;
  17992. };
  17993. /**
  17994. * Get all direct children of this node
  17995. * @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
  17996. * @returns an array of {BABYLON.Node}
  17997. */
  17998. Node.prototype.getChildren = function (predicate) {
  17999. return this.getDescendants(true, predicate);
  18000. };
  18001. /** @hidden */
  18002. Node.prototype._setReady = function (state) {
  18003. if (state === this._isReady) {
  18004. return;
  18005. }
  18006. if (!state) {
  18007. this._isReady = false;
  18008. return;
  18009. }
  18010. if (this.onReady) {
  18011. this.onReady(this);
  18012. }
  18013. this._isReady = true;
  18014. };
  18015. /**
  18016. * Get an animation by name
  18017. * @param name defines the name of the animation to look for
  18018. * @returns null if not found else the requested animation
  18019. */
  18020. Node.prototype.getAnimationByName = function (name) {
  18021. for (var i = 0; i < this.animations.length; i++) {
  18022. var animation = this.animations[i];
  18023. if (animation.name === name) {
  18024. return animation;
  18025. }
  18026. }
  18027. return null;
  18028. };
  18029. /**
  18030. * Creates an animation range for this node
  18031. * @param name defines the name of the range
  18032. * @param from defines the starting key
  18033. * @param to defines the end key
  18034. */
  18035. Node.prototype.createAnimationRange = function (name, from, to) {
  18036. // check name not already in use
  18037. if (!this._ranges[name]) {
  18038. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18039. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18040. if (this.animations[i]) {
  18041. this.animations[i].createRange(name, from, to);
  18042. }
  18043. }
  18044. }
  18045. };
  18046. /**
  18047. * Delete a specific animation range
  18048. * @param name defines the name of the range to delete
  18049. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18050. */
  18051. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18052. if (deleteFrames === void 0) { deleteFrames = true; }
  18053. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18054. if (this.animations[i]) {
  18055. this.animations[i].deleteRange(name, deleteFrames);
  18056. }
  18057. }
  18058. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18059. };
  18060. /**
  18061. * Get an animation range by name
  18062. * @param name defines the name of the animation range to look for
  18063. * @returns null if not found else the requested animation range
  18064. */
  18065. Node.prototype.getAnimationRange = function (name) {
  18066. return this._ranges[name];
  18067. };
  18068. /**
  18069. * Will start the animation sequence
  18070. * @param name defines the range frames for animation sequence
  18071. * @param loop defines if the animation should loop (false by default)
  18072. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18073. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18074. * @returns the object created for this animation. If range does not exist, it will return null
  18075. */
  18076. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18077. var range = this.getAnimationRange(name);
  18078. if (!range) {
  18079. return null;
  18080. }
  18081. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18082. };
  18083. /**
  18084. * Serialize animation ranges into a JSON compatible object
  18085. * @returns serialization object
  18086. */
  18087. Node.prototype.serializeAnimationRanges = function () {
  18088. var serializationRanges = [];
  18089. for (var name in this._ranges) {
  18090. var localRange = this._ranges[name];
  18091. if (!localRange) {
  18092. continue;
  18093. }
  18094. var range = {};
  18095. range.name = name;
  18096. range.from = localRange.from;
  18097. range.to = localRange.to;
  18098. serializationRanges.push(range);
  18099. }
  18100. return serializationRanges;
  18101. };
  18102. /**
  18103. * Computes the world matrix of the node
  18104. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18105. * @returns the world matrix
  18106. */
  18107. Node.prototype.computeWorldMatrix = function (force) {
  18108. return BABYLON.Matrix.Identity();
  18109. };
  18110. /**
  18111. * Releases resources associated with this node.
  18112. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18113. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18114. */
  18115. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18116. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18117. if (!doNotRecurse) {
  18118. var nodes = this.getDescendants(true);
  18119. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18120. var node = nodes_1[_i];
  18121. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18122. }
  18123. }
  18124. else {
  18125. var transformNodes = this.getChildTransformNodes(true);
  18126. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18127. var transformNode = transformNodes_1[_a];
  18128. transformNode.parent = null;
  18129. transformNode.computeWorldMatrix(true);
  18130. }
  18131. }
  18132. this.parent = null;
  18133. // Callback
  18134. this.onDisposeObservable.notifyObservers(this);
  18135. this.onDisposeObservable.clear();
  18136. // Behaviors
  18137. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18138. var behavior = _c[_b];
  18139. behavior.detach();
  18140. }
  18141. this._behaviors = [];
  18142. this._isDisposed = true;
  18143. };
  18144. /**
  18145. * Parse animation range data from a serialization object and store them into a given node
  18146. * @param node defines where to store the animation ranges
  18147. * @param parsedNode defines the serialization object to read data from
  18148. * @param scene defines the hosting scene
  18149. */
  18150. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18151. if (parsedNode.ranges) {
  18152. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18153. var data = parsedNode.ranges[index];
  18154. node.createAnimationRange(data.name, data.from, data.to);
  18155. }
  18156. }
  18157. };
  18158. __decorate([
  18159. BABYLON.serialize()
  18160. ], Node.prototype, "name", void 0);
  18161. __decorate([
  18162. BABYLON.serialize()
  18163. ], Node.prototype, "id", void 0);
  18164. __decorate([
  18165. BABYLON.serialize()
  18166. ], Node.prototype, "uniqueId", void 0);
  18167. __decorate([
  18168. BABYLON.serialize()
  18169. ], Node.prototype, "state", void 0);
  18170. __decorate([
  18171. BABYLON.serialize()
  18172. ], Node.prototype, "metadata", void 0);
  18173. return Node;
  18174. }());
  18175. BABYLON.Node = Node;
  18176. })(BABYLON || (BABYLON = {}));
  18177. //# sourceMappingURL=babylon.node.js.map
  18178. var BABYLON;
  18179. (function (BABYLON) {
  18180. var BoundingSphere = /** @class */ (function () {
  18181. /**
  18182. * Creates a new bounding sphere
  18183. * @param min defines the minimum vector (in local space)
  18184. * @param max defines the maximum vector (in local space)
  18185. */
  18186. function BoundingSphere(min, max) {
  18187. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18188. this.reConstruct(min, max);
  18189. }
  18190. /**
  18191. * Recreates the entire bounding sphere from scratch
  18192. * @param min defines the new minimum vector (in local space)
  18193. * @param max defines the new maximum vector (in local space)
  18194. */
  18195. BoundingSphere.prototype.reConstruct = function (min, max) {
  18196. this.minimum = min.clone();
  18197. this.maximum = max.clone();
  18198. var distance = BABYLON.Vector3.Distance(min, max);
  18199. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18200. this.radius = distance * 0.5;
  18201. this.centerWorld = BABYLON.Vector3.Zero();
  18202. this._update(BABYLON.Matrix.Identity());
  18203. };
  18204. // Methods
  18205. BoundingSphere.prototype._update = function (world) {
  18206. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18207. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18208. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18209. };
  18210. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18211. for (var i = 0; i < 6; i++) {
  18212. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18213. return false;
  18214. }
  18215. return true;
  18216. };
  18217. BoundingSphere.prototype.intersectsPoint = function (point) {
  18218. var x = this.centerWorld.x - point.x;
  18219. var y = this.centerWorld.y - point.y;
  18220. var z = this.centerWorld.z - point.z;
  18221. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18222. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18223. return false;
  18224. return true;
  18225. };
  18226. // Statics
  18227. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18228. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18229. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18230. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18231. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18232. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18233. return false;
  18234. return true;
  18235. };
  18236. return BoundingSphere;
  18237. }());
  18238. BABYLON.BoundingSphere = BoundingSphere;
  18239. })(BABYLON || (BABYLON = {}));
  18240. //# sourceMappingURL=babylon.boundingSphere.js.map
  18241. var BABYLON;
  18242. (function (BABYLON) {
  18243. var BoundingBox = /** @class */ (function () {
  18244. /**
  18245. * Creates a new bounding box
  18246. * @param min defines the minimum vector (in local space)
  18247. * @param max defines the maximum vector (in local space)
  18248. */
  18249. function BoundingBox(min, max) {
  18250. this.vectorsWorld = new Array();
  18251. this.reConstruct(min, max);
  18252. }
  18253. // Methods
  18254. /**
  18255. * Recreates the entire bounding box from scratch
  18256. * @param min defines the new minimum vector (in local space)
  18257. * @param max defines the new maximum vector (in local space)
  18258. */
  18259. BoundingBox.prototype.reConstruct = function (min, max) {
  18260. this.minimum = min.clone();
  18261. this.maximum = max.clone();
  18262. // Bounding vectors
  18263. this.vectors = new Array();
  18264. this.vectors.push(this.minimum.clone());
  18265. this.vectors.push(this.maximum.clone());
  18266. this.vectors.push(this.minimum.clone());
  18267. this.vectors[2].x = this.maximum.x;
  18268. this.vectors.push(this.minimum.clone());
  18269. this.vectors[3].y = this.maximum.y;
  18270. this.vectors.push(this.minimum.clone());
  18271. this.vectors[4].z = this.maximum.z;
  18272. this.vectors.push(this.maximum.clone());
  18273. this.vectors[5].z = this.minimum.z;
  18274. this.vectors.push(this.maximum.clone());
  18275. this.vectors[6].x = this.minimum.x;
  18276. this.vectors.push(this.maximum.clone());
  18277. this.vectors[7].y = this.minimum.y;
  18278. // OBB
  18279. this.center = this.maximum.add(this.minimum).scale(0.5);
  18280. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18281. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18282. // World
  18283. for (var index = 0; index < this.vectors.length; index++) {
  18284. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18285. }
  18286. this.minimumWorld = BABYLON.Vector3.Zero();
  18287. this.maximumWorld = BABYLON.Vector3.Zero();
  18288. this.centerWorld = BABYLON.Vector3.Zero();
  18289. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18290. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18291. };
  18292. BoundingBox.prototype.getWorldMatrix = function () {
  18293. return this._worldMatrix;
  18294. };
  18295. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18296. this._worldMatrix.copyFrom(matrix);
  18297. return this;
  18298. };
  18299. BoundingBox.prototype._update = function (world) {
  18300. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18301. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18302. for (var index = 0; index < this.vectors.length; index++) {
  18303. var v = this.vectorsWorld[index];
  18304. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18305. if (v.x < this.minimumWorld.x)
  18306. this.minimumWorld.x = v.x;
  18307. if (v.y < this.minimumWorld.y)
  18308. this.minimumWorld.y = v.y;
  18309. if (v.z < this.minimumWorld.z)
  18310. this.minimumWorld.z = v.z;
  18311. if (v.x > this.maximumWorld.x)
  18312. this.maximumWorld.x = v.x;
  18313. if (v.y > this.maximumWorld.y)
  18314. this.maximumWorld.y = v.y;
  18315. if (v.z > this.maximumWorld.z)
  18316. this.maximumWorld.z = v.z;
  18317. }
  18318. // Extend
  18319. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18320. this.extendSizeWorld.scaleInPlace(0.5);
  18321. // OBB
  18322. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18323. this.centerWorld.scaleInPlace(0.5);
  18324. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18325. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18326. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18327. this._worldMatrix = world;
  18328. };
  18329. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18330. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18331. };
  18332. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18333. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18334. };
  18335. BoundingBox.prototype.intersectsPoint = function (point) {
  18336. var delta = -BABYLON.Epsilon;
  18337. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18338. return false;
  18339. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18340. return false;
  18341. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18342. return false;
  18343. return true;
  18344. };
  18345. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18346. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18347. };
  18348. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18349. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18350. return false;
  18351. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18352. return false;
  18353. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18354. return false;
  18355. return true;
  18356. };
  18357. // Statics
  18358. BoundingBox.Intersects = function (box0, box1) {
  18359. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18360. return false;
  18361. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18362. return false;
  18363. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18364. return false;
  18365. return true;
  18366. };
  18367. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18368. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18369. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18370. return (num <= (sphereRadius * sphereRadius));
  18371. };
  18372. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18373. for (var p = 0; p < 6; p++) {
  18374. for (var i = 0; i < 8; i++) {
  18375. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18376. return false;
  18377. }
  18378. }
  18379. }
  18380. return true;
  18381. };
  18382. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18383. for (var p = 0; p < 6; p++) {
  18384. var inCount = 8;
  18385. for (var i = 0; i < 8; i++) {
  18386. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18387. --inCount;
  18388. }
  18389. else {
  18390. break;
  18391. }
  18392. }
  18393. if (inCount === 0)
  18394. return false;
  18395. }
  18396. return true;
  18397. };
  18398. return BoundingBox;
  18399. }());
  18400. BABYLON.BoundingBox = BoundingBox;
  18401. })(BABYLON || (BABYLON = {}));
  18402. //# sourceMappingURL=babylon.boundingBox.js.map
  18403. var BABYLON;
  18404. (function (BABYLON) {
  18405. var computeBoxExtents = function (axis, box) {
  18406. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18407. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18408. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18409. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18410. var r = r0 + r1 + r2;
  18411. return {
  18412. min: p - r,
  18413. max: p + r
  18414. };
  18415. };
  18416. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18417. var axisOverlap = function (axis, box0, box1) {
  18418. var result0 = computeBoxExtents(axis, box0);
  18419. var result1 = computeBoxExtents(axis, box1);
  18420. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18421. };
  18422. var BoundingInfo = /** @class */ (function () {
  18423. function BoundingInfo(minimum, maximum) {
  18424. this.minimum = minimum;
  18425. this.maximum = maximum;
  18426. this._isLocked = false;
  18427. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18428. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18429. }
  18430. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18431. get: function () {
  18432. return this._isLocked;
  18433. },
  18434. set: function (value) {
  18435. this._isLocked = value;
  18436. },
  18437. enumerable: true,
  18438. configurable: true
  18439. });
  18440. // Methods
  18441. BoundingInfo.prototype.update = function (world) {
  18442. if (this._isLocked) {
  18443. return;
  18444. }
  18445. this.boundingBox._update(world);
  18446. this.boundingSphere._update(world);
  18447. };
  18448. /**
  18449. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18450. * @param center New center of the bounding info
  18451. * @param extend New extend of the bounding info
  18452. */
  18453. BoundingInfo.prototype.centerOn = function (center, extend) {
  18454. this.minimum = center.subtract(extend);
  18455. this.maximum = center.add(extend);
  18456. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18457. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18458. return this;
  18459. };
  18460. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18461. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18462. return false;
  18463. return this.boundingBox.isInFrustum(frustumPlanes);
  18464. };
  18465. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18466. /**
  18467. * Gets the world distance between the min and max points of the bounding box
  18468. */
  18469. get: function () {
  18470. var boundingBox = this.boundingBox;
  18471. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18472. return size.length();
  18473. },
  18474. enumerable: true,
  18475. configurable: true
  18476. });
  18477. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18478. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18479. };
  18480. BoundingInfo.prototype._checkCollision = function (collider) {
  18481. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18482. };
  18483. BoundingInfo.prototype.intersectsPoint = function (point) {
  18484. if (!this.boundingSphere.centerWorld) {
  18485. return false;
  18486. }
  18487. if (!this.boundingSphere.intersectsPoint(point)) {
  18488. return false;
  18489. }
  18490. if (!this.boundingBox.intersectsPoint(point)) {
  18491. return false;
  18492. }
  18493. return true;
  18494. };
  18495. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18496. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18497. return false;
  18498. }
  18499. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18500. return false;
  18501. }
  18502. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18503. return false;
  18504. }
  18505. if (!precise) {
  18506. return true;
  18507. }
  18508. var box0 = this.boundingBox;
  18509. var box1 = boundingInfo.boundingBox;
  18510. if (!axisOverlap(box0.directions[0], box0, box1))
  18511. return false;
  18512. if (!axisOverlap(box0.directions[1], box0, box1))
  18513. return false;
  18514. if (!axisOverlap(box0.directions[2], box0, box1))
  18515. return false;
  18516. if (!axisOverlap(box1.directions[0], box0, box1))
  18517. return false;
  18518. if (!axisOverlap(box1.directions[1], box0, box1))
  18519. return false;
  18520. if (!axisOverlap(box1.directions[2], box0, box1))
  18521. return false;
  18522. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18523. return false;
  18524. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18525. return false;
  18526. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18527. return false;
  18528. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18529. return false;
  18530. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18531. return false;
  18532. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18533. return false;
  18534. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18535. return false;
  18536. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18537. return false;
  18538. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18539. return false;
  18540. return true;
  18541. };
  18542. return BoundingInfo;
  18543. }());
  18544. BABYLON.BoundingInfo = BoundingInfo;
  18545. })(BABYLON || (BABYLON = {}));
  18546. //# sourceMappingURL=babylon.boundingInfo.js.map
  18547. var BABYLON;
  18548. (function (BABYLON) {
  18549. var TransformNode = /** @class */ (function (_super) {
  18550. __extends(TransformNode, _super);
  18551. function TransformNode(name, scene, isPure) {
  18552. if (scene === void 0) { scene = null; }
  18553. if (isPure === void 0) { isPure = true; }
  18554. var _this = _super.call(this, name, scene) || this;
  18555. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18556. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18557. _this._up = new BABYLON.Vector3(0, 1, 0);
  18558. _this._right = new BABYLON.Vector3(1, 0, 0);
  18559. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18560. // Properties
  18561. _this._rotation = BABYLON.Vector3.Zero();
  18562. _this._scaling = BABYLON.Vector3.One();
  18563. _this._isDirty = false;
  18564. /**
  18565. * Set the billboard mode. Default is 0.
  18566. *
  18567. * | Value | Type | Description |
  18568. * | --- | --- | --- |
  18569. * | 0 | BILLBOARDMODE_NONE | |
  18570. * | 1 | BILLBOARDMODE_X | |
  18571. * | 2 | BILLBOARDMODE_Y | |
  18572. * | 4 | BILLBOARDMODE_Z | |
  18573. * | 7 | BILLBOARDMODE_ALL | |
  18574. *
  18575. */
  18576. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18577. _this.scalingDeterminant = 1;
  18578. _this.infiniteDistance = false;
  18579. /**
  18580. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18581. * By default the system will update normals to compensate
  18582. */
  18583. _this.ignoreNonUniformScaling = false;
  18584. _this.position = BABYLON.Vector3.Zero();
  18585. _this._localWorld = BABYLON.Matrix.Zero();
  18586. _this._worldMatrix = BABYLON.Matrix.Zero();
  18587. _this._worldMatrixDeterminant = 0;
  18588. _this._absolutePosition = BABYLON.Vector3.Zero();
  18589. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18590. _this._postMultiplyPivotMatrix = false;
  18591. _this._isWorldMatrixFrozen = false;
  18592. /**
  18593. * An event triggered after the world matrix is updated
  18594. */
  18595. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18596. _this._nonUniformScaling = false;
  18597. if (isPure) {
  18598. _this.getScene().addTransformNode(_this);
  18599. }
  18600. return _this;
  18601. }
  18602. /**
  18603. * Gets a string idenfifying the name of the class
  18604. * @returns "TransformNode" string
  18605. */
  18606. TransformNode.prototype.getClassName = function () {
  18607. return "TransformNode";
  18608. };
  18609. Object.defineProperty(TransformNode.prototype, "rotation", {
  18610. /**
  18611. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18612. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18613. * Default : (0.0, 0.0, 0.0)
  18614. */
  18615. get: function () {
  18616. return this._rotation;
  18617. },
  18618. set: function (newRotation) {
  18619. this._rotation = newRotation;
  18620. },
  18621. enumerable: true,
  18622. configurable: true
  18623. });
  18624. Object.defineProperty(TransformNode.prototype, "scaling", {
  18625. /**
  18626. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18627. * Default : (1.0, 1.0, 1.0)
  18628. */
  18629. get: function () {
  18630. return this._scaling;
  18631. },
  18632. /**
  18633. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18634. * Default : (1.0, 1.0, 1.0)
  18635. */
  18636. set: function (newScaling) {
  18637. this._scaling = newScaling;
  18638. },
  18639. enumerable: true,
  18640. configurable: true
  18641. });
  18642. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18643. /**
  18644. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18645. * It's null by default.
  18646. * 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)
  18647. */
  18648. get: function () {
  18649. return this._rotationQuaternion;
  18650. },
  18651. set: function (quaternion) {
  18652. this._rotationQuaternion = quaternion;
  18653. //reset the rotation vector.
  18654. if (quaternion && this.rotation.length()) {
  18655. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18656. }
  18657. },
  18658. enumerable: true,
  18659. configurable: true
  18660. });
  18661. Object.defineProperty(TransformNode.prototype, "forward", {
  18662. /**
  18663. * The forward direction of that transform in world space.
  18664. */
  18665. get: function () {
  18666. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18667. },
  18668. enumerable: true,
  18669. configurable: true
  18670. });
  18671. Object.defineProperty(TransformNode.prototype, "up", {
  18672. /**
  18673. * The up direction of that transform in world space.
  18674. */
  18675. get: function () {
  18676. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18677. },
  18678. enumerable: true,
  18679. configurable: true
  18680. });
  18681. Object.defineProperty(TransformNode.prototype, "right", {
  18682. /**
  18683. * The right direction of that transform in world space.
  18684. */
  18685. get: function () {
  18686. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18687. },
  18688. enumerable: true,
  18689. configurable: true
  18690. });
  18691. /**
  18692. * Returns the latest update of the World matrix
  18693. * Returns a Matrix.
  18694. */
  18695. TransformNode.prototype.getWorldMatrix = function () {
  18696. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18697. this.computeWorldMatrix();
  18698. }
  18699. return this._worldMatrix;
  18700. };
  18701. /** @hidden */
  18702. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18703. return this._worldMatrixDeterminant;
  18704. };
  18705. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18706. /**
  18707. * Returns directly the latest state of the mesh World matrix.
  18708. * A Matrix is returned.
  18709. */
  18710. get: function () {
  18711. return this._worldMatrix;
  18712. },
  18713. enumerable: true,
  18714. configurable: true
  18715. });
  18716. /**
  18717. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18718. * Returns the TransformNode.
  18719. */
  18720. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18721. this._poseMatrix.copyFrom(matrix);
  18722. return this;
  18723. };
  18724. /**
  18725. * Returns the mesh Pose matrix.
  18726. * Returned object : Matrix
  18727. */
  18728. TransformNode.prototype.getPoseMatrix = function () {
  18729. return this._poseMatrix;
  18730. };
  18731. TransformNode.prototype._isSynchronized = function () {
  18732. if (this._isDirty) {
  18733. return false;
  18734. }
  18735. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18736. return false;
  18737. if (this._cache.pivotMatrixUpdated) {
  18738. return false;
  18739. }
  18740. if (this.infiniteDistance) {
  18741. return false;
  18742. }
  18743. if (!this._cache.position.equals(this.position))
  18744. return false;
  18745. if (this.rotationQuaternion) {
  18746. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18747. return false;
  18748. }
  18749. if (!this._cache.rotation.equals(this.rotation))
  18750. return false;
  18751. if (!this._cache.scaling.equals(this.scaling))
  18752. return false;
  18753. return true;
  18754. };
  18755. TransformNode.prototype._initCache = function () {
  18756. _super.prototype._initCache.call(this);
  18757. this._cache.localMatrixUpdated = false;
  18758. this._cache.position = BABYLON.Vector3.Zero();
  18759. this._cache.scaling = BABYLON.Vector3.Zero();
  18760. this._cache.rotation = BABYLON.Vector3.Zero();
  18761. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18762. this._cache.billboardMode = -1;
  18763. };
  18764. TransformNode.prototype.markAsDirty = function (property) {
  18765. if (property === "rotation") {
  18766. this.rotationQuaternion = null;
  18767. }
  18768. this._currentRenderId = Number.MAX_VALUE;
  18769. this._isDirty = true;
  18770. return this;
  18771. };
  18772. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18773. /**
  18774. * Returns the current mesh absolute position.
  18775. * Retuns a Vector3.
  18776. */
  18777. get: function () {
  18778. return this._absolutePosition;
  18779. },
  18780. enumerable: true,
  18781. configurable: true
  18782. });
  18783. /**
  18784. * Sets a new matrix to apply before all other transformation
  18785. * @param matrix defines the transform matrix
  18786. * @returns the current TransformNode
  18787. */
  18788. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18789. return this.setPivotMatrix(matrix, false);
  18790. };
  18791. /**
  18792. * Sets a new pivot matrix to the current node
  18793. * @param matrix defines the new pivot matrix to use
  18794. * @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
  18795. * @returns the current TransformNode
  18796. */
  18797. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18798. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18799. this._pivotMatrix = matrix.clone();
  18800. this._cache.pivotMatrixUpdated = true;
  18801. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18802. if (this._postMultiplyPivotMatrix) {
  18803. if (!this._pivotMatrixInverse) {
  18804. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18805. }
  18806. else {
  18807. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18808. }
  18809. }
  18810. return this;
  18811. };
  18812. /**
  18813. * Returns the mesh pivot matrix.
  18814. * Default : Identity.
  18815. * A Matrix is returned.
  18816. */
  18817. TransformNode.prototype.getPivotMatrix = function () {
  18818. return this._pivotMatrix;
  18819. };
  18820. /**
  18821. * Prevents the World matrix to be computed any longer.
  18822. * Returns the TransformNode.
  18823. */
  18824. TransformNode.prototype.freezeWorldMatrix = function () {
  18825. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18826. this.computeWorldMatrix(true);
  18827. this._isWorldMatrixFrozen = true;
  18828. return this;
  18829. };
  18830. /**
  18831. * Allows back the World matrix computation.
  18832. * Returns the TransformNode.
  18833. */
  18834. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18835. this._isWorldMatrixFrozen = false;
  18836. this.computeWorldMatrix(true);
  18837. return this;
  18838. };
  18839. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18840. /**
  18841. * True if the World matrix has been frozen.
  18842. * Returns a boolean.
  18843. */
  18844. get: function () {
  18845. return this._isWorldMatrixFrozen;
  18846. },
  18847. enumerable: true,
  18848. configurable: true
  18849. });
  18850. /**
  18851. * Retuns the mesh absolute position in the World.
  18852. * Returns a Vector3.
  18853. */
  18854. TransformNode.prototype.getAbsolutePosition = function () {
  18855. this.computeWorldMatrix();
  18856. return this._absolutePosition;
  18857. };
  18858. /**
  18859. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18860. * Returns the TransformNode.
  18861. */
  18862. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18863. if (!absolutePosition) {
  18864. return this;
  18865. }
  18866. var absolutePositionX;
  18867. var absolutePositionY;
  18868. var absolutePositionZ;
  18869. if (absolutePosition.x === undefined) {
  18870. if (arguments.length < 3) {
  18871. return this;
  18872. }
  18873. absolutePositionX = arguments[0];
  18874. absolutePositionY = arguments[1];
  18875. absolutePositionZ = arguments[2];
  18876. }
  18877. else {
  18878. absolutePositionX = absolutePosition.x;
  18879. absolutePositionY = absolutePosition.y;
  18880. absolutePositionZ = absolutePosition.z;
  18881. }
  18882. if (this.parent) {
  18883. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18884. invertParentWorldMatrix.invert();
  18885. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18886. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18887. }
  18888. else {
  18889. this.position.x = absolutePositionX;
  18890. this.position.y = absolutePositionY;
  18891. this.position.z = absolutePositionZ;
  18892. }
  18893. return this;
  18894. };
  18895. /**
  18896. * Sets the mesh position in its local space.
  18897. * Returns the TransformNode.
  18898. */
  18899. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18900. this.computeWorldMatrix();
  18901. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18902. return this;
  18903. };
  18904. /**
  18905. * Returns the mesh position in the local space from the current World matrix values.
  18906. * Returns a new Vector3.
  18907. */
  18908. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18909. this.computeWorldMatrix();
  18910. var invLocalWorldMatrix = this._localWorld.clone();
  18911. invLocalWorldMatrix.invert();
  18912. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18913. };
  18914. /**
  18915. * Translates the mesh along the passed Vector3 in its local space.
  18916. * Returns the TransformNode.
  18917. */
  18918. TransformNode.prototype.locallyTranslate = function (vector3) {
  18919. this.computeWorldMatrix(true);
  18920. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18921. return this;
  18922. };
  18923. /**
  18924. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18925. * @param targetPoint the position (must be in same space as current mesh) to look at
  18926. * @param yawCor optional yaw (y-axis) correction in radians
  18927. * @param pitchCor optional pitch (x-axis) correction in radians
  18928. * @param rollCor optional roll (z-axis) correction in radians
  18929. * @param space the choosen space of the target
  18930. * @returns the TransformNode.
  18931. */
  18932. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18933. if (yawCor === void 0) { yawCor = 0; }
  18934. if (pitchCor === void 0) { pitchCor = 0; }
  18935. if (rollCor === void 0) { rollCor = 0; }
  18936. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18937. var dv = TransformNode._lookAtVectorCache;
  18938. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18939. targetPoint.subtractToRef(pos, dv);
  18940. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18941. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18942. var pitch = Math.atan2(dv.y, len);
  18943. if (this.rotationQuaternion) {
  18944. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18945. }
  18946. else {
  18947. this.rotation.x = pitch + pitchCor;
  18948. this.rotation.y = yaw + yawCor;
  18949. this.rotation.z = rollCor;
  18950. }
  18951. return this;
  18952. };
  18953. /**
  18954. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18955. * This Vector3 is expressed in the World space.
  18956. */
  18957. TransformNode.prototype.getDirection = function (localAxis) {
  18958. var result = BABYLON.Vector3.Zero();
  18959. this.getDirectionToRef(localAxis, result);
  18960. return result;
  18961. };
  18962. /**
  18963. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18964. * localAxis is expressed in the mesh local space.
  18965. * result is computed in the Wordl space from the mesh World matrix.
  18966. * Returns the TransformNode.
  18967. */
  18968. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18969. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18970. return this;
  18971. };
  18972. /**
  18973. * Sets a new pivot point to the current node
  18974. * @param point defines the new pivot point to use
  18975. * @param space defines if the point is in world or local space (local by default)
  18976. * @returns the current TransformNode
  18977. */
  18978. TransformNode.prototype.setPivotPoint = function (point, space) {
  18979. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18980. if (this.getScene().getRenderId() == 0) {
  18981. this.computeWorldMatrix(true);
  18982. }
  18983. var wm = this.getWorldMatrix();
  18984. if (space == BABYLON.Space.WORLD) {
  18985. var tmat = BABYLON.Tmp.Matrix[0];
  18986. wm.invertToRef(tmat);
  18987. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18988. }
  18989. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18990. };
  18991. /**
  18992. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18993. */
  18994. TransformNode.prototype.getPivotPoint = function () {
  18995. var point = BABYLON.Vector3.Zero();
  18996. this.getPivotPointToRef(point);
  18997. return point;
  18998. };
  18999. /**
  19000. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19001. * Returns the TransformNode.
  19002. */
  19003. TransformNode.prototype.getPivotPointToRef = function (result) {
  19004. result.x = -this._pivotMatrix.m[12];
  19005. result.y = -this._pivotMatrix.m[13];
  19006. result.z = -this._pivotMatrix.m[14];
  19007. return this;
  19008. };
  19009. /**
  19010. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19011. */
  19012. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19013. var point = BABYLON.Vector3.Zero();
  19014. this.getAbsolutePivotPointToRef(point);
  19015. return point;
  19016. };
  19017. /**
  19018. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19019. * Returns the TransformNode.
  19020. */
  19021. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19022. result.x = this._pivotMatrix.m[12];
  19023. result.y = this._pivotMatrix.m[13];
  19024. result.z = this._pivotMatrix.m[14];
  19025. this.getPivotPointToRef(result);
  19026. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19027. return this;
  19028. };
  19029. /**
  19030. * Defines the passed node as the parent of the current node.
  19031. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19032. * Returns the TransformNode.
  19033. */
  19034. TransformNode.prototype.setParent = function (node) {
  19035. if (node === null) {
  19036. var rotation = BABYLON.Tmp.Quaternion[0];
  19037. var position = BABYLON.Tmp.Vector3[0];
  19038. var scale = BABYLON.Tmp.Vector3[1];
  19039. if (this.parent && this.parent.computeWorldMatrix) {
  19040. this.parent.computeWorldMatrix(true);
  19041. }
  19042. this.computeWorldMatrix(true);
  19043. this.getWorldMatrix().decompose(scale, rotation, position);
  19044. if (this.rotationQuaternion) {
  19045. this.rotationQuaternion.copyFrom(rotation);
  19046. }
  19047. else {
  19048. rotation.toEulerAnglesToRef(this.rotation);
  19049. }
  19050. this.scaling.x = scale.x;
  19051. this.scaling.y = scale.y;
  19052. this.scaling.z = scale.z;
  19053. this.position.x = position.x;
  19054. this.position.y = position.y;
  19055. this.position.z = position.z;
  19056. }
  19057. else {
  19058. var rotation = BABYLON.Tmp.Quaternion[0];
  19059. var position = BABYLON.Tmp.Vector3[0];
  19060. var scale = BABYLON.Tmp.Vector3[1];
  19061. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19062. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19063. this.computeWorldMatrix(true);
  19064. node.computeWorldMatrix(true);
  19065. node.getWorldMatrix().invertToRef(invParentMatrix);
  19066. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19067. diffMatrix.decompose(scale, rotation, position);
  19068. if (this.rotationQuaternion) {
  19069. this.rotationQuaternion.copyFrom(rotation);
  19070. }
  19071. else {
  19072. rotation.toEulerAnglesToRef(this.rotation);
  19073. }
  19074. this.position.x = position.x;
  19075. this.position.y = position.y;
  19076. this.position.z = position.z;
  19077. this.scaling.x = scale.x;
  19078. this.scaling.y = scale.y;
  19079. this.scaling.z = scale.z;
  19080. }
  19081. this.parent = node;
  19082. return this;
  19083. };
  19084. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19085. get: function () {
  19086. return this._nonUniformScaling;
  19087. },
  19088. enumerable: true,
  19089. configurable: true
  19090. });
  19091. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19092. if (this._nonUniformScaling === value) {
  19093. return false;
  19094. }
  19095. this._nonUniformScaling = value;
  19096. return true;
  19097. };
  19098. /**
  19099. * Attach the current TransformNode to another TransformNode associated with a bone
  19100. * @param bone Bone affecting the TransformNode
  19101. * @param affectedTransformNode TransformNode associated with the bone
  19102. */
  19103. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19104. this._transformToBoneReferal = affectedTransformNode;
  19105. this.parent = bone;
  19106. if (bone.getWorldMatrix().determinant() < 0) {
  19107. this.scalingDeterminant *= -1;
  19108. }
  19109. return this;
  19110. };
  19111. TransformNode.prototype.detachFromBone = function () {
  19112. if (!this.parent) {
  19113. return this;
  19114. }
  19115. if (this.parent.getWorldMatrix().determinant() < 0) {
  19116. this.scalingDeterminant *= -1;
  19117. }
  19118. this._transformToBoneReferal = null;
  19119. this.parent = null;
  19120. return this;
  19121. };
  19122. /**
  19123. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19124. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19125. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19126. * The passed axis is also normalized.
  19127. * Returns the TransformNode.
  19128. */
  19129. TransformNode.prototype.rotate = function (axis, amount, space) {
  19130. axis.normalize();
  19131. if (!this.rotationQuaternion) {
  19132. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19133. this.rotation = BABYLON.Vector3.Zero();
  19134. }
  19135. var rotationQuaternion;
  19136. if (!space || space === BABYLON.Space.LOCAL) {
  19137. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19138. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19139. }
  19140. else {
  19141. if (this.parent) {
  19142. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19143. invertParentWorldMatrix.invert();
  19144. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19145. }
  19146. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19147. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19148. }
  19149. return this;
  19150. };
  19151. /**
  19152. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19153. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19154. * The passed axis is also normalized.
  19155. * Returns the TransformNode.
  19156. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19157. */
  19158. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19159. axis.normalize();
  19160. if (!this.rotationQuaternion) {
  19161. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19162. this.rotation.copyFromFloats(0, 0, 0);
  19163. }
  19164. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19165. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19166. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19167. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19168. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19169. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19170. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19171. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19172. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19173. return this;
  19174. };
  19175. /**
  19176. * Translates the mesh along the axis vector for the passed distance in the given space.
  19177. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19178. * Returns the TransformNode.
  19179. */
  19180. TransformNode.prototype.translate = function (axis, distance, space) {
  19181. var displacementVector = axis.scale(distance);
  19182. if (!space || space === BABYLON.Space.LOCAL) {
  19183. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19184. this.setPositionWithLocalVector(tempV3);
  19185. }
  19186. else {
  19187. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19188. }
  19189. return this;
  19190. };
  19191. /**
  19192. * Adds a rotation step to the mesh current rotation.
  19193. * x, y, z are Euler angles expressed in radians.
  19194. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19195. * This means this rotation is made in the mesh local space only.
  19196. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19197. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19198. * ```javascript
  19199. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19200. * ```
  19201. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19202. * 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.
  19203. * Returns the TransformNode.
  19204. */
  19205. TransformNode.prototype.addRotation = function (x, y, z) {
  19206. var rotationQuaternion;
  19207. if (this.rotationQuaternion) {
  19208. rotationQuaternion = this.rotationQuaternion;
  19209. }
  19210. else {
  19211. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19212. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19213. }
  19214. var accumulation = BABYLON.Tmp.Quaternion[0];
  19215. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19216. rotationQuaternion.multiplyInPlace(accumulation);
  19217. if (!this.rotationQuaternion) {
  19218. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19219. }
  19220. return this;
  19221. };
  19222. /**
  19223. * Computes the mesh World matrix and returns it.
  19224. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19225. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19226. * If the parameter `force`is set to `true`, the actual computation is done.
  19227. * Returns the mesh World Matrix.
  19228. */
  19229. TransformNode.prototype.computeWorldMatrix = function (force) {
  19230. if (this._isWorldMatrixFrozen) {
  19231. return this._worldMatrix;
  19232. }
  19233. if (!force && this.isSynchronized(true)) {
  19234. this._currentRenderId = this.getScene().getRenderId();
  19235. return this._worldMatrix;
  19236. }
  19237. this._cache.position.copyFrom(this.position);
  19238. this._cache.scaling.copyFrom(this.scaling);
  19239. this._cache.pivotMatrixUpdated = false;
  19240. this._cache.billboardMode = this.billboardMode;
  19241. this._currentRenderId = this.getScene().getRenderId();
  19242. this._childRenderId = this.getScene().getRenderId();
  19243. this._isDirty = false;
  19244. // Scaling
  19245. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19246. // Rotation
  19247. //rotate, if quaternion is set and rotation was used
  19248. if (this.rotationQuaternion) {
  19249. var len = this.rotation.length();
  19250. if (len) {
  19251. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19252. this.rotation.copyFromFloats(0, 0, 0);
  19253. }
  19254. }
  19255. if (this.rotationQuaternion) {
  19256. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19257. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19258. }
  19259. else {
  19260. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19261. this._cache.rotation.copyFrom(this.rotation);
  19262. }
  19263. // Translation
  19264. var camera = this.getScene().activeCamera;
  19265. if (this.infiniteDistance && !this.parent && camera) {
  19266. var cameraWorldMatrix = camera.getWorldMatrix();
  19267. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19268. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19269. }
  19270. else {
  19271. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19272. }
  19273. // Composing transformations
  19274. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19275. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19276. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19277. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19278. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19279. // Need to decompose each rotation here
  19280. var currentPosition = BABYLON.Tmp.Vector3[3];
  19281. if (this.parent && this.parent.getWorldMatrix) {
  19282. if (this._transformToBoneReferal) {
  19283. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19284. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19285. }
  19286. else {
  19287. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19288. }
  19289. }
  19290. else {
  19291. currentPosition.copyFrom(this.position);
  19292. }
  19293. currentPosition.subtractInPlace(camera.globalPosition);
  19294. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19295. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19296. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19297. }
  19298. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19299. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19300. }
  19301. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19302. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19303. }
  19304. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19305. }
  19306. else {
  19307. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19308. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19309. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19310. }
  19311. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19312. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19313. }
  19314. // Local world
  19315. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19316. // Parent
  19317. if (this.parent && this.parent.getWorldMatrix) {
  19318. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19319. if (this._transformToBoneReferal) {
  19320. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19321. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19322. }
  19323. else {
  19324. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19325. }
  19326. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19327. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19328. this._worldMatrix.copyFrom(this._localWorld);
  19329. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19330. }
  19331. else {
  19332. if (this._transformToBoneReferal) {
  19333. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19334. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19335. }
  19336. else {
  19337. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19338. }
  19339. }
  19340. this._markSyncedWithParent();
  19341. }
  19342. else {
  19343. this._worldMatrix.copyFrom(this._localWorld);
  19344. }
  19345. // Post multiply inverse of pivotMatrix
  19346. if (this._postMultiplyPivotMatrix) {
  19347. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19348. }
  19349. // Normal matrix
  19350. if (!this.ignoreNonUniformScaling) {
  19351. if (this.scaling.isNonUniform) {
  19352. this._updateNonUniformScalingState(true);
  19353. }
  19354. else if (this.parent && this.parent._nonUniformScaling) {
  19355. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19356. }
  19357. else {
  19358. this._updateNonUniformScalingState(false);
  19359. }
  19360. }
  19361. else {
  19362. this._updateNonUniformScalingState(false);
  19363. }
  19364. this._afterComputeWorldMatrix();
  19365. // Absolute position
  19366. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19367. // Callbacks
  19368. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19369. if (!this._poseMatrix) {
  19370. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19371. }
  19372. // Cache the determinant
  19373. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19374. return this._worldMatrix;
  19375. };
  19376. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19377. };
  19378. /**
  19379. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19380. * @param func: callback function to add
  19381. *
  19382. * Returns the TransformNode.
  19383. */
  19384. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19385. this.onAfterWorldMatrixUpdateObservable.add(func);
  19386. return this;
  19387. };
  19388. /**
  19389. * Removes a registered callback function.
  19390. * Returns the TransformNode.
  19391. */
  19392. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19393. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19394. return this;
  19395. };
  19396. /**
  19397. * Clone the current transform node
  19398. * Returns the new transform node
  19399. * @param name Name of the new clone
  19400. * @param newParent New parent for the clone
  19401. * @param doNotCloneChildren Do not clone children hierarchy
  19402. */
  19403. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19404. var _this = this;
  19405. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19406. result.name = name;
  19407. result.id = name;
  19408. if (newParent) {
  19409. result.parent = newParent;
  19410. }
  19411. if (!doNotCloneChildren) {
  19412. // Children
  19413. var directDescendants = this.getDescendants(true);
  19414. for (var index = 0; index < directDescendants.length; index++) {
  19415. var child = directDescendants[index];
  19416. if (child.clone) {
  19417. child.clone(name + "." + child.name, result);
  19418. }
  19419. }
  19420. }
  19421. return result;
  19422. };
  19423. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19424. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19425. serializationObject.type = this.getClassName();
  19426. // Parent
  19427. if (this.parent) {
  19428. serializationObject.parentId = this.parent.id;
  19429. }
  19430. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19431. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19432. }
  19433. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19434. serializationObject.isEnabled = this.isEnabled();
  19435. // Parent
  19436. if (this.parent) {
  19437. serializationObject.parentId = this.parent.id;
  19438. }
  19439. return serializationObject;
  19440. };
  19441. // Statics
  19442. /**
  19443. * Returns a new TransformNode object parsed from the source provided.
  19444. * The parameter `parsedMesh` is the source.
  19445. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19446. */
  19447. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19448. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19449. if (BABYLON.Tags) {
  19450. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19451. }
  19452. if (parsedTransformNode.localMatrix) {
  19453. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19454. }
  19455. else if (parsedTransformNode.pivotMatrix) {
  19456. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19457. }
  19458. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19459. // Parent
  19460. if (parsedTransformNode.parentId) {
  19461. transformNode._waitingParentId = parsedTransformNode.parentId;
  19462. }
  19463. return transformNode;
  19464. };
  19465. /**
  19466. * Releases resources associated with this transform node.
  19467. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19468. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19469. */
  19470. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19471. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19472. // Animations
  19473. this.getScene().stopAnimation(this);
  19474. // Remove from scene
  19475. this.getScene().removeTransformNode(this);
  19476. this.onAfterWorldMatrixUpdateObservable.clear();
  19477. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19478. };
  19479. // Statics
  19480. TransformNode.BILLBOARDMODE_NONE = 0;
  19481. TransformNode.BILLBOARDMODE_X = 1;
  19482. TransformNode.BILLBOARDMODE_Y = 2;
  19483. TransformNode.BILLBOARDMODE_Z = 4;
  19484. TransformNode.BILLBOARDMODE_ALL = 7;
  19485. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19486. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19487. __decorate([
  19488. BABYLON.serializeAsVector3()
  19489. ], TransformNode.prototype, "_rotation", void 0);
  19490. __decorate([
  19491. BABYLON.serializeAsQuaternion()
  19492. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19493. __decorate([
  19494. BABYLON.serializeAsVector3()
  19495. ], TransformNode.prototype, "_scaling", void 0);
  19496. __decorate([
  19497. BABYLON.serialize()
  19498. ], TransformNode.prototype, "billboardMode", void 0);
  19499. __decorate([
  19500. BABYLON.serialize()
  19501. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19502. __decorate([
  19503. BABYLON.serialize()
  19504. ], TransformNode.prototype, "infiniteDistance", void 0);
  19505. __decorate([
  19506. BABYLON.serialize()
  19507. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19508. __decorate([
  19509. BABYLON.serializeAsVector3()
  19510. ], TransformNode.prototype, "position", void 0);
  19511. return TransformNode;
  19512. }(BABYLON.Node));
  19513. BABYLON.TransformNode = TransformNode;
  19514. })(BABYLON || (BABYLON = {}));
  19515. //# sourceMappingURL=babylon.transformNode.js.map
  19516. var BABYLON;
  19517. (function (BABYLON) {
  19518. /**
  19519. * Class used to store all common mesh properties
  19520. */
  19521. var AbstractMesh = /** @class */ (function (_super) {
  19522. __extends(AbstractMesh, _super);
  19523. // Constructor
  19524. /**
  19525. * Creates a new AbstractMesh
  19526. * @param name defines the name of the mesh
  19527. * @param scene defines the hosting scene
  19528. */
  19529. function AbstractMesh(name, scene) {
  19530. if (scene === void 0) { scene = null; }
  19531. var _this = _super.call(this, name, scene, false) || this;
  19532. _this._facetNb = 0; // facet number
  19533. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19534. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19535. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19536. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19537. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19538. _this._subDiv = {
  19539. max: 1,
  19540. X: 1,
  19541. Y: 1,
  19542. Z: 1
  19543. };
  19544. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19545. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19546. // Events
  19547. /**
  19548. * An event triggered when this mesh collides with another one
  19549. */
  19550. _this.onCollideObservable = new BABYLON.Observable();
  19551. /**
  19552. * An event triggered when the collision's position changes
  19553. */
  19554. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19555. /**
  19556. * An event triggered when material is changed
  19557. */
  19558. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19559. // Properties
  19560. /**
  19561. * Gets or sets the orientation for POV movement & rotation
  19562. */
  19563. _this.definedFacingForward = true;
  19564. /**
  19565. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19566. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19567. * * 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.
  19568. * @see http://doc.babylonjs.com/features/occlusionquery
  19569. */
  19570. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19571. /**
  19572. * 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:
  19573. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19574. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19575. * * 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.
  19576. * @see http://doc.babylonjs.com/features/occlusionquery
  19577. */
  19578. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19579. /**
  19580. * 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.
  19581. * The default value is -1 which means don't break the query and wait till the result
  19582. * @see http://doc.babylonjs.com/features/occlusionquery
  19583. */
  19584. _this.occlusionRetryCount = -1;
  19585. _this._occlusionInternalRetryCounter = 0;
  19586. _this._isOccluded = false;
  19587. _this._isOcclusionQueryInProgress = false;
  19588. _this._visibility = 1.0;
  19589. /** Gets or sets the alpha index used to sort transparent meshes
  19590. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19591. */
  19592. _this.alphaIndex = Number.MAX_VALUE;
  19593. /**
  19594. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19595. */
  19596. _this.isVisible = true;
  19597. /**
  19598. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19599. */
  19600. _this.isPickable = true;
  19601. /**
  19602. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19603. */
  19604. _this.showBoundingBox = false;
  19605. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19606. _this.showSubMeshesBoundingBox = false;
  19607. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19608. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19609. */
  19610. _this.isBlocker = false;
  19611. /**
  19612. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19613. */
  19614. _this.enablePointerMoveEvents = false;
  19615. /**
  19616. * Specifies the rendering group id for this mesh (0 by default)
  19617. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19618. */
  19619. _this.renderingGroupId = 0;
  19620. _this._receiveShadows = false;
  19621. /**
  19622. * Gets or sets a boolean indicating if the outline must be rendered as well
  19623. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19624. */
  19625. _this.renderOutline = false;
  19626. /** Defines color to use when rendering outline */
  19627. _this.outlineColor = BABYLON.Color3.Red();
  19628. /** Define width to use when rendering outline */
  19629. _this.outlineWidth = 0.02;
  19630. /**
  19631. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19632. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19633. */
  19634. _this.renderOverlay = false;
  19635. /** Defines color to use when rendering overlay */
  19636. _this.overlayColor = BABYLON.Color3.Red();
  19637. /** Defines alpha to use when rendering overlay */
  19638. _this.overlayAlpha = 0.5;
  19639. _this._hasVertexAlpha = false;
  19640. _this._useVertexColors = true;
  19641. _this._computeBonesUsingShaders = true;
  19642. _this._numBoneInfluencers = 4;
  19643. _this._applyFog = true;
  19644. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19645. _this.useOctreeForRenderingSelection = true;
  19646. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19647. _this.useOctreeForPicking = true;
  19648. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19649. _this.useOctreeForCollisions = true;
  19650. _this._layerMask = 0x0FFFFFFF;
  19651. /**
  19652. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19653. */
  19654. _this.alwaysSelectAsActiveMesh = false;
  19655. /**
  19656. * Gets or sets the current action manager
  19657. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19658. */
  19659. _this.actionManager = null;
  19660. /**
  19661. * Gets or sets impostor used for physic simulation
  19662. * @see http://doc.babylonjs.com/features/physics_engine
  19663. */
  19664. _this.physicsImpostor = null;
  19665. // Collisions
  19666. _this._checkCollisions = false;
  19667. _this._collisionMask = -1;
  19668. _this._collisionGroup = -1;
  19669. /**
  19670. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19671. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19672. */
  19673. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19674. /**
  19675. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19676. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19677. */
  19678. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19679. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19680. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19681. // Edges
  19682. /**
  19683. * Defines edge width used when edgesRenderer is enabled
  19684. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19685. */
  19686. _this.edgesWidth = 1;
  19687. /**
  19688. * Defines edge color used when edgesRenderer is enabled
  19689. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19690. */
  19691. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19692. // Cache
  19693. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19694. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19695. /** @hidden */
  19696. _this._renderId = 0;
  19697. /** @hidden */
  19698. _this._intersectionsInProgress = new Array();
  19699. /** @hidden */
  19700. _this._unIndexed = false;
  19701. /** @hidden */
  19702. _this._lightSources = new Array();
  19703. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19704. if (collidedMesh === void 0) { collidedMesh = null; }
  19705. //TODO move this to the collision coordinator!
  19706. if (_this.getScene().workerCollisions)
  19707. newPosition.multiplyInPlace(_this._collider._radius);
  19708. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19709. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19710. _this.position.addInPlace(_this._diffPositionForCollisions);
  19711. }
  19712. if (collidedMesh) {
  19713. _this.onCollideObservable.notifyObservers(collidedMesh);
  19714. }
  19715. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19716. };
  19717. _this.getScene().addMesh(_this);
  19718. _this._resyncLightSources();
  19719. return _this;
  19720. }
  19721. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19722. /**
  19723. * No billboard
  19724. */
  19725. get: function () {
  19726. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19727. },
  19728. enumerable: true,
  19729. configurable: true
  19730. });
  19731. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19732. /** Billboard on X axis */
  19733. get: function () {
  19734. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19735. },
  19736. enumerable: true,
  19737. configurable: true
  19738. });
  19739. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19740. /** Billboard on Y axis */
  19741. get: function () {
  19742. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19743. },
  19744. enumerable: true,
  19745. configurable: true
  19746. });
  19747. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19748. /** Billboard on Z axis */
  19749. get: function () {
  19750. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19751. },
  19752. enumerable: true,
  19753. configurable: true
  19754. });
  19755. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19756. /** Billboard on all axes */
  19757. get: function () {
  19758. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19759. },
  19760. enumerable: true,
  19761. configurable: true
  19762. });
  19763. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19764. /**
  19765. * Gets the number of facets in the mesh
  19766. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19767. */
  19768. get: function () {
  19769. return this._facetNb;
  19770. },
  19771. enumerable: true,
  19772. configurable: true
  19773. });
  19774. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19775. /**
  19776. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19777. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19778. */
  19779. get: function () {
  19780. return this._partitioningSubdivisions;
  19781. },
  19782. set: function (nb) {
  19783. this._partitioningSubdivisions = nb;
  19784. },
  19785. enumerable: true,
  19786. configurable: true
  19787. });
  19788. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19789. /**
  19790. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19791. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19792. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19793. */
  19794. get: function () {
  19795. return this._partitioningBBoxRatio;
  19796. },
  19797. set: function (ratio) {
  19798. this._partitioningBBoxRatio = ratio;
  19799. },
  19800. enumerable: true,
  19801. configurable: true
  19802. });
  19803. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19804. /**
  19805. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19806. * Works only for updatable meshes.
  19807. * Doesn't work with multi-materials
  19808. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19809. */
  19810. get: function () {
  19811. return this._facetDepthSort;
  19812. },
  19813. set: function (sort) {
  19814. this._facetDepthSort = sort;
  19815. },
  19816. enumerable: true,
  19817. configurable: true
  19818. });
  19819. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19820. /**
  19821. * The location (Vector3) where the facet depth sort must be computed from.
  19822. * By default, the active camera position.
  19823. * Used only when facet depth sort is enabled
  19824. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19825. */
  19826. get: function () {
  19827. return this._facetDepthSortFrom;
  19828. },
  19829. set: function (location) {
  19830. this._facetDepthSortFrom = location;
  19831. },
  19832. enumerable: true,
  19833. configurable: true
  19834. });
  19835. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19836. /**
  19837. * gets a boolean indicating if facetData is enabled
  19838. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19839. */
  19840. get: function () {
  19841. return this._facetDataEnabled;
  19842. },
  19843. enumerable: true,
  19844. configurable: true
  19845. });
  19846. /** @hidden */
  19847. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19848. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19849. return false;
  19850. }
  19851. this._markSubMeshesAsMiscDirty();
  19852. return true;
  19853. };
  19854. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19855. /** Set a function to call when this mesh collides with another one */
  19856. set: function (callback) {
  19857. if (this._onCollideObserver) {
  19858. this.onCollideObservable.remove(this._onCollideObserver);
  19859. }
  19860. this._onCollideObserver = this.onCollideObservable.add(callback);
  19861. },
  19862. enumerable: true,
  19863. configurable: true
  19864. });
  19865. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19866. /** Set a function to call when the collision's position changes */
  19867. set: function (callback) {
  19868. if (this._onCollisionPositionChangeObserver) {
  19869. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19870. }
  19871. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19872. },
  19873. enumerable: true,
  19874. configurable: true
  19875. });
  19876. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19877. /**
  19878. * 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
  19879. * @see http://doc.babylonjs.com/features/occlusionquery
  19880. */
  19881. get: function () {
  19882. return this._isOccluded;
  19883. },
  19884. set: function (value) {
  19885. this._isOccluded = value;
  19886. },
  19887. enumerable: true,
  19888. configurable: true
  19889. });
  19890. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19891. /**
  19892. * Flag to check the progress status of the query
  19893. * @see http://doc.babylonjs.com/features/occlusionquery
  19894. */
  19895. get: function () {
  19896. return this._isOcclusionQueryInProgress;
  19897. },
  19898. enumerable: true,
  19899. configurable: true
  19900. });
  19901. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19902. /**
  19903. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19904. */
  19905. get: function () {
  19906. return this._visibility;
  19907. },
  19908. /**
  19909. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19910. */
  19911. set: function (value) {
  19912. if (this._visibility === value) {
  19913. return;
  19914. }
  19915. this._visibility = value;
  19916. this._markSubMeshesAsMiscDirty();
  19917. },
  19918. enumerable: true,
  19919. configurable: true
  19920. });
  19921. Object.defineProperty(AbstractMesh.prototype, "material", {
  19922. /** Gets or sets current material */
  19923. get: function () {
  19924. return this._material;
  19925. },
  19926. set: function (value) {
  19927. if (this._material === value) {
  19928. return;
  19929. }
  19930. this._material = value;
  19931. if (this.onMaterialChangedObservable.hasObservers) {
  19932. this.onMaterialChangedObservable.notifyObservers(this);
  19933. }
  19934. if (!this.subMeshes) {
  19935. return;
  19936. }
  19937. this._unBindEffect();
  19938. },
  19939. enumerable: true,
  19940. configurable: true
  19941. });
  19942. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19943. /**
  19944. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19945. * @see http://doc.babylonjs.com/babylon101/shadows
  19946. */
  19947. get: function () {
  19948. return this._receiveShadows;
  19949. },
  19950. set: function (value) {
  19951. if (this._receiveShadows === value) {
  19952. return;
  19953. }
  19954. this._receiveShadows = value;
  19955. this._markSubMeshesAsLightDirty();
  19956. },
  19957. enumerable: true,
  19958. configurable: true
  19959. });
  19960. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19961. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19962. get: function () {
  19963. return this._hasVertexAlpha;
  19964. },
  19965. set: function (value) {
  19966. if (this._hasVertexAlpha === value) {
  19967. return;
  19968. }
  19969. this._hasVertexAlpha = value;
  19970. this._markSubMeshesAsAttributesDirty();
  19971. this._markSubMeshesAsMiscDirty();
  19972. },
  19973. enumerable: true,
  19974. configurable: true
  19975. });
  19976. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19977. /** 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) */
  19978. get: function () {
  19979. return this._useVertexColors;
  19980. },
  19981. set: function (value) {
  19982. if (this._useVertexColors === value) {
  19983. return;
  19984. }
  19985. this._useVertexColors = value;
  19986. this._markSubMeshesAsAttributesDirty();
  19987. },
  19988. enumerable: true,
  19989. configurable: true
  19990. });
  19991. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19992. /**
  19993. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19994. */
  19995. get: function () {
  19996. return this._computeBonesUsingShaders;
  19997. },
  19998. set: function (value) {
  19999. if (this._computeBonesUsingShaders === value) {
  20000. return;
  20001. }
  20002. this._computeBonesUsingShaders = value;
  20003. this._markSubMeshesAsAttributesDirty();
  20004. },
  20005. enumerable: true,
  20006. configurable: true
  20007. });
  20008. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20009. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20010. get: function () {
  20011. return this._numBoneInfluencers;
  20012. },
  20013. set: function (value) {
  20014. if (this._numBoneInfluencers === value) {
  20015. return;
  20016. }
  20017. this._numBoneInfluencers = value;
  20018. this._markSubMeshesAsAttributesDirty();
  20019. },
  20020. enumerable: true,
  20021. configurable: true
  20022. });
  20023. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20024. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20025. get: function () {
  20026. return this._applyFog;
  20027. },
  20028. set: function (value) {
  20029. if (this._applyFog === value) {
  20030. return;
  20031. }
  20032. this._applyFog = value;
  20033. this._markSubMeshesAsMiscDirty();
  20034. },
  20035. enumerable: true,
  20036. configurable: true
  20037. });
  20038. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20039. /**
  20040. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20041. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20042. */
  20043. get: function () {
  20044. return this._layerMask;
  20045. },
  20046. set: function (value) {
  20047. if (value === this._layerMask) {
  20048. return;
  20049. }
  20050. this._layerMask = value;
  20051. this._resyncLightSources();
  20052. },
  20053. enumerable: true,
  20054. configurable: true
  20055. });
  20056. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20057. /**
  20058. * Gets or sets a collision mask used to mask collisions (default is -1).
  20059. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20060. */
  20061. get: function () {
  20062. return this._collisionMask;
  20063. },
  20064. set: function (mask) {
  20065. this._collisionMask = !isNaN(mask) ? mask : -1;
  20066. },
  20067. enumerable: true,
  20068. configurable: true
  20069. });
  20070. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20071. /**
  20072. * Gets or sets the current collision group mask (-1 by default).
  20073. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20074. */
  20075. get: function () {
  20076. return this._collisionGroup;
  20077. },
  20078. set: function (mask) {
  20079. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20080. },
  20081. enumerable: true,
  20082. configurable: true
  20083. });
  20084. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20085. /** @hidden */
  20086. get: function () {
  20087. return null;
  20088. },
  20089. enumerable: true,
  20090. configurable: true
  20091. });
  20092. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20093. get: function () {
  20094. return this._skeleton;
  20095. },
  20096. /**
  20097. * Gets or sets a skeleton to apply skining transformations
  20098. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20099. */
  20100. set: function (value) {
  20101. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20102. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20103. }
  20104. if (value && value.needInitialSkinMatrix) {
  20105. value._registerMeshWithPoseMatrix(this);
  20106. }
  20107. this._skeleton = value;
  20108. if (!this._skeleton) {
  20109. this._bonesTransformMatrices = null;
  20110. }
  20111. this._markSubMeshesAsAttributesDirty();
  20112. },
  20113. enumerable: true,
  20114. configurable: true
  20115. });
  20116. /**
  20117. * Returns the string "AbstractMesh"
  20118. * @returns "AbstractMesh"
  20119. */
  20120. AbstractMesh.prototype.getClassName = function () {
  20121. return "AbstractMesh";
  20122. };
  20123. /**
  20124. * Gets a string representation of the current mesh
  20125. * @param fullDetails defines a boolean indicating if full details must be included
  20126. * @returns a string representation of the current mesh
  20127. */
  20128. AbstractMesh.prototype.toString = function (fullDetails) {
  20129. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20130. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20131. if (this._skeleton) {
  20132. ret += ", skeleton: " + this._skeleton.name;
  20133. }
  20134. if (fullDetails) {
  20135. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20136. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20137. }
  20138. return ret;
  20139. };
  20140. /** @hidden */
  20141. AbstractMesh.prototype._rebuild = function () {
  20142. if (this._occlusionQuery) {
  20143. this._occlusionQuery = null;
  20144. }
  20145. if (this._edgesRenderer) {
  20146. this._edgesRenderer._rebuild();
  20147. }
  20148. if (!this.subMeshes) {
  20149. return;
  20150. }
  20151. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20152. var subMesh = _a[_i];
  20153. subMesh._rebuild();
  20154. }
  20155. };
  20156. /** @hidden */
  20157. AbstractMesh.prototype._resyncLightSources = function () {
  20158. this._lightSources.length = 0;
  20159. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20160. var light = _a[_i];
  20161. if (!light.isEnabled()) {
  20162. continue;
  20163. }
  20164. if (light.canAffectMesh(this)) {
  20165. this._lightSources.push(light);
  20166. }
  20167. }
  20168. this._markSubMeshesAsLightDirty();
  20169. };
  20170. /** @hidden */
  20171. AbstractMesh.prototype._resyncLighSource = function (light) {
  20172. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20173. var index = this._lightSources.indexOf(light);
  20174. if (index === -1) {
  20175. if (!isIn) {
  20176. return;
  20177. }
  20178. this._lightSources.push(light);
  20179. }
  20180. else {
  20181. if (isIn) {
  20182. return;
  20183. }
  20184. this._lightSources.splice(index, 1);
  20185. }
  20186. this._markSubMeshesAsLightDirty();
  20187. };
  20188. /** @hidden */
  20189. AbstractMesh.prototype._unBindEffect = function () {
  20190. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20191. var subMesh = _a[_i];
  20192. subMesh.setEffect(null);
  20193. }
  20194. };
  20195. /** @hidden */
  20196. AbstractMesh.prototype._removeLightSource = function (light) {
  20197. var index = this._lightSources.indexOf(light);
  20198. if (index === -1) {
  20199. return;
  20200. }
  20201. this._lightSources.splice(index, 1);
  20202. this._markSubMeshesAsLightDirty();
  20203. };
  20204. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20205. if (!this.subMeshes) {
  20206. return;
  20207. }
  20208. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20209. var subMesh = _a[_i];
  20210. if (subMesh._materialDefines) {
  20211. func(subMesh._materialDefines);
  20212. }
  20213. }
  20214. };
  20215. /** @hidden */
  20216. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20217. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20218. };
  20219. /** @hidden */
  20220. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20221. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20222. };
  20223. /** @hidden */
  20224. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20225. if (!this.subMeshes) {
  20226. return;
  20227. }
  20228. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20229. var subMesh = _a[_i];
  20230. var material = subMesh.getMaterial();
  20231. if (material) {
  20232. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20233. }
  20234. }
  20235. };
  20236. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20237. /**
  20238. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20239. */
  20240. get: function () {
  20241. return this._scaling;
  20242. },
  20243. set: function (newScaling) {
  20244. this._scaling = newScaling;
  20245. if (this.physicsImpostor) {
  20246. this.physicsImpostor.forceUpdate();
  20247. }
  20248. },
  20249. enumerable: true,
  20250. configurable: true
  20251. });
  20252. // Methods
  20253. /**
  20254. * Disables the mesh edge rendering mode
  20255. * @returns the currentAbstractMesh
  20256. */
  20257. AbstractMesh.prototype.disableEdgesRendering = function () {
  20258. if (this._edgesRenderer) {
  20259. this._edgesRenderer.dispose();
  20260. this._edgesRenderer = null;
  20261. }
  20262. return this;
  20263. };
  20264. /**
  20265. * Enables the edge rendering mode on the mesh.
  20266. * This mode makes the mesh edges visible
  20267. * @param epsilon defines the maximal distance between two angles to detect a face
  20268. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20269. * @returns the currentAbstractMesh
  20270. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20271. */
  20272. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20273. if (epsilon === void 0) { epsilon = 0.95; }
  20274. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20275. this.disableEdgesRendering();
  20276. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20277. return this;
  20278. };
  20279. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20280. /**
  20281. * Gets the edgesRenderer associated with the mesh
  20282. */
  20283. get: function () {
  20284. return this._edgesRenderer;
  20285. },
  20286. enumerable: true,
  20287. configurable: true
  20288. });
  20289. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20290. /**
  20291. * Returns true if the mesh is blocked. Implemented by child classes
  20292. */
  20293. get: function () {
  20294. return false;
  20295. },
  20296. enumerable: true,
  20297. configurable: true
  20298. });
  20299. /**
  20300. * Returns the mesh itself by default. Implemented by child classes
  20301. * @param camera defines the camera to use to pick the right LOD level
  20302. * @returns the currentAbstractMesh
  20303. */
  20304. AbstractMesh.prototype.getLOD = function (camera) {
  20305. return this;
  20306. };
  20307. /**
  20308. * Returns 0 by default. Implemented by child classes
  20309. * @returns an integer
  20310. */
  20311. AbstractMesh.prototype.getTotalVertices = function () {
  20312. return 0;
  20313. };
  20314. /**
  20315. * Returns null by default. Implemented by child classes
  20316. * @returns null
  20317. */
  20318. AbstractMesh.prototype.getIndices = function () {
  20319. return null;
  20320. };
  20321. /**
  20322. * Returns the array of the requested vertex data kind. Implemented by child classes
  20323. * @param kind defines the vertex data kind to use
  20324. * @returns null
  20325. */
  20326. AbstractMesh.prototype.getVerticesData = function (kind) {
  20327. return null;
  20328. };
  20329. /**
  20330. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20331. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20332. * Note that a new underlying VertexBuffer object is created each call.
  20333. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20334. * @param kind defines vertex data kind:
  20335. * * BABYLON.VertexBuffer.PositionKind
  20336. * * BABYLON.VertexBuffer.UVKind
  20337. * * BABYLON.VertexBuffer.UV2Kind
  20338. * * BABYLON.VertexBuffer.UV3Kind
  20339. * * BABYLON.VertexBuffer.UV4Kind
  20340. * * BABYLON.VertexBuffer.UV5Kind
  20341. * * BABYLON.VertexBuffer.UV6Kind
  20342. * * BABYLON.VertexBuffer.ColorKind
  20343. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20344. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20345. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20346. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20347. * @param data defines the data source
  20348. * @param updatable defines if the data must be flagged as updatable (or static)
  20349. * @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
  20350. * @returns the current mesh
  20351. */
  20352. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20353. return this;
  20354. };
  20355. /**
  20356. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20357. * If the mesh has no geometry, it is simply returned as it is.
  20358. * @param kind defines vertex data kind:
  20359. * * BABYLON.VertexBuffer.PositionKind
  20360. * * BABYLON.VertexBuffer.UVKind
  20361. * * BABYLON.VertexBuffer.UV2Kind
  20362. * * BABYLON.VertexBuffer.UV3Kind
  20363. * * BABYLON.VertexBuffer.UV4Kind
  20364. * * BABYLON.VertexBuffer.UV5Kind
  20365. * * BABYLON.VertexBuffer.UV6Kind
  20366. * * BABYLON.VertexBuffer.ColorKind
  20367. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20368. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20369. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20370. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20371. * @param data defines the data source
  20372. * @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
  20373. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20374. * @returns the current mesh
  20375. */
  20376. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20377. return this;
  20378. };
  20379. /**
  20380. * Sets the mesh indices,
  20381. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20382. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20383. * @param totalVertices Defines the total number of vertices
  20384. * @returns the current mesh
  20385. */
  20386. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20387. return this;
  20388. };
  20389. /**
  20390. * Gets a boolean indicating if specific vertex data is present
  20391. * @param kind defines the vertex data kind to use
  20392. * @returns true is data kind is present
  20393. */
  20394. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20395. return false;
  20396. };
  20397. /**
  20398. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20399. * @returns a BoundingInfo
  20400. */
  20401. AbstractMesh.prototype.getBoundingInfo = function () {
  20402. if (this._masterMesh) {
  20403. return this._masterMesh.getBoundingInfo();
  20404. }
  20405. if (!this._boundingInfo) {
  20406. // this._boundingInfo is being created here
  20407. this._updateBoundingInfo();
  20408. }
  20409. // cannot be null.
  20410. return this._boundingInfo;
  20411. };
  20412. /**
  20413. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20414. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20415. * @returns the current mesh
  20416. */
  20417. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20418. if (includeDescendants === void 0) { includeDescendants = true; }
  20419. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20420. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20421. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20422. if (maxDimension === 0) {
  20423. return this;
  20424. }
  20425. var scale = 1 / maxDimension;
  20426. this.scaling.scaleInPlace(scale);
  20427. return this;
  20428. };
  20429. /**
  20430. * Overwrite the current bounding info
  20431. * @param boundingInfo defines the new bounding info
  20432. * @returns the current mesh
  20433. */
  20434. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20435. this._boundingInfo = boundingInfo;
  20436. return this;
  20437. };
  20438. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20439. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20440. get: function () {
  20441. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20442. },
  20443. enumerable: true,
  20444. configurable: true
  20445. });
  20446. /** @hidden */
  20447. AbstractMesh.prototype._preActivate = function () {
  20448. };
  20449. /** @hidden */
  20450. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20451. };
  20452. /** @hidden */
  20453. AbstractMesh.prototype._activate = function (renderId) {
  20454. this._renderId = renderId;
  20455. };
  20456. /**
  20457. * Gets the current world matrix
  20458. * @returns a Matrix
  20459. */
  20460. AbstractMesh.prototype.getWorldMatrix = function () {
  20461. if (this._masterMesh) {
  20462. return this._masterMesh.getWorldMatrix();
  20463. }
  20464. return _super.prototype.getWorldMatrix.call(this);
  20465. };
  20466. /** @hidden */
  20467. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20468. if (this._masterMesh) {
  20469. return this._masterMesh._getWorldMatrixDeterminant();
  20470. }
  20471. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20472. };
  20473. // ================================== Point of View Movement =================================
  20474. /**
  20475. * Perform relative position change from the point of view of behind the front of the mesh.
  20476. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20477. * Supports definition of mesh facing forward or backward
  20478. * @param amountRight defines the distance on the right axis
  20479. * @param amountUp defines the distance on the up axis
  20480. * @param amountForward defines the distance on the forward axis
  20481. * @returns the current mesh
  20482. */
  20483. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20484. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20485. return this;
  20486. };
  20487. /**
  20488. * Calculate relative position change from the point of view of behind the front of the mesh.
  20489. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20490. * Supports definition of mesh facing forward or backward
  20491. * @param amountRight defines the distance on the right axis
  20492. * @param amountUp defines the distance on the up axis
  20493. * @param amountForward defines the distance on the forward axis
  20494. * @returns the new displacement vector
  20495. */
  20496. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20497. var rotMatrix = new BABYLON.Matrix();
  20498. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20499. rotQuaternion.toRotationMatrix(rotMatrix);
  20500. var translationDelta = BABYLON.Vector3.Zero();
  20501. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20502. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20503. return translationDelta;
  20504. };
  20505. // ================================== Point of View Rotation =================================
  20506. /**
  20507. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20508. * Supports definition of mesh facing forward or backward
  20509. * @param flipBack defines the flip
  20510. * @param twirlClockwise defines the twirl
  20511. * @param tiltRight defines the tilt
  20512. * @returns the current mesh
  20513. */
  20514. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20515. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20516. return this;
  20517. };
  20518. /**
  20519. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20520. * Supports definition of mesh facing forward or backward.
  20521. * @param flipBack defines the flip
  20522. * @param twirlClockwise defines the twirl
  20523. * @param tiltRight defines the tilt
  20524. * @returns the new rotation vector
  20525. */
  20526. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20527. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20528. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20529. };
  20530. /**
  20531. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20532. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20533. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20534. * @returns the new bounding vectors
  20535. */
  20536. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20537. if (includeDescendants === void 0) { includeDescendants = true; }
  20538. if (predicate === void 0) { predicate = null; }
  20539. // Ensures that all world matrix will be recomputed.
  20540. this.getScene().incrementRenderId();
  20541. this.computeWorldMatrix(true);
  20542. var min;
  20543. var max;
  20544. var boundingInfo = this.getBoundingInfo();
  20545. if (!this.subMeshes) {
  20546. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20547. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20548. }
  20549. else {
  20550. min = boundingInfo.boundingBox.minimumWorld;
  20551. max = boundingInfo.boundingBox.maximumWorld;
  20552. }
  20553. if (includeDescendants) {
  20554. var descendants = this.getDescendants(false);
  20555. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20556. var descendant = descendants_1[_i];
  20557. var childMesh = descendant;
  20558. childMesh.computeWorldMatrix(true);
  20559. // Filters meshes based on custom predicate function.
  20560. if (predicate && !predicate(childMesh)) {
  20561. continue;
  20562. }
  20563. //make sure we have the needed params to get mix and max
  20564. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20565. continue;
  20566. }
  20567. var childBoundingInfo = childMesh.getBoundingInfo();
  20568. var boundingBox = childBoundingInfo.boundingBox;
  20569. var minBox = boundingBox.minimumWorld;
  20570. var maxBox = boundingBox.maximumWorld;
  20571. BABYLON.Tools.CheckExtends(minBox, min, max);
  20572. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20573. }
  20574. }
  20575. return {
  20576. min: min,
  20577. max: max
  20578. };
  20579. };
  20580. /** @hidden */
  20581. AbstractMesh.prototype._updateBoundingInfo = function () {
  20582. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20583. this._boundingInfo.update(this.worldMatrixFromCache);
  20584. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20585. return this;
  20586. };
  20587. /** @hidden */
  20588. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20589. if (!this.subMeshes) {
  20590. return this;
  20591. }
  20592. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20593. var subMesh = this.subMeshes[subIndex];
  20594. if (!subMesh.IsGlobal) {
  20595. subMesh.updateBoundingInfo(matrix);
  20596. }
  20597. }
  20598. return this;
  20599. };
  20600. /** @hidden */
  20601. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20602. // Bounding info
  20603. this._updateBoundingInfo();
  20604. };
  20605. /**
  20606. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20607. * A mesh is in the frustum if its bounding box intersects the frustum
  20608. * @param frustumPlanes defines the frustum to test
  20609. * @returns true if the mesh is in the frustum planes
  20610. */
  20611. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20612. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20613. };
  20614. /**
  20615. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20616. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20617. * @param frustumPlanes defines the frustum to test
  20618. * @returns true if the mesh is completely in the frustum planes
  20619. */
  20620. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20621. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20622. };
  20623. /**
  20624. * True if the mesh intersects another mesh or a SolidParticle object
  20625. * @param mesh defines a target mesh or SolidParticle to test
  20626. * @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)
  20627. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20628. * @returns true if there is an intersection
  20629. */
  20630. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20631. if (precise === void 0) { precise = false; }
  20632. if (!this._boundingInfo || !mesh._boundingInfo) {
  20633. return false;
  20634. }
  20635. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20636. return true;
  20637. }
  20638. if (includeDescendants) {
  20639. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20640. var child = _a[_i];
  20641. if (child.intersectsMesh(mesh, precise, true)) {
  20642. return true;
  20643. }
  20644. }
  20645. }
  20646. return false;
  20647. };
  20648. /**
  20649. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20650. * @param point defines the point to test
  20651. * @returns true if there is an intersection
  20652. */
  20653. AbstractMesh.prototype.intersectsPoint = function (point) {
  20654. if (!this._boundingInfo) {
  20655. return false;
  20656. }
  20657. return this._boundingInfo.intersectsPoint(point);
  20658. };
  20659. /**
  20660. * Gets the current physics impostor
  20661. * @see http://doc.babylonjs.com/features/physics_engine
  20662. * @returns a physics impostor or null
  20663. */
  20664. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20665. return this.physicsImpostor;
  20666. };
  20667. /**
  20668. * Gets the position of the current mesh in camera space
  20669. * @param camera defines the camera to use
  20670. * @returns a position
  20671. */
  20672. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20673. if (camera === void 0) { camera = null; }
  20674. if (!camera) {
  20675. camera = this.getScene().activeCamera;
  20676. }
  20677. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20678. };
  20679. /**
  20680. * Returns the distance from the mesh to the active camera
  20681. * @param camera defines the camera to use
  20682. * @returns the distance
  20683. */
  20684. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20685. if (camera === void 0) { camera = null; }
  20686. if (!camera) {
  20687. camera = this.getScene().activeCamera;
  20688. }
  20689. return this.absolutePosition.subtract(camera.position).length();
  20690. };
  20691. /**
  20692. * Apply a physic impulse to the mesh
  20693. * @param force defines the force to apply
  20694. * @param contactPoint defines where to apply the force
  20695. * @returns the current mesh
  20696. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20697. */
  20698. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20699. if (!this.physicsImpostor) {
  20700. return this;
  20701. }
  20702. this.physicsImpostor.applyImpulse(force, contactPoint);
  20703. return this;
  20704. };
  20705. /**
  20706. * Creates a physic joint between two meshes
  20707. * @param otherMesh defines the other mesh to use
  20708. * @param pivot1 defines the pivot to use on this mesh
  20709. * @param pivot2 defines the pivot to use on the other mesh
  20710. * @param options defines additional options (can be plugin dependent)
  20711. * @returns the current mesh
  20712. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20713. */
  20714. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20715. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20716. return this;
  20717. }
  20718. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20719. mainPivot: pivot1,
  20720. connectedPivot: pivot2,
  20721. nativeParams: options
  20722. });
  20723. return this;
  20724. };
  20725. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20726. // Collisions
  20727. /**
  20728. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20729. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20730. */
  20731. get: function () {
  20732. return this._checkCollisions;
  20733. },
  20734. set: function (collisionEnabled) {
  20735. this._checkCollisions = collisionEnabled;
  20736. if (this.getScene().workerCollisions) {
  20737. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20738. }
  20739. },
  20740. enumerable: true,
  20741. configurable: true
  20742. });
  20743. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20744. /**
  20745. * Gets Collider object used to compute collisions (not physics)
  20746. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20747. */
  20748. get: function () {
  20749. return this._collider;
  20750. },
  20751. enumerable: true,
  20752. configurable: true
  20753. });
  20754. /**
  20755. * Move the mesh using collision engine
  20756. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20757. * @param displacement defines the requested displacement vector
  20758. * @returns the current mesh
  20759. */
  20760. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20761. var globalPosition = this.getAbsolutePosition();
  20762. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20763. if (!this._collider) {
  20764. this._collider = new BABYLON.Collider();
  20765. }
  20766. this._collider._radius = this.ellipsoid;
  20767. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20768. return this;
  20769. };
  20770. // Submeshes octree
  20771. /**
  20772. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20773. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20774. * @param maxCapacity defines the maximum size of each block (64 by default)
  20775. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20776. * @returns the new octree
  20777. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20778. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20779. */
  20780. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20781. if (maxCapacity === void 0) { maxCapacity = 64; }
  20782. if (maxDepth === void 0) { maxDepth = 2; }
  20783. if (!this._submeshesOctree) {
  20784. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20785. }
  20786. this.computeWorldMatrix(true);
  20787. var boundingInfo = this.getBoundingInfo();
  20788. // Update octree
  20789. var bbox = boundingInfo.boundingBox;
  20790. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20791. return this._submeshesOctree;
  20792. };
  20793. // Collisions
  20794. /** @hidden */
  20795. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20796. this._generatePointsArray();
  20797. if (!this._positions) {
  20798. return this;
  20799. }
  20800. // Transformation
  20801. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20802. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20803. subMesh._lastColliderWorldVertices = [];
  20804. subMesh._trianglePlanes = [];
  20805. var start = subMesh.verticesStart;
  20806. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20807. for (var i = start; i < end; i++) {
  20808. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20809. }
  20810. }
  20811. // Collide
  20812. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20813. if (collider.collisionFound) {
  20814. collider.collidedMesh = this;
  20815. }
  20816. return this;
  20817. };
  20818. /** @hidden */
  20819. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20820. var subMeshes;
  20821. var len;
  20822. // Octrees
  20823. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20824. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20825. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20826. len = intersections.length;
  20827. subMeshes = intersections.data;
  20828. }
  20829. else {
  20830. subMeshes = this.subMeshes;
  20831. len = subMeshes.length;
  20832. }
  20833. for (var index = 0; index < len; index++) {
  20834. var subMesh = subMeshes[index];
  20835. // Bounding test
  20836. if (len > 1 && !subMesh._checkCollision(collider))
  20837. continue;
  20838. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20839. }
  20840. return this;
  20841. };
  20842. /** @hidden */
  20843. AbstractMesh.prototype._checkCollision = function (collider) {
  20844. // Bounding box test
  20845. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20846. return this;
  20847. // Transformation matrix
  20848. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20849. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20850. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20851. return this;
  20852. };
  20853. // Picking
  20854. /** @hidden */
  20855. AbstractMesh.prototype._generatePointsArray = function () {
  20856. return false;
  20857. };
  20858. /**
  20859. * Checks if the passed Ray intersects with the mesh
  20860. * @param ray defines the ray to use
  20861. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20862. * @returns the picking info
  20863. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20864. */
  20865. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20866. var pickingInfo = new BABYLON.PickingInfo();
  20867. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20868. return pickingInfo;
  20869. }
  20870. if (!this._generatePointsArray()) {
  20871. return pickingInfo;
  20872. }
  20873. var intersectInfo = null;
  20874. // Octrees
  20875. var subMeshes;
  20876. var len;
  20877. if (this._submeshesOctree && this.useOctreeForPicking) {
  20878. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20879. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20880. len = intersections.length;
  20881. subMeshes = intersections.data;
  20882. }
  20883. else {
  20884. subMeshes = this.subMeshes;
  20885. len = subMeshes.length;
  20886. }
  20887. for (var index = 0; index < len; index++) {
  20888. var subMesh = subMeshes[index];
  20889. // Bounding test
  20890. if (len > 1 && !subMesh.canIntersects(ray))
  20891. continue;
  20892. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20893. if (currentIntersectInfo) {
  20894. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20895. intersectInfo = currentIntersectInfo;
  20896. intersectInfo.subMeshId = index;
  20897. if (fastCheck) {
  20898. break;
  20899. }
  20900. }
  20901. }
  20902. }
  20903. if (intersectInfo) {
  20904. // Get picked point
  20905. var world = this.getWorldMatrix();
  20906. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20907. var direction = ray.direction.clone();
  20908. direction = direction.scale(intersectInfo.distance);
  20909. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20910. var pickedPoint = worldOrigin.add(worldDirection);
  20911. // Return result
  20912. pickingInfo.hit = true;
  20913. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20914. pickingInfo.pickedPoint = pickedPoint;
  20915. pickingInfo.pickedMesh = this;
  20916. pickingInfo.bu = intersectInfo.bu || 0;
  20917. pickingInfo.bv = intersectInfo.bv || 0;
  20918. pickingInfo.faceId = intersectInfo.faceId;
  20919. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20920. return pickingInfo;
  20921. }
  20922. return pickingInfo;
  20923. };
  20924. /**
  20925. * Clones the current mesh
  20926. * @param name defines the mesh name
  20927. * @param newParent defines the new mesh parent
  20928. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20929. * @returns the new mesh
  20930. */
  20931. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20932. return null;
  20933. };
  20934. /**
  20935. * Disposes all the submeshes of the current meshnp
  20936. * @returns the current mesh
  20937. */
  20938. AbstractMesh.prototype.releaseSubMeshes = function () {
  20939. if (this.subMeshes) {
  20940. while (this.subMeshes.length) {
  20941. this.subMeshes[0].dispose();
  20942. }
  20943. }
  20944. else {
  20945. this.subMeshes = new Array();
  20946. }
  20947. return this;
  20948. };
  20949. /**
  20950. * Releases resources associated with this abstract mesh.
  20951. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20952. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20953. */
  20954. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20955. var _this = this;
  20956. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20957. var index;
  20958. // Smart Array Retainers.
  20959. this.getScene().freeActiveMeshes();
  20960. this.getScene().freeRenderingGroups();
  20961. // Action manager
  20962. if (this.actionManager !== undefined && this.actionManager !== null) {
  20963. this.actionManager.dispose();
  20964. this.actionManager = null;
  20965. }
  20966. // Skeleton
  20967. this._skeleton = null;
  20968. // Physics
  20969. if (this.physicsImpostor) {
  20970. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20971. }
  20972. // Intersections in progress
  20973. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20974. var other = this._intersectionsInProgress[index];
  20975. var pos = other._intersectionsInProgress.indexOf(this);
  20976. other._intersectionsInProgress.splice(pos, 1);
  20977. }
  20978. this._intersectionsInProgress = [];
  20979. // Lights
  20980. var lights = this.getScene().lights;
  20981. lights.forEach(function (light) {
  20982. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20983. if (meshIndex !== -1) {
  20984. light.includedOnlyMeshes.splice(meshIndex, 1);
  20985. }
  20986. meshIndex = light.excludedMeshes.indexOf(_this);
  20987. if (meshIndex !== -1) {
  20988. light.excludedMeshes.splice(meshIndex, 1);
  20989. }
  20990. // Shadow generators
  20991. var generator = light.getShadowGenerator();
  20992. if (generator) {
  20993. var shadowMap = generator.getShadowMap();
  20994. if (shadowMap && shadowMap.renderList) {
  20995. meshIndex = shadowMap.renderList.indexOf(_this);
  20996. if (meshIndex !== -1) {
  20997. shadowMap.renderList.splice(meshIndex, 1);
  20998. }
  20999. }
  21000. }
  21001. });
  21002. // Edges
  21003. if (this._edgesRenderer) {
  21004. this._edgesRenderer.dispose();
  21005. this._edgesRenderer = null;
  21006. }
  21007. // SubMeshes
  21008. if (this.getClassName() !== "InstancedMesh") {
  21009. this.releaseSubMeshes();
  21010. }
  21011. // Octree
  21012. var sceneOctree = this.getScene().selectionOctree;
  21013. if (sceneOctree !== undefined && sceneOctree !== null) {
  21014. var index = sceneOctree.dynamicContent.indexOf(this);
  21015. if (index !== -1) {
  21016. sceneOctree.dynamicContent.splice(index, 1);
  21017. }
  21018. }
  21019. // Query
  21020. var engine = this.getScene().getEngine();
  21021. if (this._occlusionQuery) {
  21022. this._isOcclusionQueryInProgress = false;
  21023. engine.deleteQuery(this._occlusionQuery);
  21024. this._occlusionQuery = null;
  21025. }
  21026. // Engine
  21027. engine.wipeCaches();
  21028. // Remove from scene
  21029. this.getScene().removeMesh(this);
  21030. if (disposeMaterialAndTextures) {
  21031. if (this.material) {
  21032. this.material.dispose(false, true);
  21033. }
  21034. }
  21035. if (!doNotRecurse) {
  21036. // Particles
  21037. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21038. if (this.getScene().particleSystems[index].emitter === this) {
  21039. this.getScene().particleSystems[index].dispose();
  21040. index--;
  21041. }
  21042. }
  21043. }
  21044. // facet data
  21045. if (this._facetDataEnabled) {
  21046. this.disableFacetData();
  21047. }
  21048. this.onAfterWorldMatrixUpdateObservable.clear();
  21049. this.onCollideObservable.clear();
  21050. this.onCollisionPositionChangeObservable.clear();
  21051. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21052. };
  21053. /**
  21054. * Adds the passed mesh as a child to the current mesh
  21055. * @param mesh defines the child mesh
  21056. * @returns the current mesh
  21057. */
  21058. AbstractMesh.prototype.addChild = function (mesh) {
  21059. mesh.setParent(this);
  21060. return this;
  21061. };
  21062. /**
  21063. * Removes the passed mesh from the current mesh children list
  21064. * @param mesh defines the child mesh
  21065. * @returns the current mesh
  21066. */
  21067. AbstractMesh.prototype.removeChild = function (mesh) {
  21068. mesh.setParent(null);
  21069. return this;
  21070. };
  21071. // Facet data
  21072. /** @hidden */
  21073. AbstractMesh.prototype._initFacetData = function () {
  21074. if (!this._facetNormals) {
  21075. this._facetNormals = new Array();
  21076. }
  21077. if (!this._facetPositions) {
  21078. this._facetPositions = new Array();
  21079. }
  21080. if (!this._facetPartitioning) {
  21081. this._facetPartitioning = new Array();
  21082. }
  21083. this._facetNb = (this.getIndices().length / 3) | 0;
  21084. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21085. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21086. for (var f = 0; f < this._facetNb; f++) {
  21087. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21088. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21089. }
  21090. this._facetDataEnabled = true;
  21091. return this;
  21092. };
  21093. /**
  21094. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21095. * This method can be called within the render loop.
  21096. * 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
  21097. * @returns the current mesh
  21098. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21099. */
  21100. AbstractMesh.prototype.updateFacetData = function () {
  21101. if (!this._facetDataEnabled) {
  21102. this._initFacetData();
  21103. }
  21104. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21105. var indices = this.getIndices();
  21106. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21107. var bInfo = this.getBoundingInfo();
  21108. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21109. // init arrays, matrix and sort function on first call
  21110. this._facetDepthSortEnabled = true;
  21111. if (indices instanceof Uint16Array) {
  21112. this._depthSortedIndices = new Uint16Array(indices);
  21113. }
  21114. else if (indices instanceof Uint32Array) {
  21115. this._depthSortedIndices = new Uint32Array(indices);
  21116. }
  21117. else {
  21118. var needs32bits = false;
  21119. for (var i = 0; i < indices.length; i++) {
  21120. if (indices[i] > 65535) {
  21121. needs32bits = true;
  21122. break;
  21123. }
  21124. }
  21125. if (needs32bits) {
  21126. this._depthSortedIndices = new Uint32Array(indices);
  21127. }
  21128. else {
  21129. this._depthSortedIndices = new Uint16Array(indices);
  21130. }
  21131. }
  21132. this._facetDepthSortFunction = function (f1, f2) {
  21133. return (f2.sqDistance - f1.sqDistance);
  21134. };
  21135. if (!this._facetDepthSortFrom) {
  21136. var camera = this.getScene().activeCamera;
  21137. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21138. }
  21139. this._depthSortedFacets = [];
  21140. for (var f = 0; f < this._facetNb; f++) {
  21141. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21142. this._depthSortedFacets.push(depthSortedFacet);
  21143. }
  21144. this._invertedMatrix = BABYLON.Matrix.Identity();
  21145. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21146. }
  21147. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21148. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21149. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21150. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21151. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21152. this._subDiv.max = this._partitioningSubdivisions;
  21153. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21154. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21155. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21156. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21157. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21158. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21159. // set the parameters for ComputeNormals()
  21160. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21161. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21162. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21163. this._facetParameters.bInfo = bInfo;
  21164. this._facetParameters.bbSize = this._bbSize;
  21165. this._facetParameters.subDiv = this._subDiv;
  21166. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21167. this._facetParameters.depthSort = this._facetDepthSort;
  21168. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21169. this.computeWorldMatrix(true);
  21170. this._worldMatrix.invertToRef(this._invertedMatrix);
  21171. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21172. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21173. }
  21174. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21175. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21176. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21177. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21178. var l = (this._depthSortedIndices.length / 3) | 0;
  21179. for (var f = 0; f < l; f++) {
  21180. var sind = this._depthSortedFacets[f].ind;
  21181. this._depthSortedIndices[f * 3] = indices[sind];
  21182. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21183. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21184. }
  21185. this.updateIndices(this._depthSortedIndices);
  21186. }
  21187. return this;
  21188. };
  21189. /**
  21190. * Returns the facetLocalNormals array.
  21191. * The normals are expressed in the mesh local spac
  21192. * @returns an array of Vector3
  21193. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21194. */
  21195. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21196. if (!this._facetNormals) {
  21197. this.updateFacetData();
  21198. }
  21199. return this._facetNormals;
  21200. };
  21201. /**
  21202. * Returns the facetLocalPositions array.
  21203. * The facet positions are expressed in the mesh local space
  21204. * @returns an array of Vector3
  21205. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21206. */
  21207. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21208. if (!this._facetPositions) {
  21209. this.updateFacetData();
  21210. }
  21211. return this._facetPositions;
  21212. };
  21213. /**
  21214. * Returns the facetLocalPartioning array
  21215. * @returns an array of array of numbers
  21216. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21217. */
  21218. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21219. if (!this._facetPartitioning) {
  21220. this.updateFacetData();
  21221. }
  21222. return this._facetPartitioning;
  21223. };
  21224. /**
  21225. * Returns the i-th facet position in the world system.
  21226. * This method allocates a new Vector3 per call
  21227. * @param i defines the facet index
  21228. * @returns a new Vector3
  21229. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21230. */
  21231. AbstractMesh.prototype.getFacetPosition = function (i) {
  21232. var pos = BABYLON.Vector3.Zero();
  21233. this.getFacetPositionToRef(i, pos);
  21234. return pos;
  21235. };
  21236. /**
  21237. * Sets the reference Vector3 with the i-th facet position in the world system
  21238. * @param i defines the facet index
  21239. * @param ref defines the target vector
  21240. * @returns the current mesh
  21241. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21242. */
  21243. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21244. var localPos = (this.getFacetLocalPositions())[i];
  21245. var world = this.getWorldMatrix();
  21246. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21247. return this;
  21248. };
  21249. /**
  21250. * Returns the i-th facet normal in the world system.
  21251. * This method allocates a new Vector3 per call
  21252. * @param i defines the facet index
  21253. * @returns a new Vector3
  21254. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21255. */
  21256. AbstractMesh.prototype.getFacetNormal = function (i) {
  21257. var norm = BABYLON.Vector3.Zero();
  21258. this.getFacetNormalToRef(i, norm);
  21259. return norm;
  21260. };
  21261. /**
  21262. * Sets the reference Vector3 with the i-th facet normal in the world system
  21263. * @param i defines the facet index
  21264. * @param ref defines the target vector
  21265. * @returns the current mesh
  21266. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21267. */
  21268. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21269. var localNorm = (this.getFacetLocalNormals())[i];
  21270. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21271. return this;
  21272. };
  21273. /**
  21274. * 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)
  21275. * @param x defines x coordinate
  21276. * @param y defines y coordinate
  21277. * @param z defines z coordinate
  21278. * @returns the array of facet indexes
  21279. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21280. */
  21281. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21282. var bInfo = this.getBoundingInfo();
  21283. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21284. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21285. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21286. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21287. return null;
  21288. }
  21289. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21290. };
  21291. /**
  21292. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21293. * @param projected sets as the (x,y,z) world projection on the facet
  21294. * @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
  21295. * @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
  21296. * @param x defines x coordinate
  21297. * @param y defines y coordinate
  21298. * @param z defines z coordinate
  21299. * @returns the face index if found (or null instead)
  21300. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21301. */
  21302. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21303. if (checkFace === void 0) { checkFace = false; }
  21304. if (facing === void 0) { facing = true; }
  21305. var world = this.getWorldMatrix();
  21306. var invMat = BABYLON.Tmp.Matrix[5];
  21307. world.invertToRef(invMat);
  21308. var invVect = BABYLON.Tmp.Vector3[8];
  21309. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21310. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21311. if (projected) {
  21312. // tranform the local computed projected vector to world coordinates
  21313. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21314. }
  21315. return closest;
  21316. };
  21317. /**
  21318. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21319. * @param projected sets as the (x,y,z) local projection on the facet
  21320. * @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
  21321. * @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
  21322. * @param x defines x coordinate
  21323. * @param y defines y coordinate
  21324. * @param z defines z coordinate
  21325. * @returns the face index if found (or null instead)
  21326. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21327. */
  21328. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21329. if (checkFace === void 0) { checkFace = false; }
  21330. if (facing === void 0) { facing = true; }
  21331. var closest = null;
  21332. var tmpx = 0.0;
  21333. var tmpy = 0.0;
  21334. var tmpz = 0.0;
  21335. var d = 0.0; // tmp dot facet normal * facet position
  21336. var t0 = 0.0;
  21337. var projx = 0.0;
  21338. var projy = 0.0;
  21339. var projz = 0.0;
  21340. // Get all the facets in the same partitioning block than (x, y, z)
  21341. var facetPositions = this.getFacetLocalPositions();
  21342. var facetNormals = this.getFacetLocalNormals();
  21343. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21344. if (!facetsInBlock) {
  21345. return null;
  21346. }
  21347. // Get the closest facet to (x, y, z)
  21348. var shortest = Number.MAX_VALUE; // init distance vars
  21349. var tmpDistance = shortest;
  21350. var fib; // current facet in the block
  21351. var norm; // current facet normal
  21352. var p0; // current facet barycenter position
  21353. // loop on all the facets in the current partitioning block
  21354. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21355. fib = facetsInBlock[idx];
  21356. norm = facetNormals[fib];
  21357. p0 = facetPositions[fib];
  21358. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21359. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21360. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21361. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21362. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21363. projx = x + norm.x * t0;
  21364. projy = y + norm.y * t0;
  21365. projz = z + norm.z * t0;
  21366. tmpx = projx - x;
  21367. tmpy = projy - y;
  21368. tmpz = projz - z;
  21369. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21370. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21371. shortest = tmpDistance;
  21372. closest = fib;
  21373. if (projected) {
  21374. projected.x = projx;
  21375. projected.y = projy;
  21376. projected.z = projz;
  21377. }
  21378. }
  21379. }
  21380. }
  21381. return closest;
  21382. };
  21383. /**
  21384. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21385. * @returns the parameters
  21386. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21387. */
  21388. AbstractMesh.prototype.getFacetDataParameters = function () {
  21389. return this._facetParameters;
  21390. };
  21391. /**
  21392. * Disables the feature FacetData and frees the related memory
  21393. * @returns the current mesh
  21394. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21395. */
  21396. AbstractMesh.prototype.disableFacetData = function () {
  21397. if (this._facetDataEnabled) {
  21398. this._facetDataEnabled = false;
  21399. this._facetPositions = new Array();
  21400. this._facetNormals = new Array();
  21401. this._facetPartitioning = new Array();
  21402. this._facetParameters = null;
  21403. this._depthSortedIndices = new Uint32Array(0);
  21404. }
  21405. return this;
  21406. };
  21407. /**
  21408. * Updates the AbstractMesh indices array
  21409. * @param indices defines the data source
  21410. * @returns the current mesh
  21411. */
  21412. AbstractMesh.prototype.updateIndices = function (indices) {
  21413. return this;
  21414. };
  21415. /**
  21416. * Creates new normals data for the mesh
  21417. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21418. * @returns the current mesh
  21419. */
  21420. AbstractMesh.prototype.createNormals = function (updatable) {
  21421. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21422. var indices = this.getIndices();
  21423. var normals;
  21424. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21425. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21426. }
  21427. else {
  21428. normals = [];
  21429. }
  21430. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21431. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21432. return this;
  21433. };
  21434. /**
  21435. * Align the mesh with a normal
  21436. * @param normal defines the normal to use
  21437. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21438. * @returns the current mesh
  21439. */
  21440. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21441. if (!upDirection) {
  21442. upDirection = BABYLON.Axis.Y;
  21443. }
  21444. var axisX = BABYLON.Tmp.Vector3[0];
  21445. var axisZ = BABYLON.Tmp.Vector3[1];
  21446. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21447. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21448. if (this.rotationQuaternion) {
  21449. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21450. }
  21451. else {
  21452. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21453. }
  21454. return this;
  21455. };
  21456. /** @hidden */
  21457. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21458. var engine = this.getEngine();
  21459. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21460. this._isOccluded = false;
  21461. return;
  21462. }
  21463. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21464. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21465. if (isOcclusionQueryAvailable) {
  21466. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21467. this._isOcclusionQueryInProgress = false;
  21468. this._occlusionInternalRetryCounter = 0;
  21469. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21470. }
  21471. else {
  21472. this._occlusionInternalRetryCounter++;
  21473. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21474. this._isOcclusionQueryInProgress = false;
  21475. this._occlusionInternalRetryCounter = 0;
  21476. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21477. // if strict continue the last state of the object.
  21478. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21479. }
  21480. else {
  21481. return;
  21482. }
  21483. }
  21484. }
  21485. var scene = this.getScene();
  21486. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21487. if (!this._occlusionQuery) {
  21488. this._occlusionQuery = engine.createQuery();
  21489. }
  21490. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21491. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21492. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21493. this._isOcclusionQueryInProgress = true;
  21494. };
  21495. /** No occlusion */
  21496. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21497. /** Occlusion set to optimisitic */
  21498. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21499. /** Occlusion set to strict */
  21500. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21501. /** Use an accurante occlusion algorithm */
  21502. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21503. /** Use a conservative occlusion algorithm */
  21504. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21505. return AbstractMesh;
  21506. }(BABYLON.TransformNode));
  21507. BABYLON.AbstractMesh = AbstractMesh;
  21508. })(BABYLON || (BABYLON = {}));
  21509. //# sourceMappingURL=babylon.abstractMesh.js.map
  21510. var BABYLON;
  21511. (function (BABYLON) {
  21512. /**
  21513. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21514. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21515. * 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.
  21516. */
  21517. var Light = /** @class */ (function (_super) {
  21518. __extends(Light, _super);
  21519. /**
  21520. * Creates a Light object in the scene.
  21521. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21522. * @param name The firendly name of the light
  21523. * @param scene The scene the light belongs too
  21524. */
  21525. function Light(name, scene) {
  21526. var _this = _super.call(this, name, scene) || this;
  21527. /**
  21528. * Diffuse gives the basic color to an object.
  21529. */
  21530. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21531. /**
  21532. * Specular produces a highlight color on an object.
  21533. * Note: This is note affecting PBR materials.
  21534. */
  21535. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21536. /**
  21537. * Strength of the light.
  21538. * Note: By default it is define in the framework own unit.
  21539. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21540. */
  21541. _this.intensity = 1.0;
  21542. /**
  21543. * Defines how far from the source the light is impacting in scene units.
  21544. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21545. */
  21546. _this.range = Number.MAX_VALUE;
  21547. /**
  21548. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21549. * of light.
  21550. */
  21551. _this._photometricScale = 1.0;
  21552. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21553. _this._radius = 0.00001;
  21554. /**
  21555. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21556. * exceeding the number allowed of the materials.
  21557. */
  21558. _this.renderPriority = 0;
  21559. _this._shadowEnabled = true;
  21560. _this._excludeWithLayerMask = 0;
  21561. _this._includeOnlyWithLayerMask = 0;
  21562. _this._lightmapMode = 0;
  21563. /**
  21564. * @hidden Internal use only.
  21565. */
  21566. _this._excludedMeshesIds = new Array();
  21567. /**
  21568. * @hidden Internal use only.
  21569. */
  21570. _this._includedOnlyMeshesIds = new Array();
  21571. _this.getScene().addLight(_this);
  21572. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21573. _this._buildUniformLayout();
  21574. _this.includedOnlyMeshes = new Array();
  21575. _this.excludedMeshes = new Array();
  21576. _this._resyncMeshes();
  21577. return _this;
  21578. }
  21579. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21580. /**
  21581. * If every light affecting the material is in this lightmapMode,
  21582. * material.lightmapTexture adds or multiplies
  21583. * (depends on material.useLightmapAsShadowmap)
  21584. * after every other light calculations.
  21585. */
  21586. get: function () {
  21587. return Light._LIGHTMAP_DEFAULT;
  21588. },
  21589. enumerable: true,
  21590. configurable: true
  21591. });
  21592. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21593. /**
  21594. * material.lightmapTexture as only diffuse lighting from this light
  21595. * adds only specular lighting from this light
  21596. * adds dynamic shadows
  21597. */
  21598. get: function () {
  21599. return Light._LIGHTMAP_SPECULAR;
  21600. },
  21601. enumerable: true,
  21602. configurable: true
  21603. });
  21604. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21605. /**
  21606. * material.lightmapTexture as only lighting
  21607. * no light calculation from this light
  21608. * only adds dynamic shadows from this light
  21609. */
  21610. get: function () {
  21611. return Light._LIGHTMAP_SHADOWSONLY;
  21612. },
  21613. enumerable: true,
  21614. configurable: true
  21615. });
  21616. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21617. /**
  21618. * Each light type uses the default quantity according to its type:
  21619. * point/spot lights use luminous intensity
  21620. * directional lights use illuminance
  21621. */
  21622. get: function () {
  21623. return Light._INTENSITYMODE_AUTOMATIC;
  21624. },
  21625. enumerable: true,
  21626. configurable: true
  21627. });
  21628. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21629. /**
  21630. * lumen (lm)
  21631. */
  21632. get: function () {
  21633. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21634. },
  21635. enumerable: true,
  21636. configurable: true
  21637. });
  21638. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21639. /**
  21640. * candela (lm/sr)
  21641. */
  21642. get: function () {
  21643. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21644. },
  21645. enumerable: true,
  21646. configurable: true
  21647. });
  21648. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21649. /**
  21650. * lux (lm/m^2)
  21651. */
  21652. get: function () {
  21653. return Light._INTENSITYMODE_ILLUMINANCE;
  21654. },
  21655. enumerable: true,
  21656. configurable: true
  21657. });
  21658. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21659. /**
  21660. * nit (cd/m^2)
  21661. */
  21662. get: function () {
  21663. return Light._INTENSITYMODE_LUMINANCE;
  21664. },
  21665. enumerable: true,
  21666. configurable: true
  21667. });
  21668. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21669. /**
  21670. * Light type const id of the point light.
  21671. */
  21672. get: function () {
  21673. return Light._LIGHTTYPEID_POINTLIGHT;
  21674. },
  21675. enumerable: true,
  21676. configurable: true
  21677. });
  21678. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21679. /**
  21680. * Light type const id of the directional light.
  21681. */
  21682. get: function () {
  21683. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21684. },
  21685. enumerable: true,
  21686. configurable: true
  21687. });
  21688. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21689. /**
  21690. * Light type const id of the spot light.
  21691. */
  21692. get: function () {
  21693. return Light._LIGHTTYPEID_SPOTLIGHT;
  21694. },
  21695. enumerable: true,
  21696. configurable: true
  21697. });
  21698. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21699. /**
  21700. * Light type const id of the hemispheric light.
  21701. */
  21702. get: function () {
  21703. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21704. },
  21705. enumerable: true,
  21706. configurable: true
  21707. });
  21708. Object.defineProperty(Light.prototype, "intensityMode", {
  21709. /**
  21710. * Gets the photometric scale used to interpret the intensity.
  21711. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21712. */
  21713. get: function () {
  21714. return this._intensityMode;
  21715. },
  21716. /**
  21717. * Sets the photometric scale used to interpret the intensity.
  21718. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21719. */
  21720. set: function (value) {
  21721. this._intensityMode = value;
  21722. this._computePhotometricScale();
  21723. },
  21724. enumerable: true,
  21725. configurable: true
  21726. });
  21727. ;
  21728. ;
  21729. Object.defineProperty(Light.prototype, "radius", {
  21730. /**
  21731. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21732. */
  21733. get: function () {
  21734. return this._radius;
  21735. },
  21736. /**
  21737. * sets the light radius used by PBR Materials to simulate soft area lights.
  21738. */
  21739. set: function (value) {
  21740. this._radius = value;
  21741. this._computePhotometricScale();
  21742. },
  21743. enumerable: true,
  21744. configurable: true
  21745. });
  21746. ;
  21747. ;
  21748. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21749. /**
  21750. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21751. * the current shadow generator.
  21752. */
  21753. get: function () {
  21754. return this._shadowEnabled;
  21755. },
  21756. /**
  21757. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21758. * the current shadow generator.
  21759. */
  21760. set: function (value) {
  21761. if (this._shadowEnabled === value) {
  21762. return;
  21763. }
  21764. this._shadowEnabled = value;
  21765. this._markMeshesAsLightDirty();
  21766. },
  21767. enumerable: true,
  21768. configurable: true
  21769. });
  21770. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21771. /**
  21772. * Gets the only meshes impacted by this light.
  21773. */
  21774. get: function () {
  21775. return this._includedOnlyMeshes;
  21776. },
  21777. /**
  21778. * Sets the only meshes impacted by this light.
  21779. */
  21780. set: function (value) {
  21781. this._includedOnlyMeshes = value;
  21782. this._hookArrayForIncludedOnly(value);
  21783. },
  21784. enumerable: true,
  21785. configurable: true
  21786. });
  21787. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21788. /**
  21789. * Gets the meshes not impacted by this light.
  21790. */
  21791. get: function () {
  21792. return this._excludedMeshes;
  21793. },
  21794. /**
  21795. * Sets the meshes not impacted by this light.
  21796. */
  21797. set: function (value) {
  21798. this._excludedMeshes = value;
  21799. this._hookArrayForExcluded(value);
  21800. },
  21801. enumerable: true,
  21802. configurable: true
  21803. });
  21804. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21805. /**
  21806. * Gets the layer id use to find what meshes are not impacted by the light.
  21807. * Inactive if 0
  21808. */
  21809. get: function () {
  21810. return this._excludeWithLayerMask;
  21811. },
  21812. /**
  21813. * Sets the layer id use to find what meshes are not impacted by the light.
  21814. * Inactive if 0
  21815. */
  21816. set: function (value) {
  21817. this._excludeWithLayerMask = value;
  21818. this._resyncMeshes();
  21819. },
  21820. enumerable: true,
  21821. configurable: true
  21822. });
  21823. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21824. /**
  21825. * Gets the layer id use to find what meshes are impacted by the light.
  21826. * Inactive if 0
  21827. */
  21828. get: function () {
  21829. return this._includeOnlyWithLayerMask;
  21830. },
  21831. /**
  21832. * Sets the layer id use to find what meshes are impacted by the light.
  21833. * Inactive if 0
  21834. */
  21835. set: function (value) {
  21836. this._includeOnlyWithLayerMask = value;
  21837. this._resyncMeshes();
  21838. },
  21839. enumerable: true,
  21840. configurable: true
  21841. });
  21842. Object.defineProperty(Light.prototype, "lightmapMode", {
  21843. /**
  21844. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21845. */
  21846. get: function () {
  21847. return this._lightmapMode;
  21848. },
  21849. /**
  21850. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21851. */
  21852. set: function (value) {
  21853. if (this._lightmapMode === value) {
  21854. return;
  21855. }
  21856. this._lightmapMode = value;
  21857. this._markMeshesAsLightDirty();
  21858. },
  21859. enumerable: true,
  21860. configurable: true
  21861. });
  21862. /**
  21863. * Returns the string "Light".
  21864. * @returns the class name
  21865. */
  21866. Light.prototype.getClassName = function () {
  21867. return "Light";
  21868. };
  21869. /**
  21870. * Converts the light information to a readable string for debug purpose.
  21871. * @param fullDetails Supports for multiple levels of logging within scene loading
  21872. * @returns the human readable light info
  21873. */
  21874. Light.prototype.toString = function (fullDetails) {
  21875. var ret = "Name: " + this.name;
  21876. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21877. if (this.animations) {
  21878. for (var i = 0; i < this.animations.length; i++) {
  21879. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21880. }
  21881. }
  21882. if (fullDetails) {
  21883. }
  21884. return ret;
  21885. };
  21886. /**
  21887. * Set the enabled state of this node.
  21888. * @param value - the new enabled state
  21889. */
  21890. Light.prototype.setEnabled = function (value) {
  21891. _super.prototype.setEnabled.call(this, value);
  21892. this._resyncMeshes();
  21893. };
  21894. /**
  21895. * Returns the Light associated shadow generator if any.
  21896. * @return the associated shadow generator.
  21897. */
  21898. Light.prototype.getShadowGenerator = function () {
  21899. return this._shadowGenerator;
  21900. };
  21901. /**
  21902. * Returns a Vector3, the absolute light position in the World.
  21903. * @returns the world space position of the light
  21904. */
  21905. Light.prototype.getAbsolutePosition = function () {
  21906. return BABYLON.Vector3.Zero();
  21907. };
  21908. /**
  21909. * Specifies if the light will affect the passed mesh.
  21910. * @param mesh The mesh to test against the light
  21911. * @return true the mesh is affected otherwise, false.
  21912. */
  21913. Light.prototype.canAffectMesh = function (mesh) {
  21914. if (!mesh) {
  21915. return true;
  21916. }
  21917. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21918. return false;
  21919. }
  21920. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21921. return false;
  21922. }
  21923. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21924. return false;
  21925. }
  21926. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21927. return false;
  21928. }
  21929. return true;
  21930. };
  21931. /**
  21932. * Computes and Returns the light World matrix.
  21933. * @returns the world matrix
  21934. */
  21935. Light.prototype.getWorldMatrix = function () {
  21936. this._currentRenderId = this.getScene().getRenderId();
  21937. this._childRenderId = this._currentRenderId;
  21938. var worldMatrix = this._getWorldMatrix();
  21939. if (this.parent && this.parent.getWorldMatrix) {
  21940. if (!this._parentedWorldMatrix) {
  21941. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21942. }
  21943. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21944. this._markSyncedWithParent();
  21945. return this._parentedWorldMatrix;
  21946. }
  21947. return worldMatrix;
  21948. };
  21949. /**
  21950. * Sort function to order lights for rendering.
  21951. * @param a First Light object to compare to second.
  21952. * @param b Second Light object to compare first.
  21953. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21954. */
  21955. Light.CompareLightsPriority = function (a, b) {
  21956. //shadow-casting lights have priority over non-shadow-casting lights
  21957. //the renderPrioirty is a secondary sort criterion
  21958. if (a.shadowEnabled !== b.shadowEnabled) {
  21959. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21960. }
  21961. return b.renderPriority - a.renderPriority;
  21962. };
  21963. /**
  21964. * Releases resources associated with this node.
  21965. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21966. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21967. */
  21968. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21969. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21970. if (this._shadowGenerator) {
  21971. this._shadowGenerator.dispose();
  21972. this._shadowGenerator = null;
  21973. }
  21974. // Animations
  21975. this.getScene().stopAnimation(this);
  21976. // Remove from meshes
  21977. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21978. var mesh = _a[_i];
  21979. mesh._removeLightSource(this);
  21980. }
  21981. this._uniformBuffer.dispose();
  21982. // Remove from scene
  21983. this.getScene().removeLight(this);
  21984. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21985. };
  21986. /**
  21987. * Returns the light type ID (integer).
  21988. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21989. */
  21990. Light.prototype.getTypeID = function () {
  21991. return 0;
  21992. };
  21993. /**
  21994. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21995. * @returns the scaled intensity in intensity mode unit
  21996. */
  21997. Light.prototype.getScaledIntensity = function () {
  21998. return this._photometricScale * this.intensity;
  21999. };
  22000. /**
  22001. * Returns a new Light object, named "name", from the current one.
  22002. * @param name The name of the cloned light
  22003. * @returns the new created light
  22004. */
  22005. Light.prototype.clone = function (name) {
  22006. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22007. if (!constructor) {
  22008. return null;
  22009. }
  22010. return BABYLON.SerializationHelper.Clone(constructor, this);
  22011. };
  22012. /**
  22013. * Serializes the current light into a Serialization object.
  22014. * @returns the serialized object.
  22015. */
  22016. Light.prototype.serialize = function () {
  22017. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22018. // Type
  22019. serializationObject.type = this.getTypeID();
  22020. // Parent
  22021. if (this.parent) {
  22022. serializationObject.parentId = this.parent.id;
  22023. }
  22024. // Inclusion / exclusions
  22025. if (this.excludedMeshes.length > 0) {
  22026. serializationObject.excludedMeshesIds = [];
  22027. this.excludedMeshes.forEach(function (mesh) {
  22028. serializationObject.excludedMeshesIds.push(mesh.id);
  22029. });
  22030. }
  22031. if (this.includedOnlyMeshes.length > 0) {
  22032. serializationObject.includedOnlyMeshesIds = [];
  22033. this.includedOnlyMeshes.forEach(function (mesh) {
  22034. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22035. });
  22036. }
  22037. // Animations
  22038. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22039. serializationObject.ranges = this.serializeAnimationRanges();
  22040. return serializationObject;
  22041. };
  22042. /**
  22043. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22044. * This new light is named "name" and added to the passed scene.
  22045. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22046. * @param name The friendly name of the light
  22047. * @param scene The scene the new light will belong to
  22048. * @returns the constructor function
  22049. */
  22050. Light.GetConstructorFromName = function (type, name, scene) {
  22051. switch (type) {
  22052. case 0:
  22053. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  22054. case 1:
  22055. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  22056. case 2:
  22057. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  22058. case 3:
  22059. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  22060. }
  22061. return null;
  22062. };
  22063. /**
  22064. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22065. * @param parsedLight The JSON representation of the light
  22066. * @param scene The scene to create the parsed light in
  22067. * @returns the created light after parsing
  22068. */
  22069. Light.Parse = function (parsedLight, scene) {
  22070. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22071. if (!constructor) {
  22072. return null;
  22073. }
  22074. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22075. // Inclusion / exclusions
  22076. if (parsedLight.excludedMeshesIds) {
  22077. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22078. }
  22079. if (parsedLight.includedOnlyMeshesIds) {
  22080. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22081. }
  22082. // Parent
  22083. if (parsedLight.parentId) {
  22084. light._waitingParentId = parsedLight.parentId;
  22085. }
  22086. // Animations
  22087. if (parsedLight.animations) {
  22088. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22089. var parsedAnimation = parsedLight.animations[animationIndex];
  22090. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22091. }
  22092. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22093. }
  22094. if (parsedLight.autoAnimate) {
  22095. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22096. }
  22097. return light;
  22098. };
  22099. Light.prototype._hookArrayForExcluded = function (array) {
  22100. var _this = this;
  22101. var oldPush = array.push;
  22102. array.push = function () {
  22103. var items = [];
  22104. for (var _i = 0; _i < arguments.length; _i++) {
  22105. items[_i] = arguments[_i];
  22106. }
  22107. var result = oldPush.apply(array, items);
  22108. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22109. var item = items_1[_a];
  22110. item._resyncLighSource(_this);
  22111. }
  22112. return result;
  22113. };
  22114. var oldSplice = array.splice;
  22115. array.splice = function (index, deleteCount) {
  22116. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22117. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22118. var item = deleted_1[_i];
  22119. item._resyncLighSource(_this);
  22120. }
  22121. return deleted;
  22122. };
  22123. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22124. var item = array_1[_i];
  22125. item._resyncLighSource(this);
  22126. }
  22127. };
  22128. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22129. var _this = this;
  22130. var oldPush = array.push;
  22131. array.push = function () {
  22132. var items = [];
  22133. for (var _i = 0; _i < arguments.length; _i++) {
  22134. items[_i] = arguments[_i];
  22135. }
  22136. var result = oldPush.apply(array, items);
  22137. _this._resyncMeshes();
  22138. return result;
  22139. };
  22140. var oldSplice = array.splice;
  22141. array.splice = function (index, deleteCount) {
  22142. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22143. _this._resyncMeshes();
  22144. return deleted;
  22145. };
  22146. this._resyncMeshes();
  22147. };
  22148. Light.prototype._resyncMeshes = function () {
  22149. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22150. var mesh = _a[_i];
  22151. mesh._resyncLighSource(this);
  22152. }
  22153. };
  22154. /**
  22155. * Forces the meshes to update their light related information in their rendering used effects
  22156. * @hidden Internal Use Only
  22157. */
  22158. Light.prototype._markMeshesAsLightDirty = function () {
  22159. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22160. var mesh = _a[_i];
  22161. if (mesh._lightSources.indexOf(this) !== -1) {
  22162. mesh._markSubMeshesAsLightDirty();
  22163. }
  22164. }
  22165. };
  22166. /**
  22167. * Recomputes the cached photometric scale if needed.
  22168. */
  22169. Light.prototype._computePhotometricScale = function () {
  22170. this._photometricScale = this._getPhotometricScale();
  22171. this.getScene().resetCachedMaterial();
  22172. };
  22173. /**
  22174. * Returns the Photometric Scale according to the light type and intensity mode.
  22175. */
  22176. Light.prototype._getPhotometricScale = function () {
  22177. var photometricScale = 0.0;
  22178. var lightTypeID = this.getTypeID();
  22179. //get photometric mode
  22180. var photometricMode = this.intensityMode;
  22181. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22182. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22183. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22184. }
  22185. else {
  22186. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22187. }
  22188. }
  22189. //compute photometric scale
  22190. switch (lightTypeID) {
  22191. case Light.LIGHTTYPEID_POINTLIGHT:
  22192. case Light.LIGHTTYPEID_SPOTLIGHT:
  22193. switch (photometricMode) {
  22194. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22195. photometricScale = 1.0 / (4.0 * Math.PI);
  22196. break;
  22197. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22198. photometricScale = 1.0;
  22199. break;
  22200. case Light.INTENSITYMODE_LUMINANCE:
  22201. photometricScale = this.radius * this.radius;
  22202. break;
  22203. }
  22204. break;
  22205. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22206. switch (photometricMode) {
  22207. case Light.INTENSITYMODE_ILLUMINANCE:
  22208. photometricScale = 1.0;
  22209. break;
  22210. case Light.INTENSITYMODE_LUMINANCE:
  22211. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22212. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22213. var apexAngleRadians = this.radius;
  22214. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22215. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22216. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22217. photometricScale = solidAngle;
  22218. break;
  22219. }
  22220. break;
  22221. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22222. // No fall off in hemisperic light.
  22223. photometricScale = 1.0;
  22224. break;
  22225. }
  22226. return photometricScale;
  22227. };
  22228. /**
  22229. * Reorder the light in the scene according to their defined priority.
  22230. * @hidden Internal Use Only
  22231. */
  22232. Light.prototype._reorderLightsInScene = function () {
  22233. var scene = this.getScene();
  22234. if (this._renderPriority != 0) {
  22235. scene.requireLightSorting = true;
  22236. }
  22237. this.getScene().sortLightsByPriority();
  22238. };
  22239. //lightmapMode Consts
  22240. Light._LIGHTMAP_DEFAULT = 0;
  22241. Light._LIGHTMAP_SPECULAR = 1;
  22242. Light._LIGHTMAP_SHADOWSONLY = 2;
  22243. // Intensity Mode Consts
  22244. Light._INTENSITYMODE_AUTOMATIC = 0;
  22245. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22246. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22247. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22248. Light._INTENSITYMODE_LUMINANCE = 4;
  22249. // Light types ids const.
  22250. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22251. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22252. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22253. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22254. __decorate([
  22255. BABYLON.serializeAsColor3()
  22256. ], Light.prototype, "diffuse", void 0);
  22257. __decorate([
  22258. BABYLON.serializeAsColor3()
  22259. ], Light.prototype, "specular", void 0);
  22260. __decorate([
  22261. BABYLON.serialize()
  22262. ], Light.prototype, "intensity", void 0);
  22263. __decorate([
  22264. BABYLON.serialize()
  22265. ], Light.prototype, "range", void 0);
  22266. __decorate([
  22267. BABYLON.serialize()
  22268. ], Light.prototype, "intensityMode", null);
  22269. __decorate([
  22270. BABYLON.serialize()
  22271. ], Light.prototype, "radius", null);
  22272. __decorate([
  22273. BABYLON.serialize()
  22274. ], Light.prototype, "_renderPriority", void 0);
  22275. __decorate([
  22276. BABYLON.expandToProperty("_reorderLightsInScene")
  22277. ], Light.prototype, "renderPriority", void 0);
  22278. __decorate([
  22279. BABYLON.serialize("shadowEnabled")
  22280. ], Light.prototype, "_shadowEnabled", void 0);
  22281. __decorate([
  22282. BABYLON.serialize("excludeWithLayerMask")
  22283. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22284. __decorate([
  22285. BABYLON.serialize("includeOnlyWithLayerMask")
  22286. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22287. __decorate([
  22288. BABYLON.serialize("lightmapMode")
  22289. ], Light.prototype, "_lightmapMode", void 0);
  22290. return Light;
  22291. }(BABYLON.Node));
  22292. BABYLON.Light = Light;
  22293. })(BABYLON || (BABYLON = {}));
  22294. //# sourceMappingURL=babylon.light.js.map
  22295. var BABYLON;
  22296. (function (BABYLON) {
  22297. var Camera = /** @class */ (function (_super) {
  22298. __extends(Camera, _super);
  22299. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22300. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22301. var _this = _super.call(this, name, scene) || this;
  22302. /**
  22303. * The vector the camera should consider as up.
  22304. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22305. */
  22306. _this.upVector = BABYLON.Vector3.Up();
  22307. _this.orthoLeft = null;
  22308. _this.orthoRight = null;
  22309. _this.orthoBottom = null;
  22310. _this.orthoTop = null;
  22311. /**
  22312. * FOV is set in Radians. (default is 0.8)
  22313. */
  22314. _this.fov = 0.8;
  22315. _this.minZ = 1;
  22316. _this.maxZ = 10000.0;
  22317. _this.inertia = 0.9;
  22318. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22319. _this.isIntermediate = false;
  22320. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22321. /**
  22322. * Restricts the camera to viewing objects with the same layerMask.
  22323. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22324. */
  22325. _this.layerMask = 0x0FFFFFFF;
  22326. /**
  22327. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22328. */
  22329. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22330. // Camera rig members
  22331. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22332. _this._rigCameras = new Array();
  22333. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22334. _this._skipRendering = false;
  22335. _this.customRenderTargets = new Array();
  22336. // Observables
  22337. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22338. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22339. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22340. _this.onRestoreStateObservable = new BABYLON.Observable();
  22341. // Cache
  22342. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22343. _this._projectionMatrix = new BABYLON.Matrix();
  22344. _this._doNotComputeProjectionMatrix = false;
  22345. _this._worldMatrix = BABYLON.Matrix.Identity();
  22346. _this._postProcesses = new Array();
  22347. _this._transformMatrix = BABYLON.Matrix.Zero();
  22348. _this._activeMeshes = new BABYLON.SmartArray(256);
  22349. _this._globalPosition = BABYLON.Vector3.Zero();
  22350. _this._refreshFrustumPlanes = true;
  22351. _this.getScene().addCamera(_this);
  22352. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22353. _this.getScene().activeCamera = _this;
  22354. }
  22355. _this.position = position;
  22356. return _this;
  22357. }
  22358. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22359. get: function () {
  22360. return Camera._PERSPECTIVE_CAMERA;
  22361. },
  22362. enumerable: true,
  22363. configurable: true
  22364. });
  22365. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22366. get: function () {
  22367. return Camera._ORTHOGRAPHIC_CAMERA;
  22368. },
  22369. enumerable: true,
  22370. configurable: true
  22371. });
  22372. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22373. /**
  22374. * This is the default FOV mode for perspective cameras.
  22375. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22376. *
  22377. */
  22378. get: function () {
  22379. return Camera._FOVMODE_VERTICAL_FIXED;
  22380. },
  22381. enumerable: true,
  22382. configurable: true
  22383. });
  22384. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22385. /**
  22386. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22387. *
  22388. */
  22389. get: function () {
  22390. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22391. },
  22392. enumerable: true,
  22393. configurable: true
  22394. });
  22395. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22396. get: function () {
  22397. return Camera._RIG_MODE_NONE;
  22398. },
  22399. enumerable: true,
  22400. configurable: true
  22401. });
  22402. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22403. get: function () {
  22404. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22405. },
  22406. enumerable: true,
  22407. configurable: true
  22408. });
  22409. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22410. get: function () {
  22411. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22412. },
  22413. enumerable: true,
  22414. configurable: true
  22415. });
  22416. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22417. get: function () {
  22418. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22419. },
  22420. enumerable: true,
  22421. configurable: true
  22422. });
  22423. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22424. get: function () {
  22425. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22426. },
  22427. enumerable: true,
  22428. configurable: true
  22429. });
  22430. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22431. get: function () {
  22432. return Camera._RIG_MODE_VR;
  22433. },
  22434. enumerable: true,
  22435. configurable: true
  22436. });
  22437. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22438. get: function () {
  22439. return Camera._RIG_MODE_WEBVR;
  22440. },
  22441. enumerable: true,
  22442. configurable: true
  22443. });
  22444. /**
  22445. * Store current camera state (fov, position, etc..)
  22446. */
  22447. Camera.prototype.storeState = function () {
  22448. this._stateStored = true;
  22449. this._storedFov = this.fov;
  22450. return this;
  22451. };
  22452. /**
  22453. * Restores the camera state values if it has been stored. You must call storeState() first
  22454. */
  22455. Camera.prototype._restoreStateValues = function () {
  22456. if (!this._stateStored) {
  22457. return false;
  22458. }
  22459. this.fov = this._storedFov;
  22460. return true;
  22461. };
  22462. /**
  22463. * Restored camera state. You must call storeState() first
  22464. */
  22465. Camera.prototype.restoreState = function () {
  22466. if (this._restoreStateValues()) {
  22467. this.onRestoreStateObservable.notifyObservers(this);
  22468. return true;
  22469. }
  22470. return false;
  22471. };
  22472. Camera.prototype.getClassName = function () {
  22473. return "Camera";
  22474. };
  22475. /**
  22476. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22477. */
  22478. Camera.prototype.toString = function (fullDetails) {
  22479. var ret = "Name: " + this.name;
  22480. ret += ", type: " + this.getClassName();
  22481. if (this.animations) {
  22482. for (var i = 0; i < this.animations.length; i++) {
  22483. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22484. }
  22485. }
  22486. if (fullDetails) {
  22487. }
  22488. return ret;
  22489. };
  22490. Object.defineProperty(Camera.prototype, "globalPosition", {
  22491. get: function () {
  22492. return this._globalPosition;
  22493. },
  22494. enumerable: true,
  22495. configurable: true
  22496. });
  22497. Camera.prototype.getActiveMeshes = function () {
  22498. return this._activeMeshes;
  22499. };
  22500. Camera.prototype.isActiveMesh = function (mesh) {
  22501. return (this._activeMeshes.indexOf(mesh) !== -1);
  22502. };
  22503. /**
  22504. * Is this camera ready to be used/rendered
  22505. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22506. * @return true if the camera is ready
  22507. */
  22508. Camera.prototype.isReady = function (completeCheck) {
  22509. if (completeCheck === void 0) { completeCheck = false; }
  22510. if (completeCheck) {
  22511. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22512. var pp = _a[_i];
  22513. if (pp && !pp.isReady()) {
  22514. return false;
  22515. }
  22516. }
  22517. }
  22518. return _super.prototype.isReady.call(this, completeCheck);
  22519. };
  22520. //Cache
  22521. Camera.prototype._initCache = function () {
  22522. _super.prototype._initCache.call(this);
  22523. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22524. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22525. this._cache.mode = undefined;
  22526. this._cache.minZ = undefined;
  22527. this._cache.maxZ = undefined;
  22528. this._cache.fov = undefined;
  22529. this._cache.fovMode = undefined;
  22530. this._cache.aspectRatio = undefined;
  22531. this._cache.orthoLeft = undefined;
  22532. this._cache.orthoRight = undefined;
  22533. this._cache.orthoBottom = undefined;
  22534. this._cache.orthoTop = undefined;
  22535. this._cache.renderWidth = undefined;
  22536. this._cache.renderHeight = undefined;
  22537. };
  22538. Camera.prototype._updateCache = function (ignoreParentClass) {
  22539. if (!ignoreParentClass) {
  22540. _super.prototype._updateCache.call(this);
  22541. }
  22542. this._cache.position.copyFrom(this.position);
  22543. this._cache.upVector.copyFrom(this.upVector);
  22544. };
  22545. // Synchronized
  22546. Camera.prototype._isSynchronized = function () {
  22547. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22548. };
  22549. Camera.prototype._isSynchronizedViewMatrix = function () {
  22550. if (!_super.prototype._isSynchronized.call(this))
  22551. return false;
  22552. return this._cache.position.equals(this.position)
  22553. && this._cache.upVector.equals(this.upVector)
  22554. && this.isSynchronizedWithParent();
  22555. };
  22556. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22557. var check = this._cache.mode === this.mode
  22558. && this._cache.minZ === this.minZ
  22559. && this._cache.maxZ === this.maxZ;
  22560. if (!check) {
  22561. return false;
  22562. }
  22563. var engine = this.getEngine();
  22564. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22565. check = this._cache.fov === this.fov
  22566. && this._cache.fovMode === this.fovMode
  22567. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22568. }
  22569. else {
  22570. check = this._cache.orthoLeft === this.orthoLeft
  22571. && this._cache.orthoRight === this.orthoRight
  22572. && this._cache.orthoBottom === this.orthoBottom
  22573. && this._cache.orthoTop === this.orthoTop
  22574. && this._cache.renderWidth === engine.getRenderWidth()
  22575. && this._cache.renderHeight === engine.getRenderHeight();
  22576. }
  22577. return check;
  22578. };
  22579. // Controls
  22580. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22581. };
  22582. Camera.prototype.detachControl = function (element) {
  22583. };
  22584. Camera.prototype.update = function () {
  22585. this._checkInputs();
  22586. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22587. this._updateRigCameras();
  22588. }
  22589. };
  22590. Camera.prototype._checkInputs = function () {
  22591. this.onAfterCheckInputsObservable.notifyObservers(this);
  22592. };
  22593. Object.defineProperty(Camera.prototype, "rigCameras", {
  22594. get: function () {
  22595. return this._rigCameras;
  22596. },
  22597. enumerable: true,
  22598. configurable: true
  22599. });
  22600. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22601. get: function () {
  22602. return this._rigPostProcess;
  22603. },
  22604. enumerable: true,
  22605. configurable: true
  22606. });
  22607. /**
  22608. * Internal, gets the first post proces.
  22609. * @returns the first post process to be run on this camera.
  22610. */
  22611. Camera.prototype._getFirstPostProcess = function () {
  22612. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22613. if (this._postProcesses[ppIndex] !== null) {
  22614. return this._postProcesses[ppIndex];
  22615. }
  22616. }
  22617. return null;
  22618. };
  22619. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22620. // invalidate framebuffer
  22621. var firstPostProcess = this._getFirstPostProcess();
  22622. if (firstPostProcess) {
  22623. firstPostProcess.markTextureDirty();
  22624. }
  22625. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22626. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22627. var cam = this._rigCameras[i];
  22628. var rigPostProcess = cam._rigPostProcess;
  22629. // for VR rig, there does not have to be a post process
  22630. if (rigPostProcess) {
  22631. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22632. if (isPass) {
  22633. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22634. cam.isIntermediate = this._postProcesses.length === 0;
  22635. }
  22636. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22637. rigPostProcess.markTextureDirty();
  22638. }
  22639. else {
  22640. cam._postProcesses = this._postProcesses.slice(0);
  22641. }
  22642. }
  22643. };
  22644. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22645. if (insertAt === void 0) { insertAt = null; }
  22646. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22647. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22648. return 0;
  22649. }
  22650. if (insertAt == null || insertAt < 0) {
  22651. this._postProcesses.push(postProcess);
  22652. }
  22653. else if (this._postProcesses[insertAt] === null) {
  22654. this._postProcesses[insertAt] = postProcess;
  22655. }
  22656. else {
  22657. this._postProcesses.splice(insertAt, 0, postProcess);
  22658. }
  22659. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22660. return this._postProcesses.indexOf(postProcess);
  22661. };
  22662. Camera.prototype.detachPostProcess = function (postProcess) {
  22663. var idx = this._postProcesses.indexOf(postProcess);
  22664. if (idx !== -1) {
  22665. this._postProcesses[idx] = null;
  22666. }
  22667. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22668. };
  22669. Camera.prototype.getWorldMatrix = function () {
  22670. if (this._isSynchronizedViewMatrix()) {
  22671. return this._worldMatrix;
  22672. }
  22673. // Getting the the view matrix will also compute the world matrix.
  22674. this.getViewMatrix();
  22675. return this._worldMatrix;
  22676. };
  22677. Camera.prototype._getViewMatrix = function () {
  22678. return BABYLON.Matrix.Identity();
  22679. };
  22680. Camera.prototype.getViewMatrix = function (force) {
  22681. if (!force && this._isSynchronizedViewMatrix()) {
  22682. return this._computedViewMatrix;
  22683. }
  22684. this.updateCache();
  22685. this._computedViewMatrix = this._getViewMatrix();
  22686. this._currentRenderId = this.getScene().getRenderId();
  22687. this._childRenderId = this._currentRenderId;
  22688. this._refreshFrustumPlanes = true;
  22689. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22690. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22691. }
  22692. this.onViewMatrixChangedObservable.notifyObservers(this);
  22693. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22694. return this._computedViewMatrix;
  22695. };
  22696. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22697. this._doNotComputeProjectionMatrix = true;
  22698. if (projection !== undefined) {
  22699. this._projectionMatrix = projection;
  22700. }
  22701. };
  22702. ;
  22703. Camera.prototype.unfreezeProjectionMatrix = function () {
  22704. this._doNotComputeProjectionMatrix = false;
  22705. };
  22706. ;
  22707. Camera.prototype.getProjectionMatrix = function (force) {
  22708. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22709. return this._projectionMatrix;
  22710. }
  22711. // Cache
  22712. this._cache.mode = this.mode;
  22713. this._cache.minZ = this.minZ;
  22714. this._cache.maxZ = this.maxZ;
  22715. // Matrix
  22716. this._refreshFrustumPlanes = true;
  22717. var engine = this.getEngine();
  22718. var scene = this.getScene();
  22719. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22720. this._cache.fov = this.fov;
  22721. this._cache.fovMode = this.fovMode;
  22722. this._cache.aspectRatio = engine.getAspectRatio(this);
  22723. if (this.minZ <= 0) {
  22724. this.minZ = 0.1;
  22725. }
  22726. if (scene.useRightHandedSystem) {
  22727. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22728. }
  22729. else {
  22730. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22731. }
  22732. }
  22733. else {
  22734. var halfWidth = engine.getRenderWidth() / 2.0;
  22735. var halfHeight = engine.getRenderHeight() / 2.0;
  22736. if (scene.useRightHandedSystem) {
  22737. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22738. }
  22739. else {
  22740. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22741. }
  22742. this._cache.orthoLeft = this.orthoLeft;
  22743. this._cache.orthoRight = this.orthoRight;
  22744. this._cache.orthoBottom = this.orthoBottom;
  22745. this._cache.orthoTop = this.orthoTop;
  22746. this._cache.renderWidth = engine.getRenderWidth();
  22747. this._cache.renderHeight = engine.getRenderHeight();
  22748. }
  22749. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22750. return this._projectionMatrix;
  22751. };
  22752. Camera.prototype.getTranformationMatrix = function () {
  22753. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22754. return this._transformMatrix;
  22755. };
  22756. Camera.prototype.updateFrustumPlanes = function () {
  22757. if (!this._refreshFrustumPlanes) {
  22758. return;
  22759. }
  22760. this.getTranformationMatrix();
  22761. if (!this._frustumPlanes) {
  22762. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22763. }
  22764. else {
  22765. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22766. }
  22767. this._refreshFrustumPlanes = false;
  22768. };
  22769. Camera.prototype.isInFrustum = function (target) {
  22770. this.updateFrustumPlanes();
  22771. return target.isInFrustum(this._frustumPlanes);
  22772. };
  22773. Camera.prototype.isCompletelyInFrustum = function (target) {
  22774. this.updateFrustumPlanes();
  22775. return target.isCompletelyInFrustum(this._frustumPlanes);
  22776. };
  22777. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22778. if (length === void 0) { length = 100; }
  22779. if (!transform) {
  22780. transform = this.getWorldMatrix();
  22781. }
  22782. if (!origin) {
  22783. origin = this.position;
  22784. }
  22785. var forward = new BABYLON.Vector3(0, 0, 1);
  22786. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22787. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22788. return new BABYLON.Ray(origin, direction, length);
  22789. };
  22790. /**
  22791. * Releases resources associated with this node.
  22792. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22793. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22794. */
  22795. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22796. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22797. // Observables
  22798. this.onViewMatrixChangedObservable.clear();
  22799. this.onProjectionMatrixChangedObservable.clear();
  22800. this.onAfterCheckInputsObservable.clear();
  22801. this.onRestoreStateObservable.clear();
  22802. // Inputs
  22803. if (this.inputs) {
  22804. this.inputs.clear();
  22805. }
  22806. // Animations
  22807. this.getScene().stopAnimation(this);
  22808. // Remove from scene
  22809. this.getScene().removeCamera(this);
  22810. while (this._rigCameras.length > 0) {
  22811. var camera = this._rigCameras.pop();
  22812. if (camera) {
  22813. camera.dispose();
  22814. }
  22815. }
  22816. // Postprocesses
  22817. if (this._rigPostProcess) {
  22818. this._rigPostProcess.dispose(this);
  22819. this._rigPostProcess = null;
  22820. this._postProcesses = [];
  22821. }
  22822. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22823. this._rigPostProcess = null;
  22824. this._postProcesses = [];
  22825. }
  22826. else {
  22827. var i = this._postProcesses.length;
  22828. while (--i >= 0) {
  22829. var postProcess = this._postProcesses[i];
  22830. if (postProcess) {
  22831. postProcess.dispose(this);
  22832. }
  22833. }
  22834. }
  22835. // Render targets
  22836. var i = this.customRenderTargets.length;
  22837. while (--i >= 0) {
  22838. this.customRenderTargets[i].dispose();
  22839. }
  22840. this.customRenderTargets = [];
  22841. // Active Meshes
  22842. this._activeMeshes.dispose();
  22843. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22844. };
  22845. Object.defineProperty(Camera.prototype, "leftCamera", {
  22846. // ---- Camera rigs section ----
  22847. get: function () {
  22848. if (this._rigCameras.length < 1) {
  22849. return null;
  22850. }
  22851. return this._rigCameras[0];
  22852. },
  22853. enumerable: true,
  22854. configurable: true
  22855. });
  22856. Object.defineProperty(Camera.prototype, "rightCamera", {
  22857. get: function () {
  22858. if (this._rigCameras.length < 2) {
  22859. return null;
  22860. }
  22861. return this._rigCameras[1];
  22862. },
  22863. enumerable: true,
  22864. configurable: true
  22865. });
  22866. Camera.prototype.getLeftTarget = function () {
  22867. if (this._rigCameras.length < 1) {
  22868. return null;
  22869. }
  22870. return this._rigCameras[0].getTarget();
  22871. };
  22872. Camera.prototype.getRightTarget = function () {
  22873. if (this._rigCameras.length < 2) {
  22874. return null;
  22875. }
  22876. return this._rigCameras[1].getTarget();
  22877. };
  22878. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22879. if (this.cameraRigMode === mode) {
  22880. return;
  22881. }
  22882. while (this._rigCameras.length > 0) {
  22883. var camera = this._rigCameras.pop();
  22884. if (camera) {
  22885. camera.dispose();
  22886. }
  22887. }
  22888. this.cameraRigMode = mode;
  22889. this._cameraRigParams = {};
  22890. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22891. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22892. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22893. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22894. // create the rig cameras, unless none
  22895. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22896. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22897. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22898. if (leftCamera && rightCamera) {
  22899. this._rigCameras.push(leftCamera);
  22900. this._rigCameras.push(rightCamera);
  22901. }
  22902. }
  22903. switch (this.cameraRigMode) {
  22904. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22905. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22906. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22907. break;
  22908. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22909. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22910. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22911. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22912. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22913. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22914. break;
  22915. case Camera.RIG_MODE_VR:
  22916. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22917. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22918. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22919. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22920. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22921. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22922. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22923. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22924. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22925. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22926. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22927. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22928. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22929. if (metrics.compensateDistortion) {
  22930. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22931. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22932. }
  22933. break;
  22934. case Camera.RIG_MODE_WEBVR:
  22935. if (rigParams.vrDisplay) {
  22936. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22937. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22938. //Left eye
  22939. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22940. this._rigCameras[0].setCameraRigParameter("left", true);
  22941. //leaving this for future reference
  22942. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22943. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22944. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22945. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22946. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22947. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22948. this._rigCameras[0].parent = this;
  22949. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22950. //Right eye
  22951. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22952. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22953. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22954. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22955. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22956. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22957. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22958. this._rigCameras[1].parent = this;
  22959. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22960. if (Camera.UseAlternateWebVRRendering) {
  22961. this._rigCameras[1]._skipRendering = true;
  22962. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22963. }
  22964. }
  22965. break;
  22966. }
  22967. this._cascadePostProcessesToRigCams();
  22968. this.update();
  22969. };
  22970. Camera.prototype._getVRProjectionMatrix = function () {
  22971. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22972. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22973. return this._projectionMatrix;
  22974. };
  22975. Camera.prototype._updateCameraRotationMatrix = function () {
  22976. //Here for WebVR
  22977. };
  22978. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22979. //Here for WebVR
  22980. };
  22981. /**
  22982. * This function MUST be overwritten by the different WebVR cameras available.
  22983. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22984. */
  22985. Camera.prototype._getWebVRProjectionMatrix = function () {
  22986. return BABYLON.Matrix.Identity();
  22987. };
  22988. /**
  22989. * This function MUST be overwritten by the different WebVR cameras available.
  22990. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22991. */
  22992. Camera.prototype._getWebVRViewMatrix = function () {
  22993. return BABYLON.Matrix.Identity();
  22994. };
  22995. Camera.prototype.setCameraRigParameter = function (name, value) {
  22996. if (!this._cameraRigParams) {
  22997. this._cameraRigParams = {};
  22998. }
  22999. this._cameraRigParams[name] = value;
  23000. //provisionnally:
  23001. if (name === "interaxialDistance") {
  23002. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23003. }
  23004. };
  23005. /**
  23006. * needs to be overridden by children so sub has required properties to be copied
  23007. */
  23008. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23009. return null;
  23010. };
  23011. /**
  23012. * May need to be overridden by children
  23013. */
  23014. Camera.prototype._updateRigCameras = function () {
  23015. for (var i = 0; i < this._rigCameras.length; i++) {
  23016. this._rigCameras[i].minZ = this.minZ;
  23017. this._rigCameras[i].maxZ = this.maxZ;
  23018. this._rigCameras[i].fov = this.fov;
  23019. }
  23020. // only update viewport when ANAGLYPH
  23021. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23022. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23023. }
  23024. };
  23025. Camera.prototype._setupInputs = function () {
  23026. };
  23027. Camera.prototype.serialize = function () {
  23028. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23029. // Type
  23030. serializationObject.type = this.getClassName();
  23031. // Parent
  23032. if (this.parent) {
  23033. serializationObject.parentId = this.parent.id;
  23034. }
  23035. if (this.inputs) {
  23036. this.inputs.serialize(serializationObject);
  23037. }
  23038. // Animations
  23039. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23040. serializationObject.ranges = this.serializeAnimationRanges();
  23041. return serializationObject;
  23042. };
  23043. Camera.prototype.clone = function (name) {
  23044. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23045. };
  23046. Camera.prototype.getDirection = function (localAxis) {
  23047. var result = BABYLON.Vector3.Zero();
  23048. this.getDirectionToRef(localAxis, result);
  23049. return result;
  23050. };
  23051. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23052. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23053. };
  23054. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23055. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23056. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23057. switch (type) {
  23058. case "ArcRotateCamera":
  23059. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  23060. case "DeviceOrientationCamera":
  23061. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  23062. case "FollowCamera":
  23063. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  23064. case "ArcFollowCamera":
  23065. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  23066. case "GamepadCamera":
  23067. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23068. case "TouchCamera":
  23069. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  23070. case "VirtualJoysticksCamera":
  23071. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  23072. case "WebVRFreeCamera":
  23073. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23074. case "WebVRGamepadCamera":
  23075. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23076. case "VRDeviceOrientationFreeCamera":
  23077. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23078. case "VRDeviceOrientationGamepadCamera":
  23079. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23080. case "AnaglyphArcRotateCamera":
  23081. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23082. case "AnaglyphFreeCamera":
  23083. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23084. case "AnaglyphGamepadCamera":
  23085. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23086. case "AnaglyphUniversalCamera":
  23087. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23088. case "StereoscopicArcRotateCamera":
  23089. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23090. case "StereoscopicFreeCamera":
  23091. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23092. case "StereoscopicGamepadCamera":
  23093. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23094. case "StereoscopicUniversalCamera":
  23095. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23096. case "FreeCamera": // Forcing Universal here
  23097. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23098. default: // Universal Camera is the default value
  23099. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23100. }
  23101. };
  23102. Camera.prototype.computeWorldMatrix = function () {
  23103. return this.getWorldMatrix();
  23104. };
  23105. Camera.Parse = function (parsedCamera, scene) {
  23106. var type = parsedCamera.type;
  23107. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23108. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23109. // Parent
  23110. if (parsedCamera.parentId) {
  23111. camera._waitingParentId = parsedCamera.parentId;
  23112. }
  23113. //If camera has an input manager, let it parse inputs settings
  23114. if (camera.inputs) {
  23115. camera.inputs.parse(parsedCamera);
  23116. camera._setupInputs();
  23117. }
  23118. if (camera.setPosition) { // need to force position
  23119. camera.position.copyFromFloats(0, 0, 0);
  23120. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23121. }
  23122. // Target
  23123. if (parsedCamera.target) {
  23124. if (camera.setTarget) {
  23125. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23126. }
  23127. }
  23128. // Apply 3d rig, when found
  23129. if (parsedCamera.cameraRigMode) {
  23130. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23131. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23132. }
  23133. // Animations
  23134. if (parsedCamera.animations) {
  23135. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23136. var parsedAnimation = parsedCamera.animations[animationIndex];
  23137. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23138. }
  23139. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23140. }
  23141. if (parsedCamera.autoAnimate) {
  23142. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23143. }
  23144. return camera;
  23145. };
  23146. // Statics
  23147. Camera._PERSPECTIVE_CAMERA = 0;
  23148. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23149. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23150. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23151. Camera._RIG_MODE_NONE = 0;
  23152. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23153. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23154. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23155. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23156. Camera._RIG_MODE_VR = 20;
  23157. Camera._RIG_MODE_WEBVR = 21;
  23158. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23159. Camera.UseAlternateWebVRRendering = false;
  23160. __decorate([
  23161. BABYLON.serializeAsVector3()
  23162. ], Camera.prototype, "position", void 0);
  23163. __decorate([
  23164. BABYLON.serializeAsVector3()
  23165. ], Camera.prototype, "upVector", void 0);
  23166. __decorate([
  23167. BABYLON.serialize()
  23168. ], Camera.prototype, "orthoLeft", void 0);
  23169. __decorate([
  23170. BABYLON.serialize()
  23171. ], Camera.prototype, "orthoRight", void 0);
  23172. __decorate([
  23173. BABYLON.serialize()
  23174. ], Camera.prototype, "orthoBottom", void 0);
  23175. __decorate([
  23176. BABYLON.serialize()
  23177. ], Camera.prototype, "orthoTop", void 0);
  23178. __decorate([
  23179. BABYLON.serialize()
  23180. ], Camera.prototype, "fov", void 0);
  23181. __decorate([
  23182. BABYLON.serialize()
  23183. ], Camera.prototype, "minZ", void 0);
  23184. __decorate([
  23185. BABYLON.serialize()
  23186. ], Camera.prototype, "maxZ", void 0);
  23187. __decorate([
  23188. BABYLON.serialize()
  23189. ], Camera.prototype, "inertia", void 0);
  23190. __decorate([
  23191. BABYLON.serialize()
  23192. ], Camera.prototype, "mode", void 0);
  23193. __decorate([
  23194. BABYLON.serialize()
  23195. ], Camera.prototype, "layerMask", void 0);
  23196. __decorate([
  23197. BABYLON.serialize()
  23198. ], Camera.prototype, "fovMode", void 0);
  23199. __decorate([
  23200. BABYLON.serialize()
  23201. ], Camera.prototype, "cameraRigMode", void 0);
  23202. __decorate([
  23203. BABYLON.serialize()
  23204. ], Camera.prototype, "interaxialDistance", void 0);
  23205. __decorate([
  23206. BABYLON.serialize()
  23207. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23208. return Camera;
  23209. }(BABYLON.Node));
  23210. BABYLON.Camera = Camera;
  23211. })(BABYLON || (BABYLON = {}));
  23212. //# sourceMappingURL=babylon.camera.js.map
  23213. var BABYLON;
  23214. (function (BABYLON) {
  23215. var RenderingManager = /** @class */ (function () {
  23216. function RenderingManager(scene) {
  23217. this._renderingGroups = new Array();
  23218. this._autoClearDepthStencil = {};
  23219. this._customOpaqueSortCompareFn = {};
  23220. this._customAlphaTestSortCompareFn = {};
  23221. this._customTransparentSortCompareFn = {};
  23222. this._renderinGroupInfo = null;
  23223. this._scene = scene;
  23224. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23225. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23226. }
  23227. }
  23228. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23229. if (depth === void 0) { depth = true; }
  23230. if (stencil === void 0) { stencil = true; }
  23231. if (this._depthStencilBufferAlreadyCleaned) {
  23232. return;
  23233. }
  23234. this._scene.getEngine().clear(null, false, depth, stencil);
  23235. this._depthStencilBufferAlreadyCleaned = true;
  23236. };
  23237. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23238. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23239. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23240. var info = null;
  23241. if (observable) {
  23242. if (!this._renderinGroupInfo) {
  23243. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23244. }
  23245. info = this._renderinGroupInfo;
  23246. info.scene = this._scene;
  23247. info.camera = this._scene.activeCamera;
  23248. }
  23249. // Dispatch sprites
  23250. if (renderSprites) {
  23251. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23252. var manager = this._scene.spriteManagers[index];
  23253. this.dispatchSprites(manager);
  23254. }
  23255. }
  23256. // Render
  23257. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23258. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23259. var renderingGroup = this._renderingGroups[index];
  23260. if (!renderingGroup && !observable)
  23261. continue;
  23262. var renderingGroupMask = 0;
  23263. // Fire PRECLEAR stage
  23264. if (observable && info) {
  23265. renderingGroupMask = Math.pow(2, index);
  23266. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23267. info.renderingGroupId = index;
  23268. observable.notifyObservers(info, renderingGroupMask);
  23269. }
  23270. // Clear depth/stencil if needed
  23271. if (RenderingManager.AUTOCLEAR) {
  23272. var autoClear = this._autoClearDepthStencil[index];
  23273. if (autoClear && autoClear.autoClear) {
  23274. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23275. }
  23276. }
  23277. if (observable && info) {
  23278. // Fire PREOPAQUE stage
  23279. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23280. observable.notifyObservers(info, renderingGroupMask);
  23281. // Fire PRETRANSPARENT stage
  23282. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23283. observable.notifyObservers(info, renderingGroupMask);
  23284. }
  23285. if (renderingGroup)
  23286. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23287. // Fire POSTTRANSPARENT stage
  23288. if (observable && info) {
  23289. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23290. observable.notifyObservers(info, renderingGroupMask);
  23291. }
  23292. }
  23293. };
  23294. RenderingManager.prototype.reset = function () {
  23295. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23296. var renderingGroup = this._renderingGroups[index];
  23297. if (renderingGroup) {
  23298. renderingGroup.prepare();
  23299. }
  23300. }
  23301. };
  23302. RenderingManager.prototype.dispose = function () {
  23303. this.freeRenderingGroups();
  23304. this._renderingGroups.length = 0;
  23305. };
  23306. /**
  23307. * Clear the info related to rendering groups preventing retention points during dispose.
  23308. */
  23309. RenderingManager.prototype.freeRenderingGroups = function () {
  23310. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23311. var renderingGroup = this._renderingGroups[index];
  23312. if (renderingGroup) {
  23313. renderingGroup.dispose();
  23314. }
  23315. }
  23316. };
  23317. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23318. if (this._renderingGroups[renderingGroupId] === undefined) {
  23319. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23320. }
  23321. };
  23322. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23323. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23324. this._prepareRenderingGroup(renderingGroupId);
  23325. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23326. };
  23327. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23328. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23329. this._prepareRenderingGroup(renderingGroupId);
  23330. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23331. };
  23332. /**
  23333. * @param subMesh The submesh to dispatch
  23334. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23335. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23336. */
  23337. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23338. if (mesh === undefined) {
  23339. mesh = subMesh.getMesh();
  23340. }
  23341. var renderingGroupId = mesh.renderingGroupId || 0;
  23342. this._prepareRenderingGroup(renderingGroupId);
  23343. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23344. };
  23345. /**
  23346. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23347. * This allowed control for front to back rendering or reversly depending of the special needs.
  23348. *
  23349. * @param renderingGroupId The rendering group id corresponding to its index
  23350. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23351. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23352. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23353. */
  23354. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23355. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23356. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23357. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23358. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23359. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23360. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23361. if (this._renderingGroups[renderingGroupId]) {
  23362. var group = this._renderingGroups[renderingGroupId];
  23363. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23364. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23365. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23366. }
  23367. };
  23368. /**
  23369. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23370. *
  23371. * @param renderingGroupId The rendering group id corresponding to its index
  23372. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23373. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23374. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23375. */
  23376. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23377. if (depth === void 0) { depth = true; }
  23378. if (stencil === void 0) { stencil = true; }
  23379. this._autoClearDepthStencil[renderingGroupId] = {
  23380. autoClear: autoClearDepthStencil,
  23381. depth: depth,
  23382. stencil: stencil
  23383. };
  23384. };
  23385. /**
  23386. * The max id used for rendering groups (not included)
  23387. */
  23388. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23389. /**
  23390. * The min id used for rendering groups (included)
  23391. */
  23392. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23393. /**
  23394. * Used to globally prevent autoclearing scenes.
  23395. */
  23396. RenderingManager.AUTOCLEAR = true;
  23397. return RenderingManager;
  23398. }());
  23399. BABYLON.RenderingManager = RenderingManager;
  23400. })(BABYLON || (BABYLON = {}));
  23401. //# sourceMappingURL=babylon.renderingManager.js.map
  23402. var BABYLON;
  23403. (function (BABYLON) {
  23404. var RenderingGroup = /** @class */ (function () {
  23405. /**
  23406. * Creates a new rendering group.
  23407. * @param index The rendering group index
  23408. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23409. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23410. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23411. */
  23412. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23413. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23414. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23415. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23416. this.index = index;
  23417. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23418. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23419. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23420. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23421. this._particleSystems = new BABYLON.SmartArray(256);
  23422. this._spriteManagers = new BABYLON.SmartArray(256);
  23423. this._edgesRenderers = new BABYLON.SmartArray(16);
  23424. this._scene = scene;
  23425. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23426. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23427. this.transparentSortCompareFn = transparentSortCompareFn;
  23428. }
  23429. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23430. /**
  23431. * Set the opaque sort comparison function.
  23432. * If null the sub meshes will be render in the order they were created
  23433. */
  23434. set: function (value) {
  23435. this._opaqueSortCompareFn = value;
  23436. if (value) {
  23437. this._renderOpaque = this.renderOpaqueSorted;
  23438. }
  23439. else {
  23440. this._renderOpaque = RenderingGroup.renderUnsorted;
  23441. }
  23442. },
  23443. enumerable: true,
  23444. configurable: true
  23445. });
  23446. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23447. /**
  23448. * Set the alpha test sort comparison function.
  23449. * If null the sub meshes will be render in the order they were created
  23450. */
  23451. set: function (value) {
  23452. this._alphaTestSortCompareFn = value;
  23453. if (value) {
  23454. this._renderAlphaTest = this.renderAlphaTestSorted;
  23455. }
  23456. else {
  23457. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23458. }
  23459. },
  23460. enumerable: true,
  23461. configurable: true
  23462. });
  23463. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23464. /**
  23465. * Set the transparent sort comparison function.
  23466. * If null the sub meshes will be render in the order they were created
  23467. */
  23468. set: function (value) {
  23469. if (value) {
  23470. this._transparentSortCompareFn = value;
  23471. }
  23472. else {
  23473. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23474. }
  23475. this._renderTransparent = this.renderTransparentSorted;
  23476. },
  23477. enumerable: true,
  23478. configurable: true
  23479. });
  23480. /**
  23481. * Render all the sub meshes contained in the group.
  23482. * @param customRenderFunction Used to override the default render behaviour of the group.
  23483. * @returns true if rendered some submeshes.
  23484. */
  23485. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23486. if (customRenderFunction) {
  23487. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23488. return;
  23489. }
  23490. var engine = this._scene.getEngine();
  23491. // Depth only
  23492. if (this._depthOnlySubMeshes.length !== 0) {
  23493. engine.setColorWrite(false);
  23494. this._renderAlphaTest(this._depthOnlySubMeshes);
  23495. engine.setColorWrite(true);
  23496. }
  23497. // Opaque
  23498. if (this._opaqueSubMeshes.length !== 0) {
  23499. this._renderOpaque(this._opaqueSubMeshes);
  23500. }
  23501. // Alpha test
  23502. if (this._alphaTestSubMeshes.length !== 0) {
  23503. this._renderAlphaTest(this._alphaTestSubMeshes);
  23504. }
  23505. var stencilState = engine.getStencilBuffer();
  23506. engine.setStencilBuffer(false);
  23507. // Sprites
  23508. if (renderSprites) {
  23509. this._renderSprites();
  23510. }
  23511. // Particles
  23512. if (renderParticles) {
  23513. this._renderParticles(activeMeshes);
  23514. }
  23515. if (this.onBeforeTransparentRendering) {
  23516. this.onBeforeTransparentRendering();
  23517. }
  23518. // Transparent
  23519. if (this._transparentSubMeshes.length !== 0) {
  23520. this._renderTransparent(this._transparentSubMeshes);
  23521. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23522. }
  23523. // Set back stencil to false in case it changes before the edge renderer.
  23524. engine.setStencilBuffer(false);
  23525. // Edges
  23526. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23527. this._edgesRenderers.data[edgesRendererIndex].render();
  23528. }
  23529. // Restore Stencil state.
  23530. engine.setStencilBuffer(stencilState);
  23531. };
  23532. /**
  23533. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23534. * @param subMeshes The submeshes to render
  23535. */
  23536. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23537. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23538. };
  23539. /**
  23540. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23541. * @param subMeshes The submeshes to render
  23542. */
  23543. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23544. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23545. };
  23546. /**
  23547. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23548. * @param subMeshes The submeshes to render
  23549. */
  23550. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23551. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23552. };
  23553. /**
  23554. * Renders the submeshes in a specified order.
  23555. * @param subMeshes The submeshes to sort before render
  23556. * @param sortCompareFn The comparison function use to sort
  23557. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23558. * @param transparent Specifies to activate blending if true
  23559. */
  23560. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23561. var subIndex = 0;
  23562. var subMesh;
  23563. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23564. for (; subIndex < subMeshes.length; subIndex++) {
  23565. subMesh = subMeshes.data[subIndex];
  23566. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23567. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23568. }
  23569. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23570. if (sortCompareFn) {
  23571. sortedArray.sort(sortCompareFn);
  23572. }
  23573. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23574. subMesh = sortedArray[subIndex];
  23575. if (transparent) {
  23576. var material = subMesh.getMaterial();
  23577. if (material && material.needDepthPrePass) {
  23578. var engine = material.getScene().getEngine();
  23579. engine.setColorWrite(false);
  23580. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23581. subMesh.render(false);
  23582. engine.setColorWrite(true);
  23583. }
  23584. }
  23585. subMesh.render(transparent);
  23586. }
  23587. };
  23588. /**
  23589. * Renders the submeshes in the order they were dispatched (no sort applied).
  23590. * @param subMeshes The submeshes to render
  23591. */
  23592. RenderingGroup.renderUnsorted = function (subMeshes) {
  23593. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23594. var submesh = subMeshes.data[subIndex];
  23595. submesh.render(false);
  23596. }
  23597. };
  23598. /**
  23599. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23600. * are rendered back to front if in the same alpha index.
  23601. *
  23602. * @param a The first submesh
  23603. * @param b The second submesh
  23604. * @returns The result of the comparison
  23605. */
  23606. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23607. // Alpha index first
  23608. if (a._alphaIndex > b._alphaIndex) {
  23609. return 1;
  23610. }
  23611. if (a._alphaIndex < b._alphaIndex) {
  23612. return -1;
  23613. }
  23614. // Then distance to camera
  23615. return RenderingGroup.backToFrontSortCompare(a, b);
  23616. };
  23617. /**
  23618. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23619. * are rendered back to front.
  23620. *
  23621. * @param a The first submesh
  23622. * @param b The second submesh
  23623. * @returns The result of the comparison
  23624. */
  23625. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23626. // Then distance to camera
  23627. if (a._distanceToCamera < b._distanceToCamera) {
  23628. return 1;
  23629. }
  23630. if (a._distanceToCamera > b._distanceToCamera) {
  23631. return -1;
  23632. }
  23633. return 0;
  23634. };
  23635. /**
  23636. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23637. * are rendered front to back (prevent overdraw).
  23638. *
  23639. * @param a The first submesh
  23640. * @param b The second submesh
  23641. * @returns The result of the comparison
  23642. */
  23643. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23644. // Then distance to camera
  23645. if (a._distanceToCamera < b._distanceToCamera) {
  23646. return -1;
  23647. }
  23648. if (a._distanceToCamera > b._distanceToCamera) {
  23649. return 1;
  23650. }
  23651. return 0;
  23652. };
  23653. /**
  23654. * Resets the different lists of submeshes to prepare a new frame.
  23655. */
  23656. RenderingGroup.prototype.prepare = function () {
  23657. this._opaqueSubMeshes.reset();
  23658. this._transparentSubMeshes.reset();
  23659. this._alphaTestSubMeshes.reset();
  23660. this._depthOnlySubMeshes.reset();
  23661. this._particleSystems.reset();
  23662. this._spriteManagers.reset();
  23663. this._edgesRenderers.reset();
  23664. };
  23665. RenderingGroup.prototype.dispose = function () {
  23666. this._opaqueSubMeshes.dispose();
  23667. this._transparentSubMeshes.dispose();
  23668. this._alphaTestSubMeshes.dispose();
  23669. this._depthOnlySubMeshes.dispose();
  23670. this._particleSystems.dispose();
  23671. this._spriteManagers.dispose();
  23672. this._edgesRenderers.dispose();
  23673. };
  23674. /**
  23675. * Inserts the submesh in its correct queue depending on its material.
  23676. * @param subMesh The submesh to dispatch
  23677. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23678. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23679. */
  23680. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23681. // Get mesh and materials if not provided
  23682. if (mesh === undefined) {
  23683. mesh = subMesh.getMesh();
  23684. }
  23685. if (material === undefined) {
  23686. material = subMesh.getMaterial();
  23687. }
  23688. if (material === null || material === undefined) {
  23689. return;
  23690. }
  23691. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23692. this._transparentSubMeshes.push(subMesh);
  23693. }
  23694. else if (material.needAlphaTesting()) { // Alpha test
  23695. if (material.needDepthPrePass) {
  23696. this._depthOnlySubMeshes.push(subMesh);
  23697. }
  23698. this._alphaTestSubMeshes.push(subMesh);
  23699. }
  23700. else {
  23701. if (material.needDepthPrePass) {
  23702. this._depthOnlySubMeshes.push(subMesh);
  23703. }
  23704. this._opaqueSubMeshes.push(subMesh); // Opaque
  23705. }
  23706. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23707. this._edgesRenderers.push(mesh._edgesRenderer);
  23708. }
  23709. };
  23710. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23711. this._spriteManagers.push(spriteManager);
  23712. };
  23713. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23714. this._particleSystems.push(particleSystem);
  23715. };
  23716. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23717. if (this._particleSystems.length === 0) {
  23718. return;
  23719. }
  23720. // Particles
  23721. var activeCamera = this._scene.activeCamera;
  23722. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23723. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23724. var particleSystem = this._particleSystems.data[particleIndex];
  23725. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23726. continue;
  23727. }
  23728. var emitter = particleSystem.emitter;
  23729. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23730. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23731. }
  23732. }
  23733. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23734. };
  23735. RenderingGroup.prototype._renderSprites = function () {
  23736. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23737. return;
  23738. }
  23739. // Sprites
  23740. var activeCamera = this._scene.activeCamera;
  23741. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23742. for (var id = 0; id < this._spriteManagers.length; id++) {
  23743. var spriteManager = this._spriteManagers.data[id];
  23744. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23745. spriteManager.render();
  23746. }
  23747. }
  23748. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23749. };
  23750. return RenderingGroup;
  23751. }());
  23752. BABYLON.RenderingGroup = RenderingGroup;
  23753. })(BABYLON || (BABYLON = {}));
  23754. //# sourceMappingURL=babylon.renderingGroup.js.map
  23755. var BABYLON;
  23756. (function (BABYLON) {
  23757. /** @hidden */
  23758. var ClickInfo = /** @class */ (function () {
  23759. function ClickInfo() {
  23760. this._singleClick = false;
  23761. this._doubleClick = false;
  23762. this._hasSwiped = false;
  23763. this._ignore = false;
  23764. }
  23765. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23766. get: function () {
  23767. return this._singleClick;
  23768. },
  23769. set: function (b) {
  23770. this._singleClick = b;
  23771. },
  23772. enumerable: true,
  23773. configurable: true
  23774. });
  23775. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23776. get: function () {
  23777. return this._doubleClick;
  23778. },
  23779. set: function (b) {
  23780. this._doubleClick = b;
  23781. },
  23782. enumerable: true,
  23783. configurable: true
  23784. });
  23785. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23786. get: function () {
  23787. return this._hasSwiped;
  23788. },
  23789. set: function (b) {
  23790. this._hasSwiped = b;
  23791. },
  23792. enumerable: true,
  23793. configurable: true
  23794. });
  23795. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23796. get: function () {
  23797. return this._ignore;
  23798. },
  23799. set: function (b) {
  23800. this._ignore = b;
  23801. },
  23802. enumerable: true,
  23803. configurable: true
  23804. });
  23805. return ClickInfo;
  23806. }());
  23807. /**
  23808. * This class is used by the onRenderingGroupObservable
  23809. */
  23810. var RenderingGroupInfo = /** @class */ (function () {
  23811. function RenderingGroupInfo() {
  23812. }
  23813. /**
  23814. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23815. * This stage will be fired no matter what
  23816. */
  23817. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23818. /**
  23819. * Called before opaque object are rendered.
  23820. * This stage will be fired only if there's 3D Opaque content to render
  23821. */
  23822. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23823. /**
  23824. * Called after the opaque objects are rendered and before the transparent ones
  23825. * This stage will be fired only if there's 3D transparent content to render
  23826. */
  23827. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23828. /**
  23829. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23830. * This stage will be fired no matter what
  23831. */
  23832. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23833. return RenderingGroupInfo;
  23834. }());
  23835. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23836. /**
  23837. * Represents a scene to be rendered by the engine.
  23838. * @see http://doc.babylonjs.com/features/scene
  23839. */
  23840. var Scene = /** @class */ (function () {
  23841. /**
  23842. * Creates a new Scene
  23843. * @param engine defines the engine to use to render this scene
  23844. */
  23845. function Scene(engine) {
  23846. // Members
  23847. /**
  23848. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23849. */
  23850. this.autoClear = true;
  23851. /**
  23852. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23853. */
  23854. this.autoClearDepthAndStencil = true;
  23855. /**
  23856. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23857. */
  23858. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23859. /**
  23860. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23861. */
  23862. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23863. this._forceWireframe = false;
  23864. this._forcePointsCloud = false;
  23865. /**
  23866. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23867. */
  23868. this.forceShowBoundingBoxes = false;
  23869. /**
  23870. * Gets or sets a boolean indicating if animations are enabled
  23871. */
  23872. this.animationsEnabled = true;
  23873. this._animationPropertiesOverride = null;
  23874. /**
  23875. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23876. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23877. */
  23878. this.useConstantAnimationDeltaTime = false;
  23879. /**
  23880. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23881. * Please note that it requires to run a ray cast through the scene on every frame
  23882. */
  23883. this.constantlyUpdateMeshUnderPointer = false;
  23884. /**
  23885. * Defines the HTML cursor to use when hovering over interactive elements
  23886. */
  23887. this.hoverCursor = "pointer";
  23888. /**
  23889. * Defines the HTML default cursor to use (empty by default)
  23890. */
  23891. this.defaultCursor = "";
  23892. /**
  23893. * This is used to call preventDefault() on pointer down
  23894. * in order to block unwanted artifacts like system double clicks
  23895. */
  23896. this.preventDefaultOnPointerDown = true;
  23897. // Metadata
  23898. /**
  23899. * Gets or sets user defined metadata
  23900. */
  23901. this.metadata = null;
  23902. /**
  23903. * Use this array to add regular expressions used to disable offline support for specific urls
  23904. */
  23905. this.disableOfflineSupportExceptionRules = new Array();
  23906. /**
  23907. * An event triggered when the scene is disposed.
  23908. */
  23909. this.onDisposeObservable = new BABYLON.Observable();
  23910. this._onDisposeObserver = null;
  23911. /**
  23912. * An event triggered before rendering the scene (right after animations and physics)
  23913. */
  23914. this.onBeforeRenderObservable = new BABYLON.Observable();
  23915. this._onBeforeRenderObserver = null;
  23916. /**
  23917. * An event triggered after rendering the scene
  23918. */
  23919. this.onAfterRenderObservable = new BABYLON.Observable();
  23920. this._onAfterRenderObserver = null;
  23921. /**
  23922. * An event triggered before animating the scene
  23923. */
  23924. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23925. /**
  23926. * An event triggered after animations processing
  23927. */
  23928. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23929. /**
  23930. * An event triggered before draw calls are ready to be sent
  23931. */
  23932. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23933. /**
  23934. * An event triggered after draw calls have been sent
  23935. */
  23936. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23937. /**
  23938. * An event triggered when physic simulation is about to be run
  23939. */
  23940. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23941. /**
  23942. * An event triggered when physic simulation has been done
  23943. */
  23944. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23945. /**
  23946. * An event triggered when the scene is ready
  23947. */
  23948. this.onReadyObservable = new BABYLON.Observable();
  23949. /**
  23950. * An event triggered before rendering a camera
  23951. */
  23952. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23953. this._onBeforeCameraRenderObserver = null;
  23954. /**
  23955. * An event triggered after rendering a camera
  23956. */
  23957. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23958. this._onAfterCameraRenderObserver = null;
  23959. /**
  23960. * An event triggered when active meshes evaluation is about to start
  23961. */
  23962. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23963. /**
  23964. * An event triggered when active meshes evaluation is done
  23965. */
  23966. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23967. /**
  23968. * An event triggered when particles rendering is about to start
  23969. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23970. */
  23971. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23972. /**
  23973. * An event triggered when particles rendering is done
  23974. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23975. */
  23976. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23977. /**
  23978. * An event triggered when sprites rendering is about to start
  23979. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23980. */
  23981. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23982. /**
  23983. * An event triggered when sprites rendering is done
  23984. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23985. */
  23986. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23987. /**
  23988. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23989. */
  23990. this.onDataLoadedObservable = new BABYLON.Observable();
  23991. /**
  23992. * An event triggered when a camera is created
  23993. */
  23994. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23995. /**
  23996. * An event triggered when a camera is removed
  23997. */
  23998. this.onCameraRemovedObservable = new BABYLON.Observable();
  23999. /**
  24000. * An event triggered when a light is created
  24001. */
  24002. this.onNewLightAddedObservable = new BABYLON.Observable();
  24003. /**
  24004. * An event triggered when a light is removed
  24005. */
  24006. this.onLightRemovedObservable = new BABYLON.Observable();
  24007. /**
  24008. * An event triggered when a geometry is created
  24009. */
  24010. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24011. /**
  24012. * An event triggered when a geometry is removed
  24013. */
  24014. this.onGeometryRemovedObservable = new BABYLON.Observable();
  24015. /**
  24016. * An event triggered when a transform node is created
  24017. */
  24018. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24019. /**
  24020. * An event triggered when a transform node is removed
  24021. */
  24022. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24023. /**
  24024. * An event triggered when a mesh is created
  24025. */
  24026. this.onNewMeshAddedObservable = new BABYLON.Observable();
  24027. /**
  24028. * An event triggered when a mesh is removed
  24029. */
  24030. this.onMeshRemovedObservable = new BABYLON.Observable();
  24031. /**
  24032. * An event triggered when render targets are about to be rendered
  24033. * Can happen multiple times per frame.
  24034. */
  24035. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24036. /**
  24037. * An event triggered when render targets were rendered.
  24038. * Can happen multiple times per frame.
  24039. */
  24040. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24041. /**
  24042. * An event triggered before calculating deterministic simulation step
  24043. */
  24044. this.onBeforeStepObservable = new BABYLON.Observable();
  24045. /**
  24046. * An event triggered after calculating deterministic simulation step
  24047. */
  24048. this.onAfterStepObservable = new BABYLON.Observable();
  24049. /**
  24050. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  24051. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24052. * 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)
  24053. */
  24054. this.onRenderingGroupObservable = new BABYLON.Observable();
  24055. // Animations
  24056. /**
  24057. * Gets a list of Animations associated with the scene
  24058. */
  24059. this.animations = [];
  24060. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24061. /**
  24062. * 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).
  24063. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24064. */
  24065. this.onPrePointerObservable = new BABYLON.Observable();
  24066. /**
  24067. * Observable event triggered each time an input event is received from the rendering canvas
  24068. */
  24069. this.onPointerObservable = new BABYLON.Observable();
  24070. this._meshPickProceed = false;
  24071. this._currentPickResult = null;
  24072. this._previousPickResult = null;
  24073. this._totalPointersPressed = 0;
  24074. this._doubleClickOccured = false;
  24075. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24076. this.cameraToUseForPointers = null;
  24077. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24078. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24079. this._startingPointerTime = 0;
  24080. this._previousStartingPointerTime = 0;
  24081. this._pointerCaptures = {};
  24082. // Deterministic lockstep
  24083. this._timeAccumulator = 0;
  24084. this._currentStepId = 0;
  24085. this._currentInternalStep = 0;
  24086. // Keyboard
  24087. /**
  24088. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24089. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24090. */
  24091. this.onPreKeyboardObservable = new BABYLON.Observable();
  24092. /**
  24093. * Observable event triggered each time an keyboard event is received from the hosting window
  24094. */
  24095. this.onKeyboardObservable = new BABYLON.Observable();
  24096. // Coordinates system
  24097. this._useRightHandedSystem = false;
  24098. // Fog
  24099. this._fogEnabled = true;
  24100. this._fogMode = Scene.FOGMODE_NONE;
  24101. /**
  24102. * Gets or sets the fog color to use
  24103. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24104. */
  24105. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24106. /**
  24107. * Gets or sets the fog density to use
  24108. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24109. */
  24110. this.fogDensity = 0.1;
  24111. /**
  24112. * Gets or sets the fog start distance to use
  24113. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24114. */
  24115. this.fogStart = 0;
  24116. /**
  24117. * Gets or sets the fog end distance to use
  24118. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24119. */
  24120. this.fogEnd = 1000.0;
  24121. // Lights
  24122. this._shadowsEnabled = true;
  24123. this._lightsEnabled = true;
  24124. /**
  24125. * All of the lights added to this scene
  24126. * @see http://doc.babylonjs.com/babylon101/lights
  24127. */
  24128. this.lights = new Array();
  24129. // Cameras
  24130. /** All of the cameras added to this scene.
  24131. * @see http://doc.babylonjs.com/babylon101/cameras
  24132. */
  24133. this.cameras = new Array();
  24134. /** All of the active cameras added to this scene. */
  24135. this.activeCameras = new Array();
  24136. // Meshes
  24137. /**
  24138. * All of the tranform nodes added to this scene
  24139. * @see http://doc.babylonjs.com/how_to/transformnode
  24140. */
  24141. this.transformNodes = new Array();
  24142. /**
  24143. * All of the (abstract) meshes added to this scene
  24144. */
  24145. this.meshes = new Array();
  24146. /**
  24147. * All of the animation groups added to this scene
  24148. * @see http://doc.babylonjs.com/how_to/group
  24149. */
  24150. this.animationGroups = new Array();
  24151. // Geometries
  24152. this._geometries = new Array();
  24153. /**
  24154. * All of the materials added to this scene
  24155. * @see http://doc.babylonjs.com/babylon101/materials
  24156. */
  24157. this.materials = new Array();
  24158. /**
  24159. * All of the multi-materials added to this scene
  24160. * @see http://doc.babylonjs.com/how_to/multi_materials
  24161. */
  24162. this.multiMaterials = new Array();
  24163. // Textures
  24164. this._texturesEnabled = true;
  24165. /**
  24166. * All of the textures added to this scene
  24167. */
  24168. this.textures = new Array();
  24169. // Particles
  24170. /**
  24171. * Gets or sets a boolean indicating if particles are enabled on this scene
  24172. */
  24173. this.particlesEnabled = true;
  24174. /**
  24175. * All of the particle systems added to this scene
  24176. * @see http://doc.babylonjs.com/babylon101/particles
  24177. */
  24178. this.particleSystems = new Array();
  24179. // Sprites
  24180. /**
  24181. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24182. */
  24183. this.spritesEnabled = true;
  24184. /**
  24185. * All of the sprite managers added to this scene
  24186. * @see http://doc.babylonjs.com/babylon101/sprites
  24187. */
  24188. this.spriteManagers = new Array();
  24189. /**
  24190. * The list of layers (background and foreground) of the scene
  24191. */
  24192. this.layers = new Array();
  24193. /**
  24194. * The list of effect layers (highlights/glow) added to the scene
  24195. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24196. * @see http://doc.babylonjs.com/how_to/glow_layer
  24197. */
  24198. this.effectLayers = new Array();
  24199. // Skeletons
  24200. this._skeletonsEnabled = true;
  24201. /**
  24202. * The list of skeletons added to the scene
  24203. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24204. */
  24205. this.skeletons = new Array();
  24206. // Morph targets
  24207. /**
  24208. * The list of morph target managers added to the scene
  24209. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24210. */
  24211. this.morphTargetManagers = new Array();
  24212. // Lens flares
  24213. /**
  24214. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24215. */
  24216. this.lensFlaresEnabled = true;
  24217. /**
  24218. * The list of lens flare system added to the scene
  24219. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24220. */
  24221. this.lensFlareSystems = new Array();
  24222. // Collisions
  24223. /**
  24224. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24225. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24226. */
  24227. this.collisionsEnabled = true;
  24228. /**
  24229. * Defines the gravity applied to this scene (used only for collisions)
  24230. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24231. */
  24232. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24233. // Postprocesses
  24234. /**
  24235. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24236. */
  24237. this.postProcessesEnabled = true;
  24238. /**
  24239. * The list of postprocesses added to the scene
  24240. */
  24241. this.postProcesses = new Array();
  24242. // Customs render targets
  24243. /**
  24244. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24245. */
  24246. this.renderTargetsEnabled = true;
  24247. /**
  24248. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24249. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24250. */
  24251. this.dumpNextRenderTargets = false;
  24252. /**
  24253. * The list of user defined render targets added to the scene
  24254. */
  24255. this.customRenderTargets = new Array();
  24256. /**
  24257. * Gets the list of meshes imported to the scene through SceneLoader
  24258. */
  24259. this.importedMeshesFiles = new Array();
  24260. // Probes
  24261. /**
  24262. * Gets or sets a boolean indicating if probes are enabled on this scene
  24263. */
  24264. this.probesEnabled = true;
  24265. /**
  24266. * The list of reflection probes added to the scene
  24267. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24268. */
  24269. this.reflectionProbes = new Array();
  24270. /** @hidden */
  24271. this._actionManagers = new Array();
  24272. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24273. // Procedural textures
  24274. /**
  24275. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24276. */
  24277. this.proceduralTexturesEnabled = true;
  24278. /**
  24279. * The list of procedural textures added to the scene
  24280. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24281. */
  24282. this.proceduralTextures = new Array();
  24283. /**
  24284. * The list of sound tracks added to the scene
  24285. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24286. */
  24287. this.soundTracks = new Array();
  24288. this._audioEnabled = true;
  24289. this._headphone = false;
  24290. // Performance counters
  24291. this._totalVertices = new BABYLON.PerfCounter();
  24292. /** @hidden */
  24293. this._activeIndices = new BABYLON.PerfCounter();
  24294. /** @hidden */
  24295. this._activeParticles = new BABYLON.PerfCounter();
  24296. /** @hidden */
  24297. this._activeBones = new BABYLON.PerfCounter();
  24298. this._animationTime = 0;
  24299. /**
  24300. * Gets or sets a general scale for animation speed
  24301. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24302. */
  24303. this.animationTimeScale = 1;
  24304. this._renderId = 0;
  24305. this._executeWhenReadyTimeoutId = -1;
  24306. this._intermediateRendering = false;
  24307. this._viewUpdateFlag = -1;
  24308. this._projectionUpdateFlag = -1;
  24309. this._alternateViewUpdateFlag = -1;
  24310. this._alternateProjectionUpdateFlag = -1;
  24311. /** @hidden */
  24312. this._toBeDisposed = new BABYLON.SmartArray(256);
  24313. this._activeRequests = new Array();
  24314. this._pendingData = new Array();
  24315. this._isDisposed = false;
  24316. /**
  24317. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24318. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24319. */
  24320. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24321. this._activeMeshes = new BABYLON.SmartArray(256);
  24322. this._processedMaterials = new BABYLON.SmartArray(256);
  24323. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24324. /** @hidden */
  24325. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24326. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24327. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24328. /** @hidden */
  24329. this._activeAnimatables = new Array();
  24330. this._transformMatrix = BABYLON.Matrix.Zero();
  24331. this._useAlternateCameraConfiguration = false;
  24332. this._alternateRendering = false;
  24333. /**
  24334. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24335. * This is useful if there are more lights that the maximum simulteanous authorized
  24336. */
  24337. this.requireLightSorting = false;
  24338. this._depthRenderer = {};
  24339. this._activeMeshesFrozen = false;
  24340. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24341. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24342. this._engine.scenes.push(this);
  24343. this._uid = null;
  24344. this._renderingManager = new BABYLON.RenderingManager(this);
  24345. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24346. if (BABYLON.OutlineRenderer) {
  24347. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24348. }
  24349. if (BABYLON.Tools.IsWindowObjectExist()) {
  24350. this.attachControl();
  24351. }
  24352. //simplification queue
  24353. if (BABYLON.SimplificationQueue) {
  24354. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24355. }
  24356. //collision coordinator initialization. For now legacy per default.
  24357. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24358. // Uniform Buffer
  24359. this._createUbo();
  24360. // Default Image processing definition.
  24361. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24362. }
  24363. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24364. /** The fog is deactivated */
  24365. get: function () {
  24366. return Scene._FOGMODE_NONE;
  24367. },
  24368. enumerable: true,
  24369. configurable: true
  24370. });
  24371. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24372. /** The fog density is following an exponential function */
  24373. get: function () {
  24374. return Scene._FOGMODE_EXP;
  24375. },
  24376. enumerable: true,
  24377. configurable: true
  24378. });
  24379. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24380. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24381. get: function () {
  24382. return Scene._FOGMODE_EXP2;
  24383. },
  24384. enumerable: true,
  24385. configurable: true
  24386. });
  24387. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24388. /** The fog density is following a linear function. */
  24389. get: function () {
  24390. return Scene._FOGMODE_LINEAR;
  24391. },
  24392. enumerable: true,
  24393. configurable: true
  24394. });
  24395. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24396. /**
  24397. * Texture used in all pbr material as the reflection texture.
  24398. * As in the majority of the scene they are the same (exception for multi room and so on),
  24399. * this is easier to reference from here than from all the materials.
  24400. */
  24401. get: function () {
  24402. return this._environmentTexture;
  24403. },
  24404. /**
  24405. * Texture used in all pbr material as the reflection texture.
  24406. * As in the majority of the scene they are the same (exception for multi room and so on),
  24407. * this is easier to set here than in all the materials.
  24408. */
  24409. set: function (value) {
  24410. if (this._environmentTexture === value) {
  24411. return;
  24412. }
  24413. this._environmentTexture = value;
  24414. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24415. },
  24416. enumerable: true,
  24417. configurable: true
  24418. });
  24419. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24420. /**
  24421. * Default image processing configuration used either in the rendering
  24422. * Forward main pass or through the imageProcessingPostProcess if present.
  24423. * As in the majority of the scene they are the same (exception for multi camera),
  24424. * this is easier to reference from here than from all the materials and post process.
  24425. *
  24426. * No setter as we it is a shared configuration, you can set the values instead.
  24427. */
  24428. get: function () {
  24429. return this._imageProcessingConfiguration;
  24430. },
  24431. enumerable: true,
  24432. configurable: true
  24433. });
  24434. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24435. get: function () {
  24436. return this._forceWireframe;
  24437. },
  24438. /**
  24439. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24440. */
  24441. set: function (value) {
  24442. if (this._forceWireframe === value) {
  24443. return;
  24444. }
  24445. this._forceWireframe = value;
  24446. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24447. },
  24448. enumerable: true,
  24449. configurable: true
  24450. });
  24451. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24452. get: function () {
  24453. return this._forcePointsCloud;
  24454. },
  24455. /**
  24456. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24457. */
  24458. set: function (value) {
  24459. if (this._forcePointsCloud === value) {
  24460. return;
  24461. }
  24462. this._forcePointsCloud = value;
  24463. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24464. },
  24465. enumerable: true,
  24466. configurable: true
  24467. });
  24468. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24469. /**
  24470. * Gets or sets the animation properties override
  24471. */
  24472. get: function () {
  24473. return this._animationPropertiesOverride;
  24474. },
  24475. set: function (value) {
  24476. this._animationPropertiesOverride = value;
  24477. },
  24478. enumerable: true,
  24479. configurable: true
  24480. });
  24481. Object.defineProperty(Scene.prototype, "onDispose", {
  24482. /** Sets a function to be executed when this scene is disposed. */
  24483. set: function (callback) {
  24484. if (this._onDisposeObserver) {
  24485. this.onDisposeObservable.remove(this._onDisposeObserver);
  24486. }
  24487. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24488. },
  24489. enumerable: true,
  24490. configurable: true
  24491. });
  24492. Object.defineProperty(Scene.prototype, "beforeRender", {
  24493. /** Sets a function to be executed before rendering this scene */
  24494. set: function (callback) {
  24495. if (this._onBeforeRenderObserver) {
  24496. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24497. }
  24498. if (callback) {
  24499. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24500. }
  24501. },
  24502. enumerable: true,
  24503. configurable: true
  24504. });
  24505. Object.defineProperty(Scene.prototype, "afterRender", {
  24506. /** Sets a function to be executed after rendering this scene */
  24507. set: function (callback) {
  24508. if (this._onAfterRenderObserver) {
  24509. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24510. }
  24511. if (callback) {
  24512. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24513. }
  24514. },
  24515. enumerable: true,
  24516. configurable: true
  24517. });
  24518. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24519. /** Sets a function to be executed before rendering a camera*/
  24520. set: function (callback) {
  24521. if (this._onBeforeCameraRenderObserver) {
  24522. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24523. }
  24524. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24525. },
  24526. enumerable: true,
  24527. configurable: true
  24528. });
  24529. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24530. /** Sets a function to be executed after rendering a camera*/
  24531. set: function (callback) {
  24532. if (this._onAfterCameraRenderObserver) {
  24533. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24534. }
  24535. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24536. },
  24537. enumerable: true,
  24538. configurable: true
  24539. });
  24540. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24541. /**
  24542. * Gets the gamepad manager associated with the scene
  24543. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24544. */
  24545. get: function () {
  24546. if (!this._gamepadManager) {
  24547. this._gamepadManager = new BABYLON.GamepadManager(this);
  24548. }
  24549. return this._gamepadManager;
  24550. },
  24551. enumerable: true,
  24552. configurable: true
  24553. });
  24554. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24555. /**
  24556. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24557. */
  24558. get: function () {
  24559. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24560. },
  24561. enumerable: true,
  24562. configurable: true
  24563. });
  24564. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24565. get: function () {
  24566. return this._useRightHandedSystem;
  24567. },
  24568. /**
  24569. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24570. */
  24571. set: function (value) {
  24572. if (this._useRightHandedSystem === value) {
  24573. return;
  24574. }
  24575. this._useRightHandedSystem = value;
  24576. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24577. },
  24578. enumerable: true,
  24579. configurable: true
  24580. });
  24581. /**
  24582. * Sets the step Id used by deterministic lock step
  24583. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24584. * @param newStepId defines the step Id
  24585. */
  24586. Scene.prototype.setStepId = function (newStepId) {
  24587. this._currentStepId = newStepId;
  24588. };
  24589. ;
  24590. /**
  24591. * Gets the step Id used by deterministic lock step
  24592. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24593. * @returns the step Id
  24594. */
  24595. Scene.prototype.getStepId = function () {
  24596. return this._currentStepId;
  24597. };
  24598. ;
  24599. /**
  24600. * Gets the internal step used by deterministic lock step
  24601. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24602. * @returns the internal step
  24603. */
  24604. Scene.prototype.getInternalStep = function () {
  24605. return this._currentInternalStep;
  24606. };
  24607. ;
  24608. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24609. get: function () {
  24610. return this._fogEnabled;
  24611. },
  24612. /**
  24613. * Gets or sets a boolean indicating if fog is enabled on this scene
  24614. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24615. */
  24616. set: function (value) {
  24617. if (this._fogEnabled === value) {
  24618. return;
  24619. }
  24620. this._fogEnabled = value;
  24621. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24622. },
  24623. enumerable: true,
  24624. configurable: true
  24625. });
  24626. Object.defineProperty(Scene.prototype, "fogMode", {
  24627. get: function () {
  24628. return this._fogMode;
  24629. },
  24630. /**
  24631. * Gets or sets the fog mode to use
  24632. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24633. */
  24634. set: function (value) {
  24635. if (this._fogMode === value) {
  24636. return;
  24637. }
  24638. this._fogMode = value;
  24639. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24640. },
  24641. enumerable: true,
  24642. configurable: true
  24643. });
  24644. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24645. get: function () {
  24646. return this._shadowsEnabled;
  24647. },
  24648. /**
  24649. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24650. */
  24651. set: function (value) {
  24652. if (this._shadowsEnabled === value) {
  24653. return;
  24654. }
  24655. this._shadowsEnabled = value;
  24656. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24657. },
  24658. enumerable: true,
  24659. configurable: true
  24660. });
  24661. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24662. get: function () {
  24663. return this._lightsEnabled;
  24664. },
  24665. /**
  24666. * Gets or sets a boolean indicating if lights are enabled on this scene
  24667. */
  24668. set: function (value) {
  24669. if (this._lightsEnabled === value) {
  24670. return;
  24671. }
  24672. this._lightsEnabled = value;
  24673. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24674. },
  24675. enumerable: true,
  24676. configurable: true
  24677. });
  24678. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24679. /** The default material used on meshes when no material is affected */
  24680. get: function () {
  24681. if (!this._defaultMaterial) {
  24682. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24683. }
  24684. return this._defaultMaterial;
  24685. },
  24686. /** The default material used on meshes when no material is affected */
  24687. set: function (value) {
  24688. this._defaultMaterial = value;
  24689. },
  24690. enumerable: true,
  24691. configurable: true
  24692. });
  24693. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24694. get: function () {
  24695. return this._texturesEnabled;
  24696. },
  24697. /**
  24698. * Gets or sets a boolean indicating if textures are enabled on this scene
  24699. */
  24700. set: function (value) {
  24701. if (this._texturesEnabled === value) {
  24702. return;
  24703. }
  24704. this._texturesEnabled = value;
  24705. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24706. },
  24707. enumerable: true,
  24708. configurable: true
  24709. });
  24710. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24711. get: function () {
  24712. return this._skeletonsEnabled;
  24713. },
  24714. /**
  24715. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24716. */
  24717. set: function (value) {
  24718. if (this._skeletonsEnabled === value) {
  24719. return;
  24720. }
  24721. this._skeletonsEnabled = value;
  24722. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24723. },
  24724. enumerable: true,
  24725. configurable: true
  24726. });
  24727. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24728. /**
  24729. * Gets the postprocess render pipeline manager
  24730. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24731. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24732. */
  24733. get: function () {
  24734. if (!this._postProcessRenderPipelineManager) {
  24735. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24736. }
  24737. return this._postProcessRenderPipelineManager;
  24738. },
  24739. enumerable: true,
  24740. configurable: true
  24741. });
  24742. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24743. /**
  24744. * Gets the main soundtrack associated with the scene
  24745. */
  24746. get: function () {
  24747. if (!this._mainSoundTrack) {
  24748. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24749. }
  24750. return this._mainSoundTrack;
  24751. },
  24752. enumerable: true,
  24753. configurable: true
  24754. });
  24755. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24756. /** @hidden */
  24757. get: function () {
  24758. return this._alternateRendering;
  24759. },
  24760. enumerable: true,
  24761. configurable: true
  24762. });
  24763. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24764. /**
  24765. * Gets the list of frustum planes (built from the active camera)
  24766. */
  24767. get: function () {
  24768. return this._frustumPlanes;
  24769. },
  24770. enumerable: true,
  24771. configurable: true
  24772. });
  24773. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24774. /**
  24775. * Gets the current geometry buffer associated to the scene.
  24776. */
  24777. get: function () {
  24778. return this._geometryBufferRenderer;
  24779. },
  24780. /**
  24781. * Sets the current geometry buffer for the scene.
  24782. */
  24783. set: function (geometryBufferRenderer) {
  24784. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24785. this._geometryBufferRenderer = geometryBufferRenderer;
  24786. }
  24787. },
  24788. enumerable: true,
  24789. configurable: true
  24790. });
  24791. Object.defineProperty(Scene.prototype, "debugLayer", {
  24792. /**
  24793. * Gets the debug layer (aka Inspector) associated with the scene
  24794. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24795. */
  24796. get: function () {
  24797. if (!this._debugLayer) {
  24798. this._debugLayer = new BABYLON.DebugLayer(this);
  24799. }
  24800. return this._debugLayer;
  24801. },
  24802. enumerable: true,
  24803. configurable: true
  24804. });
  24805. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24806. /**
  24807. * Gets a boolean indicating if collisions are processed on a web worker
  24808. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24809. */
  24810. get: function () {
  24811. return this._workerCollisions;
  24812. },
  24813. set: function (enabled) {
  24814. if (!BABYLON.CollisionCoordinatorLegacy) {
  24815. return;
  24816. }
  24817. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24818. this._workerCollisions = enabled;
  24819. if (this.collisionCoordinator) {
  24820. this.collisionCoordinator.destroy();
  24821. }
  24822. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24823. this.collisionCoordinator.init(this);
  24824. },
  24825. enumerable: true,
  24826. configurable: true
  24827. });
  24828. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24829. /**
  24830. * Gets the octree used to boost mesh selection (picking)
  24831. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24832. */
  24833. get: function () {
  24834. return this._selectionOctree;
  24835. },
  24836. enumerable: true,
  24837. configurable: true
  24838. });
  24839. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24840. /**
  24841. * Gets the mesh that is currently under the pointer
  24842. */
  24843. get: function () {
  24844. return this._pointerOverMesh;
  24845. },
  24846. enumerable: true,
  24847. configurable: true
  24848. });
  24849. Object.defineProperty(Scene.prototype, "pointerX", {
  24850. /**
  24851. * Gets the current on-screen X position of the pointer
  24852. */
  24853. get: function () {
  24854. return this._pointerX;
  24855. },
  24856. enumerable: true,
  24857. configurable: true
  24858. });
  24859. Object.defineProperty(Scene.prototype, "pointerY", {
  24860. /**
  24861. * Gets the current on-screen Y position of the pointer
  24862. */
  24863. get: function () {
  24864. return this._pointerY;
  24865. },
  24866. enumerable: true,
  24867. configurable: true
  24868. });
  24869. /**
  24870. * Gets the cached material (ie. the latest rendered one)
  24871. * @returns the cached material
  24872. */
  24873. Scene.prototype.getCachedMaterial = function () {
  24874. return this._cachedMaterial;
  24875. };
  24876. /**
  24877. * Gets the cached effect (ie. the latest rendered one)
  24878. * @returns the cached effect
  24879. */
  24880. Scene.prototype.getCachedEffect = function () {
  24881. return this._cachedEffect;
  24882. };
  24883. /**
  24884. * Gets the cached visibility state (ie. the latest rendered one)
  24885. * @returns the cached visibility state
  24886. */
  24887. Scene.prototype.getCachedVisibility = function () {
  24888. return this._cachedVisibility;
  24889. };
  24890. /**
  24891. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24892. * @param material defines the current material
  24893. * @param effect defines the current effect
  24894. * @param visibility defines the current visibility state
  24895. * @returns true if one parameter is not cached
  24896. */
  24897. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24898. if (visibility === void 0) { visibility = 1; }
  24899. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24900. };
  24901. /**
  24902. * Gets the bounding box renderer associated with the scene
  24903. * @returns a BoundingBoxRenderer
  24904. */
  24905. Scene.prototype.getBoundingBoxRenderer = function () {
  24906. if (!this._boundingBoxRenderer) {
  24907. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24908. }
  24909. return this._boundingBoxRenderer;
  24910. };
  24911. /**
  24912. * Gets the outline renderer associated with the scene
  24913. * @returns a OutlineRenderer
  24914. */
  24915. Scene.prototype.getOutlineRenderer = function () {
  24916. return this._outlineRenderer;
  24917. };
  24918. /**
  24919. * Gets the engine associated with the scene
  24920. * @returns an Engine
  24921. */
  24922. Scene.prototype.getEngine = function () {
  24923. return this._engine;
  24924. };
  24925. /**
  24926. * Gets the total number of vertices rendered per frame
  24927. * @returns the total number of vertices rendered per frame
  24928. */
  24929. Scene.prototype.getTotalVertices = function () {
  24930. return this._totalVertices.current;
  24931. };
  24932. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24933. /**
  24934. * Gets the performance counter for total vertices
  24935. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24936. */
  24937. get: function () {
  24938. return this._totalVertices;
  24939. },
  24940. enumerable: true,
  24941. configurable: true
  24942. });
  24943. /**
  24944. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24945. * @returns the total number of active indices rendered per frame
  24946. */
  24947. Scene.prototype.getActiveIndices = function () {
  24948. return this._activeIndices.current;
  24949. };
  24950. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24951. /**
  24952. * Gets the performance counter for active indices
  24953. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24954. */
  24955. get: function () {
  24956. return this._activeIndices;
  24957. },
  24958. enumerable: true,
  24959. configurable: true
  24960. });
  24961. /**
  24962. * Gets the total number of active particles rendered per frame
  24963. * @returns the total number of active particles rendered per frame
  24964. */
  24965. Scene.prototype.getActiveParticles = function () {
  24966. return this._activeParticles.current;
  24967. };
  24968. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24969. /**
  24970. * Gets the performance counter for active particles
  24971. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24972. */
  24973. get: function () {
  24974. return this._activeParticles;
  24975. },
  24976. enumerable: true,
  24977. configurable: true
  24978. });
  24979. /**
  24980. * Gets the total number of active bones rendered per frame
  24981. * @returns the total number of active bones rendered per frame
  24982. */
  24983. Scene.prototype.getActiveBones = function () {
  24984. return this._activeBones.current;
  24985. };
  24986. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24987. /**
  24988. * Gets the performance counter for active bones
  24989. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24990. */
  24991. get: function () {
  24992. return this._activeBones;
  24993. },
  24994. enumerable: true,
  24995. configurable: true
  24996. });
  24997. /** @hidden */
  24998. Scene.prototype.getInterFramePerfCounter = function () {
  24999. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25000. return 0;
  25001. };
  25002. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25003. /** @hidden */
  25004. get: function () {
  25005. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25006. return null;
  25007. },
  25008. enumerable: true,
  25009. configurable: true
  25010. });
  25011. /** @hidden */
  25012. Scene.prototype.getLastFrameDuration = function () {
  25013. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25014. return 0;
  25015. };
  25016. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25017. /** @hidden */
  25018. get: function () {
  25019. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25020. return null;
  25021. },
  25022. enumerable: true,
  25023. configurable: true
  25024. });
  25025. /** @hidden */
  25026. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25027. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25028. return 0;
  25029. };
  25030. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25031. /** @hidden */
  25032. get: function () {
  25033. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25034. return null;
  25035. },
  25036. enumerable: true,
  25037. configurable: true
  25038. });
  25039. /**
  25040. * Gets the array of active meshes
  25041. * @returns an array of AbstractMesh
  25042. */
  25043. Scene.prototype.getActiveMeshes = function () {
  25044. return this._activeMeshes;
  25045. };
  25046. /** @hidden */
  25047. Scene.prototype.getRenderTargetsDuration = function () {
  25048. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25049. return 0;
  25050. };
  25051. /** @hidden */
  25052. Scene.prototype.getRenderDuration = function () {
  25053. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25054. return 0;
  25055. };
  25056. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25057. /** @hidden */
  25058. get: function () {
  25059. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25060. return null;
  25061. },
  25062. enumerable: true,
  25063. configurable: true
  25064. });
  25065. /** @hidden */
  25066. Scene.prototype.getParticlesDuration = function () {
  25067. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25068. return 0;
  25069. };
  25070. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25071. /** @hidden */
  25072. get: function () {
  25073. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25074. return null;
  25075. },
  25076. enumerable: true,
  25077. configurable: true
  25078. });
  25079. /** @hidden */
  25080. Scene.prototype.getSpritesDuration = function () {
  25081. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25082. return 0;
  25083. };
  25084. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25085. /** @hidden */
  25086. get: function () {
  25087. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25088. return null;
  25089. },
  25090. enumerable: true,
  25091. configurable: true
  25092. });
  25093. /**
  25094. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25095. * @returns a number
  25096. */
  25097. Scene.prototype.getAnimationRatio = function () {
  25098. return this._animationRatio;
  25099. };
  25100. /**
  25101. * Gets an unique Id for the current frame
  25102. * @returns a number
  25103. */
  25104. Scene.prototype.getRenderId = function () {
  25105. return this._renderId;
  25106. };
  25107. /** Call this function if you want to manually increment the render Id*/
  25108. Scene.prototype.incrementRenderId = function () {
  25109. this._renderId++;
  25110. };
  25111. Scene.prototype._updatePointerPosition = function (evt) {
  25112. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25113. if (!canvasRect) {
  25114. return;
  25115. }
  25116. this._pointerX = evt.clientX - canvasRect.left;
  25117. this._pointerY = evt.clientY - canvasRect.top;
  25118. this._unTranslatedPointerX = this._pointerX;
  25119. this._unTranslatedPointerY = this._pointerY;
  25120. };
  25121. Scene.prototype._createUbo = function () {
  25122. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25123. this._sceneUbo.addUniform("viewProjection", 16);
  25124. this._sceneUbo.addUniform("view", 16);
  25125. };
  25126. Scene.prototype._createAlternateUbo = function () {
  25127. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25128. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25129. this._alternateSceneUbo.addUniform("view", 16);
  25130. };
  25131. // Pointers handling
  25132. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25133. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25134. if (result) {
  25135. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25136. }
  25137. return result;
  25138. };
  25139. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25140. if (pointerInfo.pickInfo) {
  25141. if (!pointerInfo.pickInfo.ray) {
  25142. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25143. }
  25144. }
  25145. };
  25146. /**
  25147. * Use this method to simulate a pointer move on a mesh
  25148. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25149. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25150. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25151. * @returns the current scene
  25152. */
  25153. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25154. var evt = new PointerEvent("pointermove", pointerEventInit);
  25155. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25156. return this;
  25157. }
  25158. return this._processPointerMove(pickResult, evt);
  25159. };
  25160. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25161. var canvas = this._engine.getRenderingCanvas();
  25162. if (!canvas) {
  25163. return this;
  25164. }
  25165. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25166. this.setPointerOverSprite(null);
  25167. this.setPointerOverMesh(pickResult.pickedMesh);
  25168. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25169. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25170. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25171. }
  25172. else {
  25173. canvas.style.cursor = this.hoverCursor;
  25174. }
  25175. }
  25176. else {
  25177. canvas.style.cursor = this.defaultCursor;
  25178. }
  25179. }
  25180. else {
  25181. this.setPointerOverMesh(null);
  25182. // Sprites
  25183. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25184. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25185. this.setPointerOverSprite(pickResult.pickedSprite);
  25186. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25187. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25188. }
  25189. else {
  25190. canvas.style.cursor = this.hoverCursor;
  25191. }
  25192. }
  25193. else {
  25194. this.setPointerOverSprite(null);
  25195. // Restore pointer
  25196. canvas.style.cursor = this.defaultCursor;
  25197. }
  25198. }
  25199. if (pickResult) {
  25200. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25201. if (this.onPointerMove) {
  25202. this.onPointerMove(evt, pickResult, type);
  25203. }
  25204. if (this.onPointerObservable.hasObservers()) {
  25205. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25206. this._setRayOnPointerInfo(pi);
  25207. this.onPointerObservable.notifyObservers(pi, type);
  25208. }
  25209. }
  25210. return this;
  25211. };
  25212. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25213. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25214. if (pickResult) {
  25215. pi.ray = pickResult.ray;
  25216. }
  25217. this.onPrePointerObservable.notifyObservers(pi, type);
  25218. if (pi.skipOnPointerObservable) {
  25219. return true;
  25220. }
  25221. else {
  25222. return false;
  25223. }
  25224. };
  25225. /**
  25226. * Use this method to simulate a pointer down on a mesh
  25227. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25228. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25229. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25230. * @returns the current scene
  25231. */
  25232. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25233. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25234. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25235. return this;
  25236. }
  25237. return this._processPointerDown(pickResult, evt);
  25238. };
  25239. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25240. var _this = this;
  25241. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25242. this._pickedDownMesh = pickResult.pickedMesh;
  25243. var actionManager = pickResult.pickedMesh.actionManager;
  25244. if (actionManager) {
  25245. if (actionManager.hasPickTriggers) {
  25246. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25247. switch (evt.button) {
  25248. case 0:
  25249. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25250. break;
  25251. case 1:
  25252. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25253. break;
  25254. case 2:
  25255. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25256. break;
  25257. }
  25258. }
  25259. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25260. window.setTimeout(function () {
  25261. 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);
  25262. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25263. if (_this._totalPointersPressed !== 0 &&
  25264. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25265. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25266. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25267. _this._startingPointerTime = 0;
  25268. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25269. }
  25270. }
  25271. }, Scene.LongPressDelay);
  25272. }
  25273. }
  25274. }
  25275. if (pickResult) {
  25276. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25277. if (this.onPointerDown) {
  25278. this.onPointerDown(evt, pickResult, type);
  25279. }
  25280. if (this.onPointerObservable.hasObservers()) {
  25281. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25282. this._setRayOnPointerInfo(pi);
  25283. this.onPointerObservable.notifyObservers(pi, type);
  25284. }
  25285. }
  25286. return this;
  25287. };
  25288. /**
  25289. * Use this method to simulate a pointer up on a mesh
  25290. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25291. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25292. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25293. * @returns the current scene
  25294. */
  25295. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25296. var evt = new PointerEvent("pointerup", pointerEventInit);
  25297. var clickInfo = new ClickInfo();
  25298. clickInfo.singleClick = true;
  25299. clickInfo.ignore = true;
  25300. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25301. return this;
  25302. }
  25303. return this._processPointerUp(pickResult, evt, clickInfo);
  25304. };
  25305. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25306. if (pickResult && pickResult && pickResult.pickedMesh) {
  25307. this._pickedUpMesh = pickResult.pickedMesh;
  25308. if (this._pickedDownMesh === this._pickedUpMesh) {
  25309. if (this.onPointerPick) {
  25310. this.onPointerPick(evt, pickResult);
  25311. }
  25312. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25313. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25314. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25315. this._setRayOnPointerInfo(pi);
  25316. this.onPointerObservable.notifyObservers(pi, type_1);
  25317. }
  25318. }
  25319. if (pickResult.pickedMesh.actionManager) {
  25320. if (clickInfo.ignore) {
  25321. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25322. }
  25323. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25324. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25325. }
  25326. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25327. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25328. }
  25329. }
  25330. }
  25331. if (this._pickedDownMesh &&
  25332. this._pickedDownMesh.actionManager &&
  25333. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25334. this._pickedDownMesh !== this._pickedUpMesh) {
  25335. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25336. }
  25337. var type = BABYLON.PointerEventTypes.POINTERUP;
  25338. if (this.onPointerObservable.hasObservers()) {
  25339. if (!clickInfo.ignore) {
  25340. if (!clickInfo.hasSwiped) {
  25341. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25342. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25343. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25344. this._setRayOnPointerInfo(pi);
  25345. this.onPointerObservable.notifyObservers(pi, type_2);
  25346. }
  25347. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25348. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25349. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25350. this._setRayOnPointerInfo(pi);
  25351. this.onPointerObservable.notifyObservers(pi, type_3);
  25352. }
  25353. }
  25354. }
  25355. else {
  25356. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25357. this._setRayOnPointerInfo(pi);
  25358. this.onPointerObservable.notifyObservers(pi, type);
  25359. }
  25360. }
  25361. if (this.onPointerUp) {
  25362. this.onPointerUp(evt, pickResult, type);
  25363. }
  25364. return this;
  25365. };
  25366. /**
  25367. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25368. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25369. * @returns true if the pointer was captured
  25370. */
  25371. Scene.prototype.isPointerCaptured = function (pointerId) {
  25372. if (pointerId === void 0) { pointerId = 0; }
  25373. return this._pointerCaptures[pointerId];
  25374. };
  25375. /**
  25376. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25377. * @param attachUp defines if you want to attach events to pointerup
  25378. * @param attachDown defines if you want to attach events to pointerdown
  25379. * @param attachMove defines if you want to attach events to pointermove
  25380. */
  25381. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25382. var _this = this;
  25383. if (attachUp === void 0) { attachUp = true; }
  25384. if (attachDown === void 0) { attachDown = true; }
  25385. if (attachMove === void 0) { attachMove = true; }
  25386. this._initActionManager = function (act, clickInfo) {
  25387. if (!_this._meshPickProceed) {
  25388. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25389. _this._currentPickResult = pickResult;
  25390. if (pickResult) {
  25391. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25392. }
  25393. _this._meshPickProceed = true;
  25394. }
  25395. return act;
  25396. };
  25397. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25398. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25399. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25400. btn !== _this._previousButtonPressed) {
  25401. _this._doubleClickOccured = false;
  25402. clickInfo.singleClick = true;
  25403. clickInfo.ignore = false;
  25404. cb(clickInfo, _this._currentPickResult);
  25405. }
  25406. };
  25407. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25408. var clickInfo = new ClickInfo();
  25409. _this._currentPickResult = null;
  25410. var act = null;
  25411. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25412. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25413. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25414. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25415. act = _this._initActionManager(act, clickInfo);
  25416. if (act)
  25417. checkPicking = act.hasPickTriggers;
  25418. }
  25419. if (checkPicking) {
  25420. var btn = evt.button;
  25421. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25422. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25423. if (!clickInfo.hasSwiped) {
  25424. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25425. if (!checkSingleClickImmediately) {
  25426. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25427. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25428. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25429. act = _this._initActionManager(act, clickInfo);
  25430. if (act)
  25431. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25432. }
  25433. }
  25434. if (checkSingleClickImmediately) {
  25435. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25436. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25437. btn !== _this._previousButtonPressed) {
  25438. clickInfo.singleClick = true;
  25439. cb(clickInfo, _this._currentPickResult);
  25440. }
  25441. }
  25442. // at least one double click is required to be check and exclusive double click is enabled
  25443. else {
  25444. // wait that no double click has been raised during the double click delay
  25445. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25446. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25447. }
  25448. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25449. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25450. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25451. act = _this._initActionManager(act, clickInfo);
  25452. if (act)
  25453. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25454. }
  25455. if (checkDoubleClick) {
  25456. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25457. if (btn === _this._previousButtonPressed &&
  25458. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25459. !_this._doubleClickOccured) {
  25460. // pointer has not moved for 2 clicks, it's a double click
  25461. if (!clickInfo.hasSwiped &&
  25462. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25463. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25464. _this._previousStartingPointerTime = 0;
  25465. _this._doubleClickOccured = true;
  25466. clickInfo.doubleClick = true;
  25467. clickInfo.ignore = false;
  25468. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25469. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25470. }
  25471. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25472. cb(clickInfo, _this._currentPickResult);
  25473. }
  25474. // if the two successive clicks are too far, it's just two simple clicks
  25475. else {
  25476. _this._doubleClickOccured = false;
  25477. _this._previousStartingPointerTime = _this._startingPointerTime;
  25478. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25479. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25480. _this._previousButtonPressed = btn;
  25481. if (Scene.ExclusiveDoubleClickMode) {
  25482. if (_this._previousDelayedSimpleClickTimeout) {
  25483. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25484. }
  25485. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25486. cb(clickInfo, _this._previousPickResult);
  25487. }
  25488. else {
  25489. cb(clickInfo, _this._currentPickResult);
  25490. }
  25491. }
  25492. }
  25493. // just the first click of the double has been raised
  25494. else {
  25495. _this._doubleClickOccured = false;
  25496. _this._previousStartingPointerTime = _this._startingPointerTime;
  25497. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25498. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25499. _this._previousButtonPressed = btn;
  25500. }
  25501. }
  25502. }
  25503. }
  25504. clickInfo.ignore = true;
  25505. cb(clickInfo, _this._currentPickResult);
  25506. };
  25507. this._spritePredicate = function (sprite) {
  25508. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25509. };
  25510. this._onPointerMove = function (evt) {
  25511. _this._updatePointerPosition(evt);
  25512. // PreObservable support
  25513. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25514. return;
  25515. }
  25516. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25517. return;
  25518. }
  25519. if (!_this.pointerMovePredicate) {
  25520. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25521. }
  25522. // Meshes
  25523. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25524. _this._processPointerMove(pickResult, evt);
  25525. };
  25526. this._onPointerDown = function (evt) {
  25527. _this._totalPointersPressed++;
  25528. _this._pickedDownMesh = null;
  25529. _this._meshPickProceed = false;
  25530. _this._updatePointerPosition(evt);
  25531. if (_this.preventDefaultOnPointerDown && canvas) {
  25532. evt.preventDefault();
  25533. canvas.focus();
  25534. }
  25535. // PreObservable support
  25536. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25537. return;
  25538. }
  25539. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25540. return;
  25541. }
  25542. _this._pointerCaptures[evt.pointerId] = true;
  25543. _this._startingPointerPosition.x = _this._pointerX;
  25544. _this._startingPointerPosition.y = _this._pointerY;
  25545. _this._startingPointerTime = Date.now();
  25546. if (!_this.pointerDownPredicate) {
  25547. _this.pointerDownPredicate = function (mesh) {
  25548. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25549. };
  25550. }
  25551. // Meshes
  25552. _this._pickedDownMesh = null;
  25553. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25554. _this._processPointerDown(pickResult, evt);
  25555. // Sprites
  25556. _this._pickedDownSprite = null;
  25557. if (_this.spriteManagers.length > 0) {
  25558. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25559. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25560. if (pickResult.pickedSprite.actionManager) {
  25561. _this._pickedDownSprite = pickResult.pickedSprite;
  25562. switch (evt.button) {
  25563. case 0:
  25564. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25565. break;
  25566. case 1:
  25567. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25568. break;
  25569. case 2:
  25570. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25571. break;
  25572. }
  25573. if (pickResult.pickedSprite.actionManager) {
  25574. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25575. }
  25576. }
  25577. }
  25578. }
  25579. };
  25580. this._onPointerUp = function (evt) {
  25581. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25582. return; // So we need to test it the pointer down was pressed before.
  25583. }
  25584. _this._totalPointersPressed--;
  25585. _this._pickedUpMesh = null;
  25586. _this._meshPickProceed = false;
  25587. _this._updatePointerPosition(evt);
  25588. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25589. // PreObservable support
  25590. if (_this.onPrePointerObservable.hasObservers()) {
  25591. if (!clickInfo.ignore) {
  25592. if (!clickInfo.hasSwiped) {
  25593. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25594. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25595. return;
  25596. }
  25597. }
  25598. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25599. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25600. return;
  25601. }
  25602. }
  25603. }
  25604. }
  25605. else {
  25606. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25607. return;
  25608. }
  25609. }
  25610. }
  25611. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25612. return;
  25613. }
  25614. _this._pointerCaptures[evt.pointerId] = false;
  25615. if (!_this.pointerUpPredicate) {
  25616. _this.pointerUpPredicate = function (mesh) {
  25617. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25618. };
  25619. }
  25620. // Meshes
  25621. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25622. _this._initActionManager(null, clickInfo);
  25623. }
  25624. if (!pickResult) {
  25625. pickResult = _this._currentPickResult;
  25626. }
  25627. _this._processPointerUp(pickResult, evt, clickInfo);
  25628. // Sprites
  25629. if (!clickInfo.ignore) {
  25630. if (_this.spriteManagers.length > 0) {
  25631. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25632. if (spritePickResult) {
  25633. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25634. if (spritePickResult.pickedSprite.actionManager) {
  25635. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25636. if (spritePickResult.pickedSprite.actionManager) {
  25637. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25638. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25639. }
  25640. }
  25641. }
  25642. }
  25643. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25644. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25645. }
  25646. }
  25647. }
  25648. }
  25649. _this._previousPickResult = _this._currentPickResult;
  25650. });
  25651. };
  25652. this._onKeyDown = function (evt) {
  25653. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25654. if (_this.onPreKeyboardObservable.hasObservers()) {
  25655. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25656. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25657. if (pi.skipOnPointerObservable) {
  25658. return;
  25659. }
  25660. }
  25661. if (_this.onKeyboardObservable.hasObservers()) {
  25662. var pi = new BABYLON.KeyboardInfo(type, evt);
  25663. _this.onKeyboardObservable.notifyObservers(pi, type);
  25664. }
  25665. if (_this.actionManager) {
  25666. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25667. }
  25668. };
  25669. this._onKeyUp = function (evt) {
  25670. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25671. if (_this.onPreKeyboardObservable.hasObservers()) {
  25672. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25673. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25674. if (pi.skipOnPointerObservable) {
  25675. return;
  25676. }
  25677. }
  25678. if (_this.onKeyboardObservable.hasObservers()) {
  25679. var pi = new BABYLON.KeyboardInfo(type, evt);
  25680. _this.onKeyboardObservable.notifyObservers(pi, type);
  25681. }
  25682. if (_this.actionManager) {
  25683. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25684. }
  25685. };
  25686. var engine = this.getEngine();
  25687. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25688. if (!canvas) {
  25689. return;
  25690. }
  25691. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25692. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25693. });
  25694. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25695. if (!canvas) {
  25696. return;
  25697. }
  25698. canvas.removeEventListener("keydown", _this._onKeyDown);
  25699. canvas.removeEventListener("keyup", _this._onKeyUp);
  25700. });
  25701. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25702. var canvas = this._engine.getRenderingCanvas();
  25703. if (!canvas) {
  25704. return;
  25705. }
  25706. if (attachMove) {
  25707. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25708. // Wheel
  25709. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25710. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25711. }
  25712. if (attachDown) {
  25713. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25714. }
  25715. if (attachUp) {
  25716. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25717. }
  25718. canvas.tabIndex = 1;
  25719. };
  25720. /** Detaches all event handlers*/
  25721. Scene.prototype.detachControl = function () {
  25722. var engine = this.getEngine();
  25723. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25724. var canvas = engine.getRenderingCanvas();
  25725. if (!canvas) {
  25726. return;
  25727. }
  25728. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25729. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25730. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25731. if (this._onCanvasBlurObserver) {
  25732. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25733. }
  25734. if (this._onCanvasFocusObserver) {
  25735. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25736. }
  25737. // Wheel
  25738. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25739. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25740. // Keyboard
  25741. canvas.removeEventListener("keydown", this._onKeyDown);
  25742. canvas.removeEventListener("keyup", this._onKeyUp);
  25743. // Observables
  25744. this.onKeyboardObservable.clear();
  25745. this.onPreKeyboardObservable.clear();
  25746. this.onPointerObservable.clear();
  25747. this.onPrePointerObservable.clear();
  25748. };
  25749. /**
  25750. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25751. * Delay loaded resources are not taking in account
  25752. * @return true if all required resources are ready
  25753. */
  25754. Scene.prototype.isReady = function () {
  25755. if (this._isDisposed) {
  25756. return false;
  25757. }
  25758. if (this._pendingData.length > 0) {
  25759. return false;
  25760. }
  25761. var index;
  25762. var engine = this.getEngine();
  25763. // Geometries
  25764. for (index = 0; index < this._geometries.length; index++) {
  25765. var geometry = this._geometries[index];
  25766. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25767. return false;
  25768. }
  25769. }
  25770. // Meshes
  25771. for (index = 0; index < this.meshes.length; index++) {
  25772. var mesh = this.meshes[index];
  25773. if (!mesh.isEnabled()) {
  25774. continue;
  25775. }
  25776. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25777. continue;
  25778. }
  25779. if (!mesh.isReady(true)) {
  25780. return false;
  25781. }
  25782. // Effect layers
  25783. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25784. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25785. var layer = _a[_i];
  25786. if (!layer.hasMesh(mesh)) {
  25787. continue;
  25788. }
  25789. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25790. var subMesh = _c[_b];
  25791. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25792. return false;
  25793. }
  25794. }
  25795. }
  25796. }
  25797. // Post-processes
  25798. if (this.activeCameras && this.activeCameras.length > 0) {
  25799. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25800. var camera = _e[_d];
  25801. if (!camera.isReady(true)) {
  25802. return false;
  25803. }
  25804. }
  25805. }
  25806. else if (this.activeCamera) {
  25807. if (!this.activeCamera.isReady(true)) {
  25808. return false;
  25809. }
  25810. }
  25811. // Particles
  25812. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25813. var particleSystem = _g[_f];
  25814. if (!particleSystem.isReady()) {
  25815. return false;
  25816. }
  25817. }
  25818. return true;
  25819. };
  25820. /** Resets all cached information relative to material (including effect and visibility) */
  25821. Scene.prototype.resetCachedMaterial = function () {
  25822. this._cachedMaterial = null;
  25823. this._cachedEffect = null;
  25824. this._cachedVisibility = null;
  25825. };
  25826. /**
  25827. * Registers a function to be called before every frame render
  25828. * @param func defines the function to register
  25829. */
  25830. Scene.prototype.registerBeforeRender = function (func) {
  25831. this.onBeforeRenderObservable.add(func);
  25832. };
  25833. /**
  25834. * Unregisters a function called before every frame render
  25835. * @param func defines the function to unregister
  25836. */
  25837. Scene.prototype.unregisterBeforeRender = function (func) {
  25838. this.onBeforeRenderObservable.removeCallback(func);
  25839. };
  25840. /**
  25841. * Registers a function to be called after every frame render
  25842. * @param func defines the function to register
  25843. */
  25844. Scene.prototype.registerAfterRender = function (func) {
  25845. this.onAfterRenderObservable.add(func);
  25846. };
  25847. /**
  25848. * Unregisters a function called after every frame render
  25849. * @param func defines the function to unregister
  25850. */
  25851. Scene.prototype.unregisterAfterRender = function (func) {
  25852. this.onAfterRenderObservable.removeCallback(func);
  25853. };
  25854. Scene.prototype._executeOnceBeforeRender = function (func) {
  25855. var _this = this;
  25856. var execFunc = function () {
  25857. func();
  25858. setTimeout(function () {
  25859. _this.unregisterBeforeRender(execFunc);
  25860. });
  25861. };
  25862. this.registerBeforeRender(execFunc);
  25863. };
  25864. /**
  25865. * The provided function will run before render once and will be disposed afterwards.
  25866. * A timeout delay can be provided so that the function will be executed in N ms.
  25867. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25868. * @param func The function to be executed.
  25869. * @param timeout optional delay in ms
  25870. */
  25871. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25872. var _this = this;
  25873. if (timeout !== undefined) {
  25874. setTimeout(function () {
  25875. _this._executeOnceBeforeRender(func);
  25876. }, timeout);
  25877. }
  25878. else {
  25879. this._executeOnceBeforeRender(func);
  25880. }
  25881. };
  25882. /** @hidden */
  25883. Scene.prototype._addPendingData = function (data) {
  25884. this._pendingData.push(data);
  25885. };
  25886. /** @hidden */
  25887. Scene.prototype._removePendingData = function (data) {
  25888. var wasLoading = this.isLoading;
  25889. var index = this._pendingData.indexOf(data);
  25890. if (index !== -1) {
  25891. this._pendingData.splice(index, 1);
  25892. }
  25893. if (wasLoading && !this.isLoading) {
  25894. this.onDataLoadedObservable.notifyObservers(this);
  25895. }
  25896. };
  25897. /**
  25898. * Returns the number of items waiting to be loaded
  25899. * @returns the number of items waiting to be loaded
  25900. */
  25901. Scene.prototype.getWaitingItemsCount = function () {
  25902. return this._pendingData.length;
  25903. };
  25904. Object.defineProperty(Scene.prototype, "isLoading", {
  25905. /**
  25906. * Returns a boolean indicating if the scene is still loading data
  25907. */
  25908. get: function () {
  25909. return this._pendingData.length > 0;
  25910. },
  25911. enumerable: true,
  25912. configurable: true
  25913. });
  25914. /**
  25915. * Registers a function to be executed when the scene is ready
  25916. * @param {Function} func - the function to be executed
  25917. */
  25918. Scene.prototype.executeWhenReady = function (func) {
  25919. var _this = this;
  25920. this.onReadyObservable.add(func);
  25921. if (this._executeWhenReadyTimeoutId !== -1) {
  25922. return;
  25923. }
  25924. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25925. _this._checkIsReady();
  25926. }, 150);
  25927. };
  25928. /**
  25929. * Returns a promise that resolves when the scene is ready
  25930. * @returns A promise that resolves when the scene is ready
  25931. */
  25932. Scene.prototype.whenReadyAsync = function () {
  25933. var _this = this;
  25934. return new Promise(function (resolve) {
  25935. _this.executeWhenReady(function () {
  25936. resolve();
  25937. });
  25938. });
  25939. };
  25940. /** @hidden */
  25941. Scene.prototype._checkIsReady = function () {
  25942. var _this = this;
  25943. if (this.isReady()) {
  25944. this.onReadyObservable.notifyObservers(this);
  25945. this.onReadyObservable.clear();
  25946. this._executeWhenReadyTimeoutId = -1;
  25947. return;
  25948. }
  25949. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25950. _this._checkIsReady();
  25951. }, 150);
  25952. };
  25953. // Animations
  25954. /**
  25955. * Will start the animation sequence of a given target
  25956. * @param target defines the target
  25957. * @param from defines from which frame should animation start
  25958. * @param to defines until which frame should animation run.
  25959. * @param weight defines the weight to apply to the animation (1.0 by default)
  25960. * @param loop defines if the animation loops
  25961. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25962. * @param onAnimationEnd defines the function to be executed when the animation ends
  25963. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25964. * @returns the animatable object created for this animation
  25965. */
  25966. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25967. if (weight === void 0) { weight = 1.0; }
  25968. if (speedRatio === void 0) { speedRatio = 1.0; }
  25969. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25970. returnedAnimatable.weight = weight;
  25971. return returnedAnimatable;
  25972. };
  25973. /**
  25974. * Will start the animation sequence of a given target
  25975. * @param target defines the target
  25976. * @param from defines from which frame should animation start
  25977. * @param to defines until which frame should animation run.
  25978. * @param loop defines if the animation loops
  25979. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25980. * @param onAnimationEnd defines the function to be executed when the animation ends
  25981. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25982. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25983. * @returns the animatable object created for this animation
  25984. */
  25985. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25986. if (speedRatio === void 0) { speedRatio = 1.0; }
  25987. if (stopCurrent === void 0) { stopCurrent = true; }
  25988. if (from > to && speedRatio > 0) {
  25989. speedRatio *= -1;
  25990. }
  25991. if (stopCurrent) {
  25992. this.stopAnimation(target);
  25993. }
  25994. if (!animatable) {
  25995. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25996. }
  25997. // Local animations
  25998. if (target.animations) {
  25999. animatable.appendAnimations(target, target.animations);
  26000. }
  26001. // Children animations
  26002. if (target.getAnimatables) {
  26003. var animatables = target.getAnimatables();
  26004. for (var index = 0; index < animatables.length; index++) {
  26005. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  26006. }
  26007. }
  26008. animatable.reset();
  26009. return animatable;
  26010. };
  26011. /**
  26012. * Begin a new animation on a given node
  26013. * @param target defines the target where the animation will take place
  26014. * @param animations defines the list of animations to start
  26015. * @param from defines the initial value
  26016. * @param to defines the final value
  26017. * @param loop defines if you want animation to loop (off by default)
  26018. * @param speedRatio defines the speed ratio to apply to all animations
  26019. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26020. * @returns the list of created animatables
  26021. */
  26022. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26023. if (speedRatio === undefined) {
  26024. speedRatio = 1.0;
  26025. }
  26026. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26027. return animatable;
  26028. };
  26029. /**
  26030. * Begin a new animation on a given node and its hierarchy
  26031. * @param target defines the root node where the animation will take place
  26032. * @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.
  26033. * @param animations defines the list of animations to start
  26034. * @param from defines the initial value
  26035. * @param to defines the final value
  26036. * @param loop defines if you want animation to loop (off by default)
  26037. * @param speedRatio defines the speed ratio to apply to all animations
  26038. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26039. * @returns the list of animatables created for all nodes
  26040. */
  26041. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26042. var children = target.getDescendants(directDescendantsOnly);
  26043. var result = [];
  26044. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26045. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26046. var child = children_1[_i];
  26047. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26048. }
  26049. return result;
  26050. };
  26051. /**
  26052. * Gets the animatable associated with a specific target
  26053. * @param target defines the target of the animatable
  26054. * @returns the required animatable if found
  26055. */
  26056. Scene.prototype.getAnimatableByTarget = function (target) {
  26057. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26058. if (this._activeAnimatables[index].target === target) {
  26059. return this._activeAnimatables[index];
  26060. }
  26061. }
  26062. return null;
  26063. };
  26064. /**
  26065. * Gets all animatables associated with a given target
  26066. * @param target defines the target to look animatables for
  26067. * @returns an array of Animatables
  26068. */
  26069. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26070. var result = [];
  26071. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26072. if (this._activeAnimatables[index].target === target) {
  26073. result.push(this._activeAnimatables[index]);
  26074. }
  26075. }
  26076. return result;
  26077. };
  26078. Object.defineProperty(Scene.prototype, "animatables", {
  26079. /**
  26080. * Gets all animatable attached to the scene
  26081. */
  26082. get: function () {
  26083. return this._activeAnimatables;
  26084. },
  26085. enumerable: true,
  26086. configurable: true
  26087. });
  26088. /**
  26089. * Will stop the animation of the given target
  26090. * @param target - the target
  26091. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  26092. */
  26093. Scene.prototype.stopAnimation = function (target, animationName) {
  26094. var animatables = this.getAllAnimatablesByTarget(target);
  26095. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26096. var animatable = animatables_1[_i];
  26097. animatable.stop(animationName);
  26098. }
  26099. };
  26100. /**
  26101. * Stops and removes all animations that have been applied to the scene
  26102. */
  26103. Scene.prototype.stopAllAnimations = function () {
  26104. if (this._activeAnimatables) {
  26105. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26106. this._activeAnimatables[i].stop();
  26107. }
  26108. this._activeAnimatables = [];
  26109. }
  26110. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26111. var group = _a[_i];
  26112. group.stop();
  26113. }
  26114. };
  26115. Scene.prototype._animate = function () {
  26116. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26117. return;
  26118. }
  26119. // Getting time
  26120. var now = BABYLON.Tools.Now;
  26121. if (!this._animationTimeLast) {
  26122. if (this._pendingData.length > 0) {
  26123. return;
  26124. }
  26125. this._animationTimeLast = now;
  26126. }
  26127. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26128. this._animationTime += deltaTime;
  26129. this._animationTimeLast = now;
  26130. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26131. this._activeAnimatables[index]._animate(this._animationTime);
  26132. }
  26133. // Late animation bindings
  26134. this._processLateAnimationBindings();
  26135. };
  26136. /** @hidden */
  26137. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26138. var target = runtimeAnimation.target;
  26139. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26140. if (!target._lateAnimationHolders) {
  26141. target._lateAnimationHolders = {};
  26142. }
  26143. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26144. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26145. totalWeight: 0,
  26146. animations: [],
  26147. originalValue: originalValue
  26148. };
  26149. }
  26150. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26151. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26152. };
  26153. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26154. var normalizer = 1.0;
  26155. var finalPosition = BABYLON.Tmp.Vector3[0];
  26156. var finalScaling = BABYLON.Tmp.Vector3[1];
  26157. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26158. var startIndex = 0;
  26159. var originalAnimation = holder.animations[0];
  26160. var originalValue = holder.originalValue;
  26161. var scale = 1;
  26162. if (holder.totalWeight < 1.0) {
  26163. // We need to mix the original value in
  26164. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26165. scale = 1.0 - holder.totalWeight;
  26166. }
  26167. else {
  26168. startIndex = 1;
  26169. // We need to normalize the weights
  26170. normalizer = holder.totalWeight;
  26171. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26172. scale = originalAnimation.weight / normalizer;
  26173. if (scale == 1) {
  26174. return originalAnimation.currentValue;
  26175. }
  26176. }
  26177. finalScaling.scaleInPlace(scale);
  26178. finalPosition.scaleInPlace(scale);
  26179. finalQuaternion.scaleInPlace(scale);
  26180. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26181. var runtimeAnimation = holder.animations[animIndex];
  26182. var scale = runtimeAnimation.weight / normalizer;
  26183. var currentPosition = BABYLON.Tmp.Vector3[2];
  26184. var currentScaling = BABYLON.Tmp.Vector3[3];
  26185. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26186. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26187. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26188. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26189. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26190. }
  26191. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26192. return originalAnimation._workValue;
  26193. };
  26194. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26195. var originalAnimation = holder.animations[0];
  26196. var originalValue = holder.originalValue;
  26197. if (holder.animations.length === 1) {
  26198. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26199. }
  26200. var normalizer = 1.0;
  26201. var quaternions;
  26202. var weights;
  26203. if (holder.totalWeight < 1.0) {
  26204. var scale = 1.0 - holder.totalWeight;
  26205. quaternions = [];
  26206. weights = [];
  26207. quaternions.push(originalValue);
  26208. weights.push(scale);
  26209. }
  26210. else {
  26211. if (holder.animations.length === 2) { // Slerp as soon as we can
  26212. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26213. }
  26214. quaternions = [];
  26215. weights = [];
  26216. normalizer = holder.totalWeight;
  26217. }
  26218. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26219. var runtimeAnimation = holder.animations[animIndex];
  26220. quaternions.push(runtimeAnimation.currentValue);
  26221. weights.push(runtimeAnimation.weight / normalizer);
  26222. }
  26223. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26224. var cumulativeAmount = 0;
  26225. var cumulativeQuaternion = null;
  26226. for (var index = 0; index < quaternions.length;) {
  26227. if (!cumulativeQuaternion) {
  26228. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26229. cumulativeAmount = weights[index] + weights[index + 1];
  26230. index += 2;
  26231. continue;
  26232. }
  26233. cumulativeAmount += weights[index];
  26234. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26235. index++;
  26236. }
  26237. return cumulativeQuaternion;
  26238. };
  26239. Scene.prototype._processLateAnimationBindings = function () {
  26240. if (!this._registeredForLateAnimationBindings.length) {
  26241. return;
  26242. }
  26243. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26244. var target = this._registeredForLateAnimationBindings.data[index];
  26245. for (var path in target._lateAnimationHolders) {
  26246. var holder = target._lateAnimationHolders[path];
  26247. var originalAnimation = holder.animations[0];
  26248. var originalValue = holder.originalValue;
  26249. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26250. var finalValue = void 0;
  26251. if (matrixDecomposeMode) {
  26252. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26253. }
  26254. else {
  26255. var quaternionMode = originalValue.w !== undefined;
  26256. if (quaternionMode) {
  26257. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26258. }
  26259. else {
  26260. var startIndex = 0;
  26261. var normalizer = 1.0;
  26262. if (holder.totalWeight < 1.0) {
  26263. // We need to mix the original value in
  26264. if (originalValue.scale) {
  26265. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26266. }
  26267. else {
  26268. finalValue = originalValue * (1.0 - holder.totalWeight);
  26269. }
  26270. }
  26271. else {
  26272. // We need to normalize the weights
  26273. normalizer = holder.totalWeight;
  26274. var scale_1 = originalAnimation.weight / normalizer;
  26275. if (scale_1 !== 1) {
  26276. if (originalAnimation.currentValue.scale) {
  26277. finalValue = originalAnimation.currentValue.scale(scale_1);
  26278. }
  26279. else {
  26280. finalValue = originalAnimation.currentValue * scale_1;
  26281. }
  26282. }
  26283. else {
  26284. finalValue = originalAnimation.currentValue;
  26285. }
  26286. startIndex = 1;
  26287. }
  26288. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26289. var runtimeAnimation = holder.animations[animIndex];
  26290. var scale = runtimeAnimation.weight / normalizer;
  26291. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26292. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26293. }
  26294. else {
  26295. finalValue += runtimeAnimation.currentValue * scale;
  26296. }
  26297. }
  26298. }
  26299. }
  26300. target[path] = finalValue;
  26301. }
  26302. target._lateAnimationHolders = {};
  26303. }
  26304. this._registeredForLateAnimationBindings.reset();
  26305. };
  26306. // Matrix
  26307. /** @hidden */
  26308. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26309. this._useAlternateCameraConfiguration = active;
  26310. };
  26311. /**
  26312. * Gets the current view matrix
  26313. * @returns a Matrix
  26314. */
  26315. Scene.prototype.getViewMatrix = function () {
  26316. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26317. };
  26318. /**
  26319. * Gets the current projection matrix
  26320. * @returns a Matrix
  26321. */
  26322. Scene.prototype.getProjectionMatrix = function () {
  26323. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26324. };
  26325. /**
  26326. * Gets the current transform matrix
  26327. * @returns a Matrix made of View * Projection
  26328. */
  26329. Scene.prototype.getTransformMatrix = function () {
  26330. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26331. };
  26332. /**
  26333. * Sets the current transform matrix
  26334. * @param view defines the View matrix to use
  26335. * @param projection defines the Projection matrix to use
  26336. */
  26337. Scene.prototype.setTransformMatrix = function (view, projection) {
  26338. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26339. return;
  26340. }
  26341. this._viewUpdateFlag = view.updateFlag;
  26342. this._projectionUpdateFlag = projection.updateFlag;
  26343. this._viewMatrix = view;
  26344. this._projectionMatrix = projection;
  26345. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26346. // Update frustum
  26347. if (!this._frustumPlanes) {
  26348. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26349. }
  26350. else {
  26351. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26352. }
  26353. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26354. var otherCamera = this.activeCamera._alternateCamera;
  26355. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26356. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26357. }
  26358. if (this._sceneUbo.useUbo) {
  26359. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26360. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26361. this._sceneUbo.update();
  26362. }
  26363. };
  26364. /** @hidden */
  26365. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26366. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26367. return;
  26368. }
  26369. this._alternateViewUpdateFlag = view.updateFlag;
  26370. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26371. this._alternateViewMatrix = view;
  26372. this._alternateProjectionMatrix = projection;
  26373. if (!this._alternateTransformMatrix) {
  26374. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26375. }
  26376. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26377. if (!this._alternateSceneUbo) {
  26378. this._createAlternateUbo();
  26379. }
  26380. if (this._alternateSceneUbo.useUbo) {
  26381. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26382. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26383. this._alternateSceneUbo.update();
  26384. }
  26385. };
  26386. /**
  26387. * Gets the uniform buffer used to store scene data
  26388. * @returns a UniformBuffer
  26389. */
  26390. Scene.prototype.getSceneUniformBuffer = function () {
  26391. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26392. };
  26393. /**
  26394. * Gets an unique (relatively to the current scene) Id
  26395. * @returns an unique number for the scene
  26396. */
  26397. Scene.prototype.getUniqueId = function () {
  26398. var result = Scene._uniqueIdCounter;
  26399. Scene._uniqueIdCounter++;
  26400. return result;
  26401. };
  26402. /**
  26403. * Add a mesh to the list of scene's meshes
  26404. * @param newMesh defines the mesh to add
  26405. * @param recursive if all child meshes should also be added to the scene
  26406. */
  26407. Scene.prototype.addMesh = function (newMesh, recursive) {
  26408. var _this = this;
  26409. if (recursive === void 0) { recursive = false; }
  26410. this.meshes.push(newMesh);
  26411. //notify the collision coordinator
  26412. if (this.collisionCoordinator) {
  26413. this.collisionCoordinator.onMeshAdded(newMesh);
  26414. }
  26415. newMesh._resyncLightSources();
  26416. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26417. if (recursive) {
  26418. newMesh.getChildMeshes().forEach(function (m) {
  26419. _this.addMesh(m);
  26420. });
  26421. }
  26422. };
  26423. /**
  26424. * Remove a mesh for the list of scene's meshes
  26425. * @param toRemove defines the mesh to remove
  26426. * @param recursive if all child meshes should also be removed from the scene
  26427. * @returns the index where the mesh was in the mesh list
  26428. */
  26429. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26430. var _this = this;
  26431. if (recursive === void 0) { recursive = false; }
  26432. var index = this.meshes.indexOf(toRemove);
  26433. if (index !== -1) {
  26434. // Remove from the scene if mesh found
  26435. this.meshes.splice(index, 1);
  26436. }
  26437. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26438. if (recursive) {
  26439. toRemove.getChildMeshes().forEach(function (m) {
  26440. _this.removeMesh(m);
  26441. });
  26442. }
  26443. return index;
  26444. };
  26445. /**
  26446. * Add a transform node to the list of scene's transform nodes
  26447. * @param newTransformNode defines the transform node to add
  26448. */
  26449. Scene.prototype.addTransformNode = function (newTransformNode) {
  26450. this.transformNodes.push(newTransformNode);
  26451. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26452. };
  26453. /**
  26454. * Remove a transform node for the list of scene's transform nodes
  26455. * @param toRemove defines the transform node to remove
  26456. * @returns the index where the transform node was in the transform node list
  26457. */
  26458. Scene.prototype.removeTransformNode = function (toRemove) {
  26459. var index = this.transformNodes.indexOf(toRemove);
  26460. if (index !== -1) {
  26461. // Remove from the scene if found
  26462. this.transformNodes.splice(index, 1);
  26463. }
  26464. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26465. return index;
  26466. };
  26467. /**
  26468. * Remove a skeleton for the list of scene's skeletons
  26469. * @param toRemove defines the skeleton to remove
  26470. * @returns the index where the skeleton was in the skeleton list
  26471. */
  26472. Scene.prototype.removeSkeleton = function (toRemove) {
  26473. var index = this.skeletons.indexOf(toRemove);
  26474. if (index !== -1) {
  26475. // Remove from the scene if found
  26476. this.skeletons.splice(index, 1);
  26477. }
  26478. return index;
  26479. };
  26480. /**
  26481. * Remove a morph target for the list of scene's morph targets
  26482. * @param toRemove defines the morph target to remove
  26483. * @returns the index where the morph target was in the morph target list
  26484. */
  26485. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26486. var index = this.morphTargetManagers.indexOf(toRemove);
  26487. if (index !== -1) {
  26488. // Remove from the scene if found
  26489. this.morphTargetManagers.splice(index, 1);
  26490. }
  26491. return index;
  26492. };
  26493. /**
  26494. * Remove a light for the list of scene's lights
  26495. * @param toRemove defines the light to remove
  26496. * @returns the index where the light was in the light list
  26497. */
  26498. Scene.prototype.removeLight = function (toRemove) {
  26499. var index = this.lights.indexOf(toRemove);
  26500. if (index !== -1) {
  26501. // Remove from meshes
  26502. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26503. var mesh = _a[_i];
  26504. mesh._removeLightSource(toRemove);
  26505. }
  26506. // Remove from the scene if mesh found
  26507. this.lights.splice(index, 1);
  26508. this.sortLightsByPriority();
  26509. }
  26510. this.onLightRemovedObservable.notifyObservers(toRemove);
  26511. return index;
  26512. };
  26513. /**
  26514. * Remove a camera for the list of scene's cameras
  26515. * @param toRemove defines the camera to remove
  26516. * @returns the index where the camera was in the camera list
  26517. */
  26518. Scene.prototype.removeCamera = function (toRemove) {
  26519. var index = this.cameras.indexOf(toRemove);
  26520. if (index !== -1) {
  26521. // Remove from the scene if mesh found
  26522. this.cameras.splice(index, 1);
  26523. }
  26524. // Remove from activeCameras
  26525. var index2 = this.activeCameras.indexOf(toRemove);
  26526. if (index2 !== -1) {
  26527. // Remove from the scene if mesh found
  26528. this.activeCameras.splice(index2, 1);
  26529. }
  26530. // Reset the activeCamera
  26531. if (this.activeCamera === toRemove) {
  26532. if (this.cameras.length > 0) {
  26533. this.activeCamera = this.cameras[0];
  26534. }
  26535. else {
  26536. this.activeCamera = null;
  26537. }
  26538. }
  26539. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26540. return index;
  26541. };
  26542. /**
  26543. * Remove a particle system for the list of scene's particle systems
  26544. * @param toRemove defines the particle system to remove
  26545. * @returns the index where the particle system was in the particle system list
  26546. */
  26547. Scene.prototype.removeParticleSystem = function (toRemove) {
  26548. var index = this.particleSystems.indexOf(toRemove);
  26549. if (index !== -1) {
  26550. this.particleSystems.splice(index, 1);
  26551. }
  26552. return index;
  26553. };
  26554. /**
  26555. * Remove a animation for the list of scene's animations
  26556. * @param toRemove defines the animation to remove
  26557. * @returns the index where the animation was in the animation list
  26558. */
  26559. Scene.prototype.removeAnimation = function (toRemove) {
  26560. var index = this.animations.indexOf(toRemove);
  26561. if (index !== -1) {
  26562. this.animations.splice(index, 1);
  26563. }
  26564. return index;
  26565. };
  26566. /**
  26567. * Removes the given animation group from this scene.
  26568. * @param toRemove The animation group to remove
  26569. * @returns The index of the removed animation group
  26570. */
  26571. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26572. var index = this.animationGroups.indexOf(toRemove);
  26573. if (index !== -1) {
  26574. this.animationGroups.splice(index, 1);
  26575. }
  26576. return index;
  26577. };
  26578. /**
  26579. * Removes the given multi-material from this scene.
  26580. * @param toRemove The multi-material to remove
  26581. * @returns The index of the removed multi-material
  26582. */
  26583. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26584. var index = this.multiMaterials.indexOf(toRemove);
  26585. if (index !== -1) {
  26586. this.multiMaterials.splice(index, 1);
  26587. }
  26588. return index;
  26589. };
  26590. /**
  26591. * Removes the given material from this scene.
  26592. * @param toRemove The material to remove
  26593. * @returns The index of the removed material
  26594. */
  26595. Scene.prototype.removeMaterial = function (toRemove) {
  26596. var index = this.materials.indexOf(toRemove);
  26597. if (index !== -1) {
  26598. this.materials.splice(index, 1);
  26599. }
  26600. return index;
  26601. };
  26602. /**
  26603. * Removes the given lens flare system from this scene.
  26604. * @param toRemove The lens flare system to remove
  26605. * @returns The index of the removed lens flare system
  26606. */
  26607. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26608. var index = this.lensFlareSystems.indexOf(toRemove);
  26609. if (index !== -1) {
  26610. this.lensFlareSystems.splice(index, 1);
  26611. }
  26612. return index;
  26613. };
  26614. /**
  26615. * Removes the given action manager from this scene.
  26616. * @param toRemove The action manager to remove
  26617. * @returns The index of the removed action manager
  26618. */
  26619. Scene.prototype.removeActionManager = function (toRemove) {
  26620. var index = this._actionManagers.indexOf(toRemove);
  26621. if (index !== -1) {
  26622. this._actionManagers.splice(index, 1);
  26623. }
  26624. return index;
  26625. };
  26626. /**
  26627. * Removes the given effect layer from this scene.
  26628. * @param toRemove defines the effect layer to remove
  26629. * @returns the index of the removed effect layer
  26630. */
  26631. Scene.prototype.removeEffectLayer = function (toRemove) {
  26632. var index = this.effectLayers.indexOf(toRemove);
  26633. if (index !== -1) {
  26634. this.effectLayers.splice(index, 1);
  26635. }
  26636. return index;
  26637. };
  26638. /**
  26639. * Removes the given texture from this scene.
  26640. * @param toRemove The texture to remove
  26641. * @returns The index of the removed texture
  26642. */
  26643. Scene.prototype.removeTexture = function (toRemove) {
  26644. var index = this.textures.indexOf(toRemove);
  26645. if (index !== -1) {
  26646. this.textures.splice(index, 1);
  26647. }
  26648. return index;
  26649. };
  26650. /**
  26651. * Adds the given light to this scene
  26652. * @param newLight The light to add
  26653. */
  26654. Scene.prototype.addLight = function (newLight) {
  26655. this.lights.push(newLight);
  26656. this.sortLightsByPriority();
  26657. // Add light to all meshes (To support if the light is removed and then readded)
  26658. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26659. var mesh = _a[_i];
  26660. if (mesh._lightSources.indexOf(newLight) === -1) {
  26661. mesh._lightSources.push(newLight);
  26662. mesh._resyncLightSources();
  26663. }
  26664. }
  26665. this.onNewLightAddedObservable.notifyObservers(newLight);
  26666. };
  26667. /**
  26668. * Sorts the list list based on light priorities
  26669. */
  26670. Scene.prototype.sortLightsByPriority = function () {
  26671. if (this.requireLightSorting) {
  26672. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26673. }
  26674. };
  26675. /**
  26676. * Adds the given camera to this scene
  26677. * @param newCamera The camera to add
  26678. */
  26679. Scene.prototype.addCamera = function (newCamera) {
  26680. this.cameras.push(newCamera);
  26681. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26682. };
  26683. /**
  26684. * Adds the given skeleton to this scene
  26685. * @param newSkeleton The skeleton to add
  26686. */
  26687. Scene.prototype.addSkeleton = function (newSkeleton) {
  26688. this.skeletons.push(newSkeleton);
  26689. };
  26690. /**
  26691. * Adds the given particle system to this scene
  26692. * @param newParticleSystem The particle system to add
  26693. */
  26694. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26695. this.particleSystems.push(newParticleSystem);
  26696. };
  26697. /**
  26698. * Adds the given animation to this scene
  26699. * @param newAnimation The animation to add
  26700. */
  26701. Scene.prototype.addAnimation = function (newAnimation) {
  26702. this.animations.push(newAnimation);
  26703. };
  26704. /**
  26705. * Adds the given animation group to this scene.
  26706. * @param newAnimationGroup The animation group to add
  26707. */
  26708. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26709. this.animationGroups.push(newAnimationGroup);
  26710. };
  26711. /**
  26712. * Adds the given multi-material to this scene
  26713. * @param newMultiMaterial The multi-material to add
  26714. */
  26715. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26716. this.multiMaterials.push(newMultiMaterial);
  26717. };
  26718. /**
  26719. * Adds the given material to this scene
  26720. * @param newMaterial The material to add
  26721. */
  26722. Scene.prototype.addMaterial = function (newMaterial) {
  26723. this.materials.push(newMaterial);
  26724. };
  26725. /**
  26726. * Adds the given morph target to this scene
  26727. * @param newMorphTargetManager The morph target to add
  26728. */
  26729. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26730. this.morphTargetManagers.push(newMorphTargetManager);
  26731. };
  26732. /**
  26733. * Adds the given geometry to this scene
  26734. * @param newGeometry The geometry to add
  26735. */
  26736. Scene.prototype.addGeometry = function (newGeometry) {
  26737. this._geometries.push(newGeometry);
  26738. };
  26739. /**
  26740. * Adds the given lens flare system to this scene
  26741. * @param newLensFlareSystem The lens flare system to add
  26742. */
  26743. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26744. this.lensFlareSystems.push(newLensFlareSystem);
  26745. };
  26746. /**
  26747. * Adds the given effect layer to this scene
  26748. * @param newEffectLayer defines the effect layer to add
  26749. */
  26750. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26751. this.effectLayers.push(newEffectLayer);
  26752. };
  26753. /**
  26754. * Adds the given action manager to this scene
  26755. * @param newActionManager The action manager to add
  26756. */
  26757. Scene.prototype.addActionManager = function (newActionManager) {
  26758. this._actionManagers.push(newActionManager);
  26759. };
  26760. /**
  26761. * Adds the given texture to this scene.
  26762. * @param newTexture The texture to add
  26763. */
  26764. Scene.prototype.addTexture = function (newTexture) {
  26765. this.textures.push(newTexture);
  26766. };
  26767. /**
  26768. * Switch active camera
  26769. * @param newCamera defines the new active camera
  26770. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26771. */
  26772. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26773. if (attachControl === void 0) { attachControl = true; }
  26774. var canvas = this._engine.getRenderingCanvas();
  26775. if (!canvas) {
  26776. return;
  26777. }
  26778. if (this.activeCamera) {
  26779. this.activeCamera.detachControl(canvas);
  26780. }
  26781. this.activeCamera = newCamera;
  26782. if (attachControl) {
  26783. newCamera.attachControl(canvas);
  26784. }
  26785. };
  26786. /**
  26787. * sets the active camera of the scene using its ID
  26788. * @param id defines the camera's ID
  26789. * @return the new active camera or null if none found.
  26790. */
  26791. Scene.prototype.setActiveCameraByID = function (id) {
  26792. var camera = this.getCameraByID(id);
  26793. if (camera) {
  26794. this.activeCamera = camera;
  26795. return camera;
  26796. }
  26797. return null;
  26798. };
  26799. /**
  26800. * sets the active camera of the scene using its name
  26801. * @param name defines the camera's name
  26802. * @returns the new active camera or null if none found.
  26803. */
  26804. Scene.prototype.setActiveCameraByName = function (name) {
  26805. var camera = this.getCameraByName(name);
  26806. if (camera) {
  26807. this.activeCamera = camera;
  26808. return camera;
  26809. }
  26810. return null;
  26811. };
  26812. /**
  26813. * get an animation group using its name
  26814. * @param name defines the material's name
  26815. * @return the animation group or null if none found.
  26816. */
  26817. Scene.prototype.getAnimationGroupByName = function (name) {
  26818. for (var index = 0; index < this.animationGroups.length; index++) {
  26819. if (this.animationGroups[index].name === name) {
  26820. return this.animationGroups[index];
  26821. }
  26822. }
  26823. return null;
  26824. };
  26825. /**
  26826. * get a material using its id
  26827. * @param id defines the material's ID
  26828. * @return the material or null if none found.
  26829. */
  26830. Scene.prototype.getMaterialByID = function (id) {
  26831. for (var index = 0; index < this.materials.length; index++) {
  26832. if (this.materials[index].id === id) {
  26833. return this.materials[index];
  26834. }
  26835. }
  26836. return null;
  26837. };
  26838. /**
  26839. * Gets a material using its name
  26840. * @param name defines the material's name
  26841. * @return the material or null if none found.
  26842. */
  26843. Scene.prototype.getMaterialByName = function (name) {
  26844. for (var index = 0; index < this.materials.length; index++) {
  26845. if (this.materials[index].name === name) {
  26846. return this.materials[index];
  26847. }
  26848. }
  26849. return null;
  26850. };
  26851. /**
  26852. * Gets a lens flare system using its name
  26853. * @param name defines the name to look for
  26854. * @returns the lens flare system or null if not found
  26855. */
  26856. Scene.prototype.getLensFlareSystemByName = function (name) {
  26857. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26858. if (this.lensFlareSystems[index].name === name) {
  26859. return this.lensFlareSystems[index];
  26860. }
  26861. }
  26862. return null;
  26863. };
  26864. /**
  26865. * Gets a lens flare system using its id
  26866. * @param id defines the id to look for
  26867. * @returns the lens flare system or null if not found
  26868. */
  26869. Scene.prototype.getLensFlareSystemByID = function (id) {
  26870. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26871. if (this.lensFlareSystems[index].id === id) {
  26872. return this.lensFlareSystems[index];
  26873. }
  26874. }
  26875. return null;
  26876. };
  26877. /**
  26878. * Gets a camera using its id
  26879. * @param id defines the id to look for
  26880. * @returns the camera or null if not found
  26881. */
  26882. Scene.prototype.getCameraByID = function (id) {
  26883. for (var index = 0; index < this.cameras.length; index++) {
  26884. if (this.cameras[index].id === id) {
  26885. return this.cameras[index];
  26886. }
  26887. }
  26888. return null;
  26889. };
  26890. /**
  26891. * Gets a camera using its unique id
  26892. * @param uniqueId defines the unique id to look for
  26893. * @returns the camera or null if not found
  26894. */
  26895. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26896. for (var index = 0; index < this.cameras.length; index++) {
  26897. if (this.cameras[index].uniqueId === uniqueId) {
  26898. return this.cameras[index];
  26899. }
  26900. }
  26901. return null;
  26902. };
  26903. /**
  26904. * Gets a camera using its name
  26905. * @param name defines the camera's name
  26906. * @return the camera or null if none found.
  26907. */
  26908. Scene.prototype.getCameraByName = function (name) {
  26909. for (var index = 0; index < this.cameras.length; index++) {
  26910. if (this.cameras[index].name === name) {
  26911. return this.cameras[index];
  26912. }
  26913. }
  26914. return null;
  26915. };
  26916. /**
  26917. * Gets a bone using its id
  26918. * @param id defines the bone's id
  26919. * @return the bone or null if not found
  26920. */
  26921. Scene.prototype.getBoneByID = function (id) {
  26922. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26923. var skeleton = this.skeletons[skeletonIndex];
  26924. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26925. if (skeleton.bones[boneIndex].id === id) {
  26926. return skeleton.bones[boneIndex];
  26927. }
  26928. }
  26929. }
  26930. return null;
  26931. };
  26932. /**
  26933. * Gets a bone using its id
  26934. * @param name defines the bone's name
  26935. * @return the bone or null if not found
  26936. */
  26937. Scene.prototype.getBoneByName = function (name) {
  26938. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26939. var skeleton = this.skeletons[skeletonIndex];
  26940. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26941. if (skeleton.bones[boneIndex].name === name) {
  26942. return skeleton.bones[boneIndex];
  26943. }
  26944. }
  26945. }
  26946. return null;
  26947. };
  26948. /**
  26949. * Gets a light node using its name
  26950. * @param name defines the the light's name
  26951. * @return the light or null if none found.
  26952. */
  26953. Scene.prototype.getLightByName = function (name) {
  26954. for (var index = 0; index < this.lights.length; index++) {
  26955. if (this.lights[index].name === name) {
  26956. return this.lights[index];
  26957. }
  26958. }
  26959. return null;
  26960. };
  26961. /**
  26962. * Gets a light node using its id
  26963. * @param id defines the light's id
  26964. * @return the light or null if none found.
  26965. */
  26966. Scene.prototype.getLightByID = function (id) {
  26967. for (var index = 0; index < this.lights.length; index++) {
  26968. if (this.lights[index].id === id) {
  26969. return this.lights[index];
  26970. }
  26971. }
  26972. return null;
  26973. };
  26974. /**
  26975. * Gets a light node using its scene-generated unique ID
  26976. * @param uniqueId defines the light's unique id
  26977. * @return the light or null if none found.
  26978. */
  26979. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26980. for (var index = 0; index < this.lights.length; index++) {
  26981. if (this.lights[index].uniqueId === uniqueId) {
  26982. return this.lights[index];
  26983. }
  26984. }
  26985. return null;
  26986. };
  26987. /**
  26988. * Gets a particle system by id
  26989. * @param id defines the particle system id
  26990. * @return the corresponding system or null if none found
  26991. */
  26992. Scene.prototype.getParticleSystemByID = function (id) {
  26993. for (var index = 0; index < this.particleSystems.length; index++) {
  26994. if (this.particleSystems[index].id === id) {
  26995. return this.particleSystems[index];
  26996. }
  26997. }
  26998. return null;
  26999. };
  27000. /**
  27001. * Gets a geometry using its ID
  27002. * @param id defines the geometry's id
  27003. * @return the geometry or null if none found.
  27004. */
  27005. Scene.prototype.getGeometryByID = function (id) {
  27006. for (var index = 0; index < this._geometries.length; index++) {
  27007. if (this._geometries[index].id === id) {
  27008. return this._geometries[index];
  27009. }
  27010. }
  27011. return null;
  27012. };
  27013. /**
  27014. * Add a new geometry to this scene
  27015. * @param geometry defines the geometry to be added to the scene.
  27016. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27017. * @return a boolean defining if the geometry was added or not
  27018. */
  27019. Scene.prototype.pushGeometry = function (geometry, force) {
  27020. if (!force && this.getGeometryByID(geometry.id)) {
  27021. return false;
  27022. }
  27023. this._geometries.push(geometry);
  27024. //notify the collision coordinator
  27025. if (this.collisionCoordinator) {
  27026. this.collisionCoordinator.onGeometryAdded(geometry);
  27027. }
  27028. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27029. return true;
  27030. };
  27031. /**
  27032. * Removes an existing geometry
  27033. * @param geometry defines the geometry to be removed from the scene
  27034. * @return a boolean defining if the geometry was removed or not
  27035. */
  27036. Scene.prototype.removeGeometry = function (geometry) {
  27037. var index = this._geometries.indexOf(geometry);
  27038. if (index > -1) {
  27039. this._geometries.splice(index, 1);
  27040. //notify the collision coordinator
  27041. if (this.collisionCoordinator) {
  27042. this.collisionCoordinator.onGeometryDeleted(geometry);
  27043. }
  27044. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27045. return true;
  27046. }
  27047. return false;
  27048. };
  27049. /**
  27050. * Gets the list of geometries attached to the scene
  27051. * @returns an array of Geometry
  27052. */
  27053. Scene.prototype.getGeometries = function () {
  27054. return this._geometries;
  27055. };
  27056. /**
  27057. * Gets the first added mesh found of a given ID
  27058. * @param id defines the id to search for
  27059. * @return the mesh found or null if not found at all
  27060. */
  27061. Scene.prototype.getMeshByID = function (id) {
  27062. for (var index = 0; index < this.meshes.length; index++) {
  27063. if (this.meshes[index].id === id) {
  27064. return this.meshes[index];
  27065. }
  27066. }
  27067. return null;
  27068. };
  27069. /**
  27070. * Gets a list of meshes using their id
  27071. * @param id defines the id to search for
  27072. * @returns a list of meshes
  27073. */
  27074. Scene.prototype.getMeshesByID = function (id) {
  27075. return this.meshes.filter(function (m) {
  27076. return m.id === id;
  27077. });
  27078. };
  27079. /**
  27080. * Gets the first added transform node found of a given ID
  27081. * @param id defines the id to search for
  27082. * @return the found transform node or null if not found at all.
  27083. */
  27084. Scene.prototype.getTransformNodeByID = function (id) {
  27085. for (var index = 0; index < this.transformNodes.length; index++) {
  27086. if (this.transformNodes[index].id === id) {
  27087. return this.transformNodes[index];
  27088. }
  27089. }
  27090. return null;
  27091. };
  27092. /**
  27093. * Gets a list of transform nodes using their id
  27094. * @param id defines the id to search for
  27095. * @returns a list of transform nodes
  27096. */
  27097. Scene.prototype.getTransformNodesByID = function (id) {
  27098. return this.transformNodes.filter(function (m) {
  27099. return m.id === id;
  27100. });
  27101. };
  27102. /**
  27103. * Gets a mesh with its auto-generated unique id
  27104. * @param uniqueId defines the unique id to search for
  27105. * @return the found mesh or null if not found at all.
  27106. */
  27107. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27108. for (var index = 0; index < this.meshes.length; index++) {
  27109. if (this.meshes[index].uniqueId === uniqueId) {
  27110. return this.meshes[index];
  27111. }
  27112. }
  27113. return null;
  27114. };
  27115. /**
  27116. * Gets a the last added mesh using a given id
  27117. * @param id defines the id to search for
  27118. * @return the found mesh or null if not found at all.
  27119. */
  27120. Scene.prototype.getLastMeshByID = function (id) {
  27121. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27122. if (this.meshes[index].id === id) {
  27123. return this.meshes[index];
  27124. }
  27125. }
  27126. return null;
  27127. };
  27128. /**
  27129. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27130. * @param id defines the id to search for
  27131. * @return the found node or null if not found at all
  27132. */
  27133. Scene.prototype.getLastEntryByID = function (id) {
  27134. var index;
  27135. for (index = this.meshes.length - 1; index >= 0; index--) {
  27136. if (this.meshes[index].id === id) {
  27137. return this.meshes[index];
  27138. }
  27139. }
  27140. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27141. if (this.transformNodes[index].id === id) {
  27142. return this.transformNodes[index];
  27143. }
  27144. }
  27145. for (index = this.cameras.length - 1; index >= 0; index--) {
  27146. if (this.cameras[index].id === id) {
  27147. return this.cameras[index];
  27148. }
  27149. }
  27150. for (index = this.lights.length - 1; index >= 0; index--) {
  27151. if (this.lights[index].id === id) {
  27152. return this.lights[index];
  27153. }
  27154. }
  27155. return null;
  27156. };
  27157. /**
  27158. * Gets a node (Mesh, Camera, Light) using a given id
  27159. * @param id defines the id to search for
  27160. * @return the found node or null if not found at all
  27161. */
  27162. Scene.prototype.getNodeByID = function (id) {
  27163. var mesh = this.getMeshByID(id);
  27164. if (mesh) {
  27165. return mesh;
  27166. }
  27167. var light = this.getLightByID(id);
  27168. if (light) {
  27169. return light;
  27170. }
  27171. var camera = this.getCameraByID(id);
  27172. if (camera) {
  27173. return camera;
  27174. }
  27175. var bone = this.getBoneByID(id);
  27176. return bone;
  27177. };
  27178. /**
  27179. * Gets a node (Mesh, Camera, Light) using a given name
  27180. * @param name defines the name to search for
  27181. * @return the found node or null if not found at all.
  27182. */
  27183. Scene.prototype.getNodeByName = function (name) {
  27184. var mesh = this.getMeshByName(name);
  27185. if (mesh) {
  27186. return mesh;
  27187. }
  27188. var light = this.getLightByName(name);
  27189. if (light) {
  27190. return light;
  27191. }
  27192. var camera = this.getCameraByName(name);
  27193. if (camera) {
  27194. return camera;
  27195. }
  27196. var bone = this.getBoneByName(name);
  27197. return bone;
  27198. };
  27199. /**
  27200. * Gets a mesh using a given name
  27201. * @param name defines the name to search for
  27202. * @return the found mesh or null if not found at all.
  27203. */
  27204. Scene.prototype.getMeshByName = function (name) {
  27205. for (var index = 0; index < this.meshes.length; index++) {
  27206. if (this.meshes[index].name === name) {
  27207. return this.meshes[index];
  27208. }
  27209. }
  27210. return null;
  27211. };
  27212. /**
  27213. * Gets a transform node using a given name
  27214. * @param name defines the name to search for
  27215. * @return the found transform node or null if not found at all.
  27216. */
  27217. Scene.prototype.getTransformNodeByName = function (name) {
  27218. for (var index = 0; index < this.transformNodes.length; index++) {
  27219. if (this.transformNodes[index].name === name) {
  27220. return this.transformNodes[index];
  27221. }
  27222. }
  27223. return null;
  27224. };
  27225. /**
  27226. * Gets a sound using a given name
  27227. * @param name defines the name to search for
  27228. * @return the found sound or null if not found at all.
  27229. */
  27230. Scene.prototype.getSoundByName = function (name) {
  27231. var index;
  27232. if (BABYLON.AudioEngine) {
  27233. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27234. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27235. return this.mainSoundTrack.soundCollection[index];
  27236. }
  27237. }
  27238. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27239. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27240. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27241. return this.soundTracks[sdIndex].soundCollection[index];
  27242. }
  27243. }
  27244. }
  27245. }
  27246. return null;
  27247. };
  27248. /**
  27249. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27250. * @param id defines the id to search for
  27251. * @return the found skeleton or null if not found at all.
  27252. */
  27253. Scene.prototype.getLastSkeletonByID = function (id) {
  27254. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27255. if (this.skeletons[index].id === id) {
  27256. return this.skeletons[index];
  27257. }
  27258. }
  27259. return null;
  27260. };
  27261. /**
  27262. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27263. * @param id defines the id to search for
  27264. * @return the found skeleton or null if not found at all.
  27265. */
  27266. Scene.prototype.getSkeletonById = function (id) {
  27267. for (var index = 0; index < this.skeletons.length; index++) {
  27268. if (this.skeletons[index].id === id) {
  27269. return this.skeletons[index];
  27270. }
  27271. }
  27272. return null;
  27273. };
  27274. /**
  27275. * Gets a skeleton using a given name
  27276. * @param name defines the name to search for
  27277. * @return the found skeleton or null if not found at all.
  27278. */
  27279. Scene.prototype.getSkeletonByName = function (name) {
  27280. for (var index = 0; index < this.skeletons.length; index++) {
  27281. if (this.skeletons[index].name === name) {
  27282. return this.skeletons[index];
  27283. }
  27284. }
  27285. return null;
  27286. };
  27287. /**
  27288. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27289. * @param id defines the id to search for
  27290. * @return the found morph target manager or null if not found at all.
  27291. */
  27292. Scene.prototype.getMorphTargetManagerById = function (id) {
  27293. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27294. if (this.morphTargetManagers[index].uniqueId === id) {
  27295. return this.morphTargetManagers[index];
  27296. }
  27297. }
  27298. return null;
  27299. };
  27300. /**
  27301. * Gets a boolean indicating if the given mesh is active
  27302. * @param mesh defines the mesh to look for
  27303. * @returns true if the mesh is in the active list
  27304. */
  27305. Scene.prototype.isActiveMesh = function (mesh) {
  27306. return (this._activeMeshes.indexOf(mesh) !== -1);
  27307. };
  27308. /**
  27309. * Return a the first highlight layer of the scene with a given name.
  27310. * @param name The name of the highlight layer to look for.
  27311. * @return The highlight layer if found otherwise null.
  27312. */
  27313. Scene.prototype.getHighlightLayerByName = function (name) {
  27314. for (var index = 0; index < this.effectLayers.length; index++) {
  27315. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27316. return this.effectLayers[index];
  27317. }
  27318. }
  27319. return null;
  27320. };
  27321. /**
  27322. * Return a the first highlight layer of the scene with a given name.
  27323. * @param name The name of the highlight layer to look for.
  27324. * @return The highlight layer if found otherwise null.
  27325. */
  27326. Scene.prototype.getGlowLayerByName = function (name) {
  27327. for (var index = 0; index < this.effectLayers.length; index++) {
  27328. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27329. return this.effectLayers[index];
  27330. }
  27331. }
  27332. return null;
  27333. };
  27334. Object.defineProperty(Scene.prototype, "uid", {
  27335. /**
  27336. * Return a unique id as a string which can serve as an identifier for the scene
  27337. */
  27338. get: function () {
  27339. if (!this._uid) {
  27340. this._uid = BABYLON.Tools.RandomId();
  27341. }
  27342. return this._uid;
  27343. },
  27344. enumerable: true,
  27345. configurable: true
  27346. });
  27347. /**
  27348. * Add an externaly attached data from its key.
  27349. * This method call will fail and return false, if such key already exists.
  27350. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27351. * @param key the unique key that identifies the data
  27352. * @param data the data object to associate to the key for this Engine instance
  27353. * @return true if no such key were already present and the data was added successfully, false otherwise
  27354. */
  27355. Scene.prototype.addExternalData = function (key, data) {
  27356. if (!this._externalData) {
  27357. this._externalData = new BABYLON.StringDictionary();
  27358. }
  27359. return this._externalData.add(key, data);
  27360. };
  27361. /**
  27362. * Get an externaly attached data from its key
  27363. * @param key the unique key that identifies the data
  27364. * @return the associated data, if present (can be null), or undefined if not present
  27365. */
  27366. Scene.prototype.getExternalData = function (key) {
  27367. if (!this._externalData) {
  27368. return null;
  27369. }
  27370. return this._externalData.get(key);
  27371. };
  27372. /**
  27373. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27374. * @param key the unique key that identifies the data
  27375. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27376. * @return the associated data, can be null if the factory returned null.
  27377. */
  27378. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27379. if (!this._externalData) {
  27380. this._externalData = new BABYLON.StringDictionary();
  27381. }
  27382. return this._externalData.getOrAddWithFactory(key, factory);
  27383. };
  27384. /**
  27385. * Remove an externaly attached data from the Engine instance
  27386. * @param key the unique key that identifies the data
  27387. * @return true if the data was successfully removed, false if it doesn't exist
  27388. */
  27389. Scene.prototype.removeExternalData = function (key) {
  27390. return this._externalData.remove(key);
  27391. };
  27392. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27393. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27394. if (mesh.showSubMeshesBoundingBox) {
  27395. var boundingInfo = subMesh.getBoundingInfo();
  27396. if (boundingInfo !== null && boundingInfo !== undefined) {
  27397. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27398. }
  27399. }
  27400. var material = subMesh.getMaterial();
  27401. if (material !== null && material !== undefined) {
  27402. // Render targets
  27403. if (material.getRenderTargetTextures !== undefined) {
  27404. if (this._processedMaterials.indexOf(material) === -1) {
  27405. this._processedMaterials.push(material);
  27406. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27407. }
  27408. }
  27409. // Dispatch
  27410. this._activeIndices.addCount(subMesh.indexCount, false);
  27411. this._renderingManager.dispatch(subMesh, mesh, material);
  27412. }
  27413. }
  27414. };
  27415. /**
  27416. * Clear the processed materials smart array preventing retention point in material dispose.
  27417. */
  27418. Scene.prototype.freeProcessedMaterials = function () {
  27419. this._processedMaterials.dispose();
  27420. };
  27421. /**
  27422. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27423. */
  27424. Scene.prototype.freeActiveMeshes = function () {
  27425. this._activeMeshes.dispose();
  27426. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27427. this.activeCamera._activeMeshes.dispose();
  27428. }
  27429. if (this.activeCameras) {
  27430. for (var i = 0; i < this.activeCameras.length; i++) {
  27431. var activeCamera = this.activeCameras[i];
  27432. if (activeCamera && activeCamera._activeMeshes) {
  27433. activeCamera._activeMeshes.dispose();
  27434. }
  27435. }
  27436. }
  27437. };
  27438. /**
  27439. * Clear the info related to rendering groups preventing retention points during dispose.
  27440. */
  27441. Scene.prototype.freeRenderingGroups = function () {
  27442. if (this._renderingManager) {
  27443. this._renderingManager.freeRenderingGroups();
  27444. }
  27445. if (this.textures) {
  27446. for (var i = 0; i < this.textures.length; i++) {
  27447. var texture = this.textures[i];
  27448. if (texture && texture.renderList) {
  27449. texture.freeRenderingGroups();
  27450. }
  27451. }
  27452. }
  27453. };
  27454. /** @hidden */
  27455. Scene.prototype._isInIntermediateRendering = function () {
  27456. return this._intermediateRendering;
  27457. };
  27458. /**
  27459. * Defines the current active mesh candidate provider
  27460. * @param provider defines the provider to use
  27461. */
  27462. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27463. this._activeMeshCandidateProvider = provider;
  27464. };
  27465. /**
  27466. * Gets the current active mesh candidate provider
  27467. * @returns the current active mesh candidate provider
  27468. */
  27469. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27470. return this._activeMeshCandidateProvider;
  27471. };
  27472. /**
  27473. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27474. * @returns the current scene
  27475. */
  27476. Scene.prototype.freezeActiveMeshes = function () {
  27477. if (!this.activeCamera) {
  27478. return this;
  27479. }
  27480. if (!this._frustumPlanes) {
  27481. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27482. }
  27483. this._evaluateActiveMeshes();
  27484. this._activeMeshesFrozen = true;
  27485. return this;
  27486. };
  27487. /**
  27488. * Use this function to restart evaluating active meshes on every frame
  27489. * @returns the current scene
  27490. */
  27491. Scene.prototype.unfreezeActiveMeshes = function () {
  27492. this._activeMeshesFrozen = false;
  27493. return this;
  27494. };
  27495. Scene.prototype._evaluateActiveMeshes = function () {
  27496. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27497. return;
  27498. }
  27499. if (!this.activeCamera) {
  27500. return;
  27501. }
  27502. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27503. this.activeCamera._activeMeshes.reset();
  27504. this._activeMeshes.reset();
  27505. this._renderingManager.reset();
  27506. this._processedMaterials.reset();
  27507. this._activeParticleSystems.reset();
  27508. this._activeSkeletons.reset();
  27509. this._softwareSkinnedMeshes.reset();
  27510. if (this._boundingBoxRenderer) {
  27511. this._boundingBoxRenderer.reset();
  27512. }
  27513. // Meshes
  27514. var meshes;
  27515. var len;
  27516. var checkIsEnabled = true;
  27517. // Determine mesh candidates
  27518. if (this._activeMeshCandidateProvider !== undefined) {
  27519. // Use _activeMeshCandidateProvider
  27520. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27521. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27522. if (meshes !== undefined) {
  27523. len = meshes.length;
  27524. }
  27525. else {
  27526. len = 0;
  27527. }
  27528. }
  27529. else if (this._selectionOctree !== undefined) {
  27530. // Octree
  27531. var selection = this._selectionOctree.select(this._frustumPlanes);
  27532. meshes = selection.data;
  27533. len = selection.length;
  27534. }
  27535. else {
  27536. // Full scene traversal
  27537. len = this.meshes.length;
  27538. meshes = this.meshes;
  27539. }
  27540. // Check each mesh
  27541. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27542. mesh = meshes[meshIndex];
  27543. if (mesh.isBlocked) {
  27544. continue;
  27545. }
  27546. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27547. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27548. continue;
  27549. }
  27550. mesh.computeWorldMatrix();
  27551. // Intersections
  27552. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27553. this._meshesForIntersections.pushNoDuplicate(mesh);
  27554. }
  27555. // Switch to current LOD
  27556. meshLOD = mesh.getLOD(this.activeCamera);
  27557. if (meshLOD === undefined || meshLOD === null) {
  27558. continue;
  27559. }
  27560. mesh._preActivate();
  27561. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27562. this._activeMeshes.push(mesh);
  27563. this.activeCamera._activeMeshes.push(mesh);
  27564. mesh._activate(this._renderId);
  27565. if (meshLOD !== mesh) {
  27566. meshLOD._activate(this._renderId);
  27567. }
  27568. this._activeMesh(mesh, meshLOD);
  27569. }
  27570. }
  27571. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27572. // Particle systems
  27573. if (this.particlesEnabled) {
  27574. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27575. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27576. var particleSystem = this.particleSystems[particleIndex];
  27577. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27578. continue;
  27579. }
  27580. var emitter = particleSystem.emitter;
  27581. if (!emitter.position || emitter.isEnabled()) {
  27582. this._activeParticleSystems.push(particleSystem);
  27583. particleSystem.animate();
  27584. this._renderingManager.dispatchParticles(particleSystem);
  27585. }
  27586. }
  27587. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27588. }
  27589. };
  27590. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27591. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27592. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27593. mesh.skeleton.prepare();
  27594. }
  27595. if (!mesh.computeBonesUsingShaders) {
  27596. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27597. }
  27598. }
  27599. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27600. var boundingInfo = sourceMesh.getBoundingInfo();
  27601. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27602. }
  27603. if (mesh !== undefined && mesh !== null
  27604. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27605. // Submeshes Octrees
  27606. var len;
  27607. var subMeshes;
  27608. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27609. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27610. len = intersections.length;
  27611. subMeshes = intersections.data;
  27612. }
  27613. else {
  27614. subMeshes = mesh.subMeshes;
  27615. len = subMeshes.length;
  27616. }
  27617. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27618. subMesh = subMeshes[subIndex];
  27619. this._evaluateSubMesh(subMesh, mesh);
  27620. }
  27621. }
  27622. };
  27623. /**
  27624. * Update the transform matrix to update from the current active camera
  27625. * @param force defines a boolean used to force the update even if cache is up to date
  27626. */
  27627. Scene.prototype.updateTransformMatrix = function (force) {
  27628. if (!this.activeCamera) {
  27629. return;
  27630. }
  27631. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27632. };
  27633. /**
  27634. * 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)
  27635. * @param alternateCamera defines the camera to use
  27636. */
  27637. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27638. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27639. };
  27640. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27641. if (camera && camera._skipRendering) {
  27642. return;
  27643. }
  27644. var engine = this._engine;
  27645. this.activeCamera = camera;
  27646. if (!this.activeCamera)
  27647. throw new Error("Active camera not set");
  27648. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27649. // Viewport
  27650. engine.setViewport(this.activeCamera.viewport);
  27651. // Camera
  27652. this.resetCachedMaterial();
  27653. this._renderId++;
  27654. this.updateTransformMatrix();
  27655. if (camera._alternateCamera) {
  27656. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27657. this._alternateRendering = true;
  27658. }
  27659. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27660. // Meshes
  27661. this._evaluateActiveMeshes();
  27662. // Software skinning
  27663. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27664. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27665. mesh.applySkeleton(mesh.skeleton);
  27666. }
  27667. // Render targets
  27668. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27669. var needsRestoreFrameBuffer = false;
  27670. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27671. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27672. }
  27673. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27674. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27675. }
  27676. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27677. this._intermediateRendering = true;
  27678. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27679. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27680. var renderTarget = this._renderTargets.data[renderIndex];
  27681. if (renderTarget._shouldRender()) {
  27682. this._renderId++;
  27683. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27684. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27685. }
  27686. }
  27687. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27688. this._intermediateRendering = false;
  27689. this._renderId++;
  27690. needsRestoreFrameBuffer = true; // Restore back buffer
  27691. }
  27692. // Render EffecttLayer Texture
  27693. var stencilState = this._engine.getStencilBuffer();
  27694. var renderEffects = false;
  27695. var needStencil = false;
  27696. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27697. this._intermediateRendering = true;
  27698. for (var i = 0; i < this.effectLayers.length; i++) {
  27699. var effectLayer = this.effectLayers[i];
  27700. if (effectLayer.shouldRender() &&
  27701. (!effectLayer.camera ||
  27702. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27703. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27704. renderEffects = true;
  27705. needStencil = needStencil || effectLayer.needStencil();
  27706. var renderTarget = effectLayer._mainTexture;
  27707. if (renderTarget._shouldRender()) {
  27708. this._renderId++;
  27709. renderTarget.render(false, false);
  27710. needsRestoreFrameBuffer = true;
  27711. }
  27712. }
  27713. }
  27714. this._intermediateRendering = false;
  27715. this._renderId++;
  27716. }
  27717. if (needsRestoreFrameBuffer) {
  27718. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27719. }
  27720. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27721. // Prepare Frame
  27722. this.postProcessManager._prepareFrame();
  27723. // Backgrounds
  27724. var layerIndex;
  27725. var layer;
  27726. if (this.layers.length) {
  27727. engine.setDepthBuffer(false);
  27728. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27729. layer = this.layers[layerIndex];
  27730. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27731. layer.render();
  27732. }
  27733. }
  27734. engine.setDepthBuffer(true);
  27735. }
  27736. // Activate effect Layer stencil
  27737. if (needStencil) {
  27738. this._engine.setStencilBuffer(true);
  27739. }
  27740. // Render
  27741. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27742. this._renderingManager.render(null, null, true, true);
  27743. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27744. // Restore effect Layer stencil
  27745. if (needStencil) {
  27746. this._engine.setStencilBuffer(stencilState);
  27747. }
  27748. // Bounding boxes
  27749. if (this._boundingBoxRenderer) {
  27750. this._boundingBoxRenderer.render();
  27751. }
  27752. // Lens flares
  27753. if (this.lensFlaresEnabled) {
  27754. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27755. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27756. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27757. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27758. lensFlareSystem.render();
  27759. }
  27760. }
  27761. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27762. }
  27763. // Effect Layer
  27764. if (renderEffects) {
  27765. engine.setDepthBuffer(false);
  27766. for (var i = 0; i < this.effectLayers.length; i++) {
  27767. if (this.effectLayers[i].shouldRender()) {
  27768. this.effectLayers[i].render();
  27769. }
  27770. }
  27771. engine.setDepthBuffer(true);
  27772. }
  27773. // Foregrounds
  27774. if (this.layers.length) {
  27775. engine.setDepthBuffer(false);
  27776. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27777. layer = this.layers[layerIndex];
  27778. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27779. layer.render();
  27780. }
  27781. }
  27782. engine.setDepthBuffer(true);
  27783. }
  27784. // Finalize frame
  27785. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27786. // Reset some special arrays
  27787. this._renderTargets.reset();
  27788. this._alternateRendering = false;
  27789. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27790. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27791. };
  27792. Scene.prototype._processSubCameras = function (camera) {
  27793. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27794. this._renderForCamera(camera);
  27795. return;
  27796. }
  27797. // rig cameras
  27798. for (var index = 0; index < camera._rigCameras.length; index++) {
  27799. this._renderForCamera(camera._rigCameras[index], camera);
  27800. }
  27801. this.activeCamera = camera;
  27802. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27803. };
  27804. Scene.prototype._checkIntersections = function () {
  27805. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27806. var sourceMesh = this._meshesForIntersections.data[index];
  27807. if (!sourceMesh.actionManager) {
  27808. continue;
  27809. }
  27810. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27811. var action = sourceMesh.actionManager.actions[actionIndex];
  27812. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27813. var parameters = action.getTriggerParameter();
  27814. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27815. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27816. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27817. if (areIntersecting && currentIntersectionInProgress === -1) {
  27818. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27819. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27820. sourceMesh._intersectionsInProgress.push(otherMesh);
  27821. }
  27822. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27823. sourceMesh._intersectionsInProgress.push(otherMesh);
  27824. }
  27825. }
  27826. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27827. //They intersected, and now they don't.
  27828. //is this trigger an exit trigger? execute an event.
  27829. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27830. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27831. }
  27832. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27833. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27834. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27835. return otherMesh === parameterMesh;
  27836. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27837. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27838. }
  27839. }
  27840. }
  27841. }
  27842. }
  27843. };
  27844. /**
  27845. * Render the scene
  27846. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27847. */
  27848. Scene.prototype.render = function (updateCameras) {
  27849. if (updateCameras === void 0) { updateCameras = true; }
  27850. if (this.isDisposed) {
  27851. return;
  27852. }
  27853. this._activeParticles.fetchNewFrame();
  27854. this._totalVertices.fetchNewFrame();
  27855. this._activeIndices.fetchNewFrame();
  27856. this._activeBones.fetchNewFrame();
  27857. this._meshesForIntersections.reset();
  27858. this.resetCachedMaterial();
  27859. this.onBeforeAnimationsObservable.notifyObservers(this);
  27860. // Actions
  27861. if (this.actionManager) {
  27862. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27863. }
  27864. //Simplification Queue
  27865. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27866. this.simplificationQueue.executeNext();
  27867. }
  27868. if (this._engine.isDeterministicLockStep()) {
  27869. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27870. var defaultFPS = (60.0 / 1000.0);
  27871. var defaultFrameTime = 1000 / 60; // frame time in MS
  27872. if (this._physicsEngine) {
  27873. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27874. }
  27875. var stepsTaken = 0;
  27876. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27877. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27878. internalSteps = Math.min(internalSteps, maxSubSteps);
  27879. do {
  27880. this.onBeforeStepObservable.notifyObservers(this);
  27881. // Animations
  27882. this._animationRatio = defaultFrameTime * defaultFPS;
  27883. this._animate();
  27884. this.onAfterAnimationsObservable.notifyObservers(this);
  27885. // Physics
  27886. if (this._physicsEngine) {
  27887. this.onBeforePhysicsObservable.notifyObservers(this);
  27888. this._physicsEngine._step(defaultFrameTime / 1000);
  27889. this.onAfterPhysicsObservable.notifyObservers(this);
  27890. }
  27891. this.onAfterStepObservable.notifyObservers(this);
  27892. this._currentStepId++;
  27893. stepsTaken++;
  27894. deltaTime -= defaultFrameTime;
  27895. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27896. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27897. }
  27898. else {
  27899. // Animations
  27900. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27901. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27902. this._animate();
  27903. this.onAfterAnimationsObservable.notifyObservers(this);
  27904. // Physics
  27905. if (this._physicsEngine) {
  27906. this.onBeforePhysicsObservable.notifyObservers(this);
  27907. this._physicsEngine._step(deltaTime / 1000.0);
  27908. this.onAfterPhysicsObservable.notifyObservers(this);
  27909. }
  27910. }
  27911. // update gamepad manager
  27912. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27913. this._gamepadManager._checkGamepadsStatus();
  27914. }
  27915. // Update Cameras
  27916. if (updateCameras) {
  27917. if (this.activeCameras.length > 0) {
  27918. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27919. var camera = this.activeCameras[cameraIndex];
  27920. camera.update();
  27921. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27922. // rig cameras
  27923. for (var index = 0; index < camera._rigCameras.length; index++) {
  27924. camera._rigCameras[index].update();
  27925. }
  27926. }
  27927. }
  27928. }
  27929. else if (this.activeCamera) {
  27930. this.activeCamera.update();
  27931. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27932. // rig cameras
  27933. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27934. this.activeCamera._rigCameras[index].update();
  27935. }
  27936. }
  27937. }
  27938. }
  27939. // Before render
  27940. this.onBeforeRenderObservable.notifyObservers(this);
  27941. // Customs render targets
  27942. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27943. var engine = this.getEngine();
  27944. var currentActiveCamera = this.activeCamera;
  27945. if (this.renderTargetsEnabled) {
  27946. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27947. this._intermediateRendering = true;
  27948. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27949. var renderTarget = this.customRenderTargets[customIndex];
  27950. if (renderTarget._shouldRender()) {
  27951. this._renderId++;
  27952. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27953. if (!this.activeCamera)
  27954. throw new Error("Active camera not set");
  27955. // Viewport
  27956. engine.setViewport(this.activeCamera.viewport);
  27957. // Camera
  27958. this.updateTransformMatrix();
  27959. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27960. }
  27961. }
  27962. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27963. this._intermediateRendering = false;
  27964. this._renderId++;
  27965. }
  27966. // Restore back buffer
  27967. if (this.customRenderTargets.length > 0) {
  27968. engine.restoreDefaultFramebuffer();
  27969. }
  27970. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27971. this.activeCamera = currentActiveCamera;
  27972. // Procedural textures
  27973. if (this.proceduralTexturesEnabled) {
  27974. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27975. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27976. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27977. if (proceduralTexture._shouldRender()) {
  27978. proceduralTexture.render();
  27979. }
  27980. }
  27981. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27982. }
  27983. // Clear
  27984. if (this.autoClearDepthAndStencil || this.autoClear) {
  27985. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27986. }
  27987. // Shadows
  27988. if (this.shadowsEnabled) {
  27989. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27990. var light = this.lights[lightIndex];
  27991. var shadowGenerator = light.getShadowGenerator();
  27992. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27993. var shadowMap = (shadowGenerator.getShadowMap());
  27994. if (this.textures.indexOf(shadowMap) !== -1) {
  27995. this._renderTargets.push(shadowMap);
  27996. }
  27997. }
  27998. }
  27999. }
  28000. // Depth renderer
  28001. for (var key in this._depthRenderer) {
  28002. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  28003. }
  28004. // Geometry renderer
  28005. if (this._geometryBufferRenderer) {
  28006. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  28007. }
  28008. // RenderPipeline
  28009. if (this._postProcessRenderPipelineManager) {
  28010. this._postProcessRenderPipelineManager.update();
  28011. }
  28012. // Multi-cameras?
  28013. if (this.activeCameras.length > 0) {
  28014. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28015. if (cameraIndex > 0) {
  28016. this._engine.clear(null, false, true, true);
  28017. }
  28018. this._processSubCameras(this.activeCameras[cameraIndex]);
  28019. }
  28020. }
  28021. else {
  28022. if (!this.activeCamera) {
  28023. throw new Error("No camera defined");
  28024. }
  28025. this._processSubCameras(this.activeCamera);
  28026. }
  28027. // Intersection checks
  28028. this._checkIntersections();
  28029. // Update the audio listener attached to the camera
  28030. if (BABYLON.AudioEngine) {
  28031. this._updateAudioParameters();
  28032. }
  28033. // After render
  28034. if (this.afterRender) {
  28035. this.afterRender();
  28036. }
  28037. this.onAfterRenderObservable.notifyObservers(this);
  28038. // Cleaning
  28039. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28040. var data = this._toBeDisposed.data[index];
  28041. if (data) {
  28042. data.dispose();
  28043. }
  28044. this._toBeDisposed[index] = null;
  28045. }
  28046. this._toBeDisposed.reset();
  28047. if (this.dumpNextRenderTargets) {
  28048. this.dumpNextRenderTargets = false;
  28049. }
  28050. this._activeBones.addCount(0, true);
  28051. this._activeIndices.addCount(0, true);
  28052. this._activeParticles.addCount(0, true);
  28053. };
  28054. Scene.prototype._updateAudioParameters = function () {
  28055. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  28056. return;
  28057. }
  28058. var listeningCamera;
  28059. var audioEngine = BABYLON.Engine.audioEngine;
  28060. if (this.activeCameras.length > 0) {
  28061. listeningCamera = this.activeCameras[0];
  28062. }
  28063. else {
  28064. listeningCamera = this.activeCamera;
  28065. }
  28066. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  28067. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  28068. // for VR cameras
  28069. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  28070. listeningCamera = listeningCamera.rigCameras[0];
  28071. }
  28072. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  28073. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  28074. cameraDirection.normalize();
  28075. // To avoid some errors on GearVR
  28076. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  28077. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  28078. }
  28079. var i;
  28080. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28081. var sound = this.mainSoundTrack.soundCollection[i];
  28082. if (sound.useCustomAttenuation) {
  28083. sound.updateDistanceFromListener();
  28084. }
  28085. }
  28086. for (i = 0; i < this.soundTracks.length; i++) {
  28087. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28088. sound = this.soundTracks[i].soundCollection[j];
  28089. if (sound.useCustomAttenuation) {
  28090. sound.updateDistanceFromListener();
  28091. }
  28092. }
  28093. }
  28094. }
  28095. };
  28096. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28097. // Audio
  28098. /**
  28099. * Gets or sets if audio support is enabled
  28100. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28101. */
  28102. get: function () {
  28103. return this._audioEnabled;
  28104. },
  28105. set: function (value) {
  28106. this._audioEnabled = value;
  28107. if (BABYLON.AudioEngine) {
  28108. if (this._audioEnabled) {
  28109. this._enableAudio();
  28110. }
  28111. else {
  28112. this._disableAudio();
  28113. }
  28114. }
  28115. },
  28116. enumerable: true,
  28117. configurable: true
  28118. });
  28119. Scene.prototype._disableAudio = function () {
  28120. var i;
  28121. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28122. this.mainSoundTrack.soundCollection[i].pause();
  28123. }
  28124. for (i = 0; i < this.soundTracks.length; i++) {
  28125. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28126. this.soundTracks[i].soundCollection[j].pause();
  28127. }
  28128. }
  28129. };
  28130. Scene.prototype._enableAudio = function () {
  28131. var i;
  28132. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28133. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28134. this.mainSoundTrack.soundCollection[i].play();
  28135. }
  28136. }
  28137. for (i = 0; i < this.soundTracks.length; i++) {
  28138. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28139. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28140. this.soundTracks[i].soundCollection[j].play();
  28141. }
  28142. }
  28143. }
  28144. };
  28145. Object.defineProperty(Scene.prototype, "headphone", {
  28146. /**
  28147. * Gets or sets if audio will be output to headphones
  28148. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28149. */
  28150. get: function () {
  28151. return this._headphone;
  28152. },
  28153. set: function (value) {
  28154. this._headphone = value;
  28155. if (BABYLON.AudioEngine) {
  28156. if (this._headphone) {
  28157. this._switchAudioModeForHeadphones();
  28158. }
  28159. else {
  28160. this._switchAudioModeForNormalSpeakers();
  28161. }
  28162. }
  28163. },
  28164. enumerable: true,
  28165. configurable: true
  28166. });
  28167. Scene.prototype._switchAudioModeForHeadphones = function () {
  28168. this.mainSoundTrack.switchPanningModelToHRTF();
  28169. for (var i = 0; i < this.soundTracks.length; i++) {
  28170. this.soundTracks[i].switchPanningModelToHRTF();
  28171. }
  28172. };
  28173. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28174. this.mainSoundTrack.switchPanningModelToEqualPower();
  28175. for (var i = 0; i < this.soundTracks.length; i++) {
  28176. this.soundTracks[i].switchPanningModelToEqualPower();
  28177. }
  28178. };
  28179. /**
  28180. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28181. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28182. * @returns the created depth renderer
  28183. */
  28184. Scene.prototype.enableDepthRenderer = function (camera) {
  28185. camera = camera || this.activeCamera;
  28186. if (!camera) {
  28187. throw "No camera available to enable depth renderer";
  28188. }
  28189. if (!this._depthRenderer[camera.id]) {
  28190. var textureType = 0;
  28191. if (this._engine.getCaps().textureHalfFloatRender) {
  28192. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28193. }
  28194. else if (this._engine.getCaps().textureFloatRender) {
  28195. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28196. }
  28197. else {
  28198. throw "Depth renderer does not support int texture type";
  28199. }
  28200. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28201. }
  28202. return this._depthRenderer[camera.id];
  28203. };
  28204. /**
  28205. * Disables a depth renderer for a given camera
  28206. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28207. */
  28208. Scene.prototype.disableDepthRenderer = function (camera) {
  28209. camera = camera || this.activeCamera;
  28210. if (!camera || !this._depthRenderer[camera.id]) {
  28211. return;
  28212. }
  28213. this._depthRenderer[camera.id].dispose();
  28214. delete this._depthRenderer[camera.id];
  28215. };
  28216. /**
  28217. * Enables a GeometryBufferRender and associates it with the scene
  28218. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28219. * @returns the GeometryBufferRenderer
  28220. */
  28221. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28222. if (ratio === void 0) { ratio = 1; }
  28223. if (this._geometryBufferRenderer) {
  28224. return this._geometryBufferRenderer;
  28225. }
  28226. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28227. if (!this._geometryBufferRenderer.isSupported) {
  28228. this._geometryBufferRenderer = null;
  28229. }
  28230. return this._geometryBufferRenderer;
  28231. };
  28232. /**
  28233. * Disables the GeometryBufferRender associated with the scene
  28234. */
  28235. Scene.prototype.disableGeometryBufferRenderer = function () {
  28236. if (!this._geometryBufferRenderer) {
  28237. return;
  28238. }
  28239. this._geometryBufferRenderer.dispose();
  28240. this._geometryBufferRenderer = null;
  28241. };
  28242. /**
  28243. * Freeze all materials
  28244. * A frozen material will not be updatable but should be faster to render
  28245. */
  28246. Scene.prototype.freezeMaterials = function () {
  28247. for (var i = 0; i < this.materials.length; i++) {
  28248. this.materials[i].freeze();
  28249. }
  28250. };
  28251. /**
  28252. * Unfreeze all materials
  28253. * A frozen material will not be updatable but should be faster to render
  28254. */
  28255. Scene.prototype.unfreezeMaterials = function () {
  28256. for (var i = 0; i < this.materials.length; i++) {
  28257. this.materials[i].unfreeze();
  28258. }
  28259. };
  28260. /**
  28261. * Releases all held ressources
  28262. */
  28263. Scene.prototype.dispose = function () {
  28264. this.beforeRender = null;
  28265. this.afterRender = null;
  28266. this.skeletons = [];
  28267. this.morphTargetManagers = [];
  28268. this.importedMeshesFiles = new Array();
  28269. this.stopAllAnimations();
  28270. this.resetCachedMaterial();
  28271. for (var key in this._depthRenderer) {
  28272. this._depthRenderer[key].dispose();
  28273. }
  28274. if (this._gamepadManager) {
  28275. this._gamepadManager.dispose();
  28276. this._gamepadManager = null;
  28277. }
  28278. // Smart arrays
  28279. if (this.activeCamera) {
  28280. this.activeCamera._activeMeshes.dispose();
  28281. this.activeCamera = null;
  28282. }
  28283. this._activeMeshes.dispose();
  28284. this._renderingManager.dispose();
  28285. this._processedMaterials.dispose();
  28286. this._activeParticleSystems.dispose();
  28287. this._activeSkeletons.dispose();
  28288. this._softwareSkinnedMeshes.dispose();
  28289. this._renderTargets.dispose();
  28290. this._registeredForLateAnimationBindings.dispose();
  28291. if (this._boundingBoxRenderer) {
  28292. this._boundingBoxRenderer.dispose();
  28293. }
  28294. this._meshesForIntersections.dispose();
  28295. this._toBeDisposed.dispose();
  28296. // Abort active requests
  28297. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28298. var request = _a[_i];
  28299. request.abort();
  28300. }
  28301. // Debug layer
  28302. if (this._debugLayer) {
  28303. this._debugLayer.hide();
  28304. }
  28305. // Events
  28306. this.onDisposeObservable.notifyObservers(this);
  28307. this.onDisposeObservable.clear();
  28308. this.onBeforeRenderObservable.clear();
  28309. this.onAfterRenderObservable.clear();
  28310. this.onBeforeRenderTargetsRenderObservable.clear();
  28311. this.onAfterRenderTargetsRenderObservable.clear();
  28312. this.onAfterStepObservable.clear();
  28313. this.onBeforeStepObservable.clear();
  28314. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28315. this.onAfterActiveMeshesEvaluationObservable.clear();
  28316. this.onBeforeParticlesRenderingObservable.clear();
  28317. this.onAfterParticlesRenderingObservable.clear();
  28318. this.onBeforeSpritesRenderingObservable.clear();
  28319. this.onAfterSpritesRenderingObservable.clear();
  28320. this.onBeforeDrawPhaseObservable.clear();
  28321. this.onAfterDrawPhaseObservable.clear();
  28322. this.onBeforePhysicsObservable.clear();
  28323. this.onAfterPhysicsObservable.clear();
  28324. this.onBeforeAnimationsObservable.clear();
  28325. this.onAfterAnimationsObservable.clear();
  28326. this.onDataLoadedObservable.clear();
  28327. this.detachControl();
  28328. // Release sounds & sounds tracks
  28329. if (BABYLON.AudioEngine) {
  28330. this.disposeSounds();
  28331. }
  28332. // VR Helper
  28333. if (this.VRHelper) {
  28334. this.VRHelper.dispose();
  28335. }
  28336. // Detach cameras
  28337. var canvas = this._engine.getRenderingCanvas();
  28338. if (canvas) {
  28339. var index;
  28340. for (index = 0; index < this.cameras.length; index++) {
  28341. this.cameras[index].detachControl(canvas);
  28342. }
  28343. }
  28344. // Release animation groups
  28345. while (this.animationGroups.length) {
  28346. this.animationGroups[0].dispose();
  28347. }
  28348. // Release lights
  28349. while (this.lights.length) {
  28350. this.lights[0].dispose();
  28351. }
  28352. // Release meshes
  28353. while (this.meshes.length) {
  28354. this.meshes[0].dispose(true);
  28355. }
  28356. while (this.transformNodes.length) {
  28357. this.removeTransformNode(this.transformNodes[0]);
  28358. }
  28359. // Release cameras
  28360. while (this.cameras.length) {
  28361. this.cameras[0].dispose();
  28362. }
  28363. // Release materials
  28364. if (this.defaultMaterial) {
  28365. this.defaultMaterial.dispose();
  28366. }
  28367. while (this.multiMaterials.length) {
  28368. this.multiMaterials[0].dispose();
  28369. }
  28370. while (this.materials.length) {
  28371. this.materials[0].dispose();
  28372. }
  28373. // Release particles
  28374. while (this.particleSystems.length) {
  28375. this.particleSystems[0].dispose();
  28376. }
  28377. // Release sprites
  28378. while (this.spriteManagers.length) {
  28379. this.spriteManagers[0].dispose();
  28380. }
  28381. // Release postProcesses
  28382. while (this.postProcesses.length) {
  28383. this.postProcesses[0].dispose();
  28384. }
  28385. // Release layers
  28386. while (this.layers.length) {
  28387. this.layers[0].dispose();
  28388. }
  28389. while (this.effectLayers.length) {
  28390. this.effectLayers[0].dispose();
  28391. }
  28392. // Release textures
  28393. while (this.textures.length) {
  28394. this.textures[0].dispose();
  28395. }
  28396. // Release UBO
  28397. this._sceneUbo.dispose();
  28398. if (this._alternateSceneUbo) {
  28399. this._alternateSceneUbo.dispose();
  28400. }
  28401. // Post-processes
  28402. this.postProcessManager.dispose();
  28403. if (this._postProcessRenderPipelineManager) {
  28404. this._postProcessRenderPipelineManager.dispose();
  28405. }
  28406. // Physics
  28407. if (this._physicsEngine) {
  28408. this.disablePhysicsEngine();
  28409. }
  28410. // Remove from engine
  28411. index = this._engine.scenes.indexOf(this);
  28412. if (index > -1) {
  28413. this._engine.scenes.splice(index, 1);
  28414. }
  28415. this._engine.wipeCaches(true);
  28416. this._isDisposed = true;
  28417. };
  28418. Object.defineProperty(Scene.prototype, "isDisposed", {
  28419. /**
  28420. * Gets if the scene is already disposed
  28421. */
  28422. get: function () {
  28423. return this._isDisposed;
  28424. },
  28425. enumerable: true,
  28426. configurable: true
  28427. });
  28428. /**
  28429. * Releases sounds & soundtracks
  28430. */
  28431. Scene.prototype.disposeSounds = function () {
  28432. if (!this._mainSoundTrack) {
  28433. return;
  28434. }
  28435. this.mainSoundTrack.dispose();
  28436. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28437. this.soundTracks[scIndex].dispose();
  28438. }
  28439. };
  28440. /**
  28441. * Call this function to reduce memory footprint of the scene.
  28442. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28443. */
  28444. Scene.prototype.clearCachedVertexData = function () {
  28445. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28446. var mesh = this.meshes[meshIndex];
  28447. var geometry = mesh.geometry;
  28448. if (geometry) {
  28449. geometry._indices = [];
  28450. for (var vbName in geometry._vertexBuffers) {
  28451. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28452. continue;
  28453. }
  28454. geometry._vertexBuffers[vbName]._buffer._data = null;
  28455. }
  28456. }
  28457. }
  28458. };
  28459. /**
  28460. * This function will remove the local cached buffer data from texture.
  28461. * It will save memory but will prevent the texture from being rebuilt
  28462. */
  28463. Scene.prototype.cleanCachedTextureBuffer = function () {
  28464. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28465. var baseTexture = _a[_i];
  28466. var buffer = baseTexture._buffer;
  28467. if (buffer) {
  28468. baseTexture._buffer = null;
  28469. }
  28470. }
  28471. };
  28472. // Octrees
  28473. /**
  28474. * Get the world extend vectors with an optional filter
  28475. *
  28476. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28477. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28478. */
  28479. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28480. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28481. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28482. filterPredicate = filterPredicate || (function () { return true; });
  28483. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28484. mesh.computeWorldMatrix(true);
  28485. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28486. return;
  28487. }
  28488. var boundingInfo = mesh.getBoundingInfo();
  28489. var minBox = boundingInfo.boundingBox.minimumWorld;
  28490. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28491. BABYLON.Tools.CheckExtends(minBox, min, max);
  28492. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28493. });
  28494. return {
  28495. min: min,
  28496. max: max
  28497. };
  28498. };
  28499. /**
  28500. * Creates or updates the octree used to boost selection (picking)
  28501. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28502. * @param maxCapacity defines the maximum capacity per leaf
  28503. * @param maxDepth defines the maximum depth of the octree
  28504. * @returns an octree of AbstractMesh
  28505. */
  28506. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28507. if (maxCapacity === void 0) { maxCapacity = 64; }
  28508. if (maxDepth === void 0) { maxDepth = 2; }
  28509. if (!this._selectionOctree) {
  28510. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28511. }
  28512. var worldExtends = this.getWorldExtends();
  28513. // Update octree
  28514. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28515. return this._selectionOctree;
  28516. };
  28517. // Picking
  28518. /**
  28519. * Creates a ray that can be used to pick in the scene
  28520. * @param x defines the x coordinate of the origin (on-screen)
  28521. * @param y defines the y coordinate of the origin (on-screen)
  28522. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28523. * @param camera defines the camera to use for the picking
  28524. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28525. * @returns a Ray
  28526. */
  28527. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28528. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28529. var result = BABYLON.Ray.Zero();
  28530. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28531. return result;
  28532. };
  28533. /**
  28534. * Creates a ray that can be used to pick in the scene
  28535. * @param x defines the x coordinate of the origin (on-screen)
  28536. * @param y defines the y coordinate of the origin (on-screen)
  28537. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28538. * @param result defines the ray where to store the picking ray
  28539. * @param camera defines the camera to use for the picking
  28540. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28541. * @returns the current scene
  28542. */
  28543. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28544. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28545. var engine = this._engine;
  28546. if (!camera) {
  28547. if (!this.activeCamera)
  28548. throw new Error("Active camera not set");
  28549. camera = this.activeCamera;
  28550. }
  28551. var cameraViewport = camera.viewport;
  28552. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28553. // Moving coordinates to local viewport world
  28554. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28555. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28556. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28557. return this;
  28558. };
  28559. /**
  28560. * Creates a ray that can be used to pick in the scene
  28561. * @param x defines the x coordinate of the origin (on-screen)
  28562. * @param y defines the y coordinate of the origin (on-screen)
  28563. * @param camera defines the camera to use for the picking
  28564. * @returns a Ray
  28565. */
  28566. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28567. var result = BABYLON.Ray.Zero();
  28568. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28569. return result;
  28570. };
  28571. /**
  28572. * Creates a ray that can be used to pick in the scene
  28573. * @param x defines the x coordinate of the origin (on-screen)
  28574. * @param y defines the y coordinate of the origin (on-screen)
  28575. * @param result defines the ray where to store the picking ray
  28576. * @param camera defines the camera to use for the picking
  28577. * @returns the current scene
  28578. */
  28579. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28580. if (!BABYLON.PickingInfo) {
  28581. return this;
  28582. }
  28583. var engine = this._engine;
  28584. if (!camera) {
  28585. if (!this.activeCamera)
  28586. throw new Error("Active camera not set");
  28587. camera = this.activeCamera;
  28588. }
  28589. var cameraViewport = camera.viewport;
  28590. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28591. var identity = BABYLON.Matrix.Identity();
  28592. // Moving coordinates to local viewport world
  28593. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28594. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28595. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28596. return this;
  28597. };
  28598. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28599. if (!BABYLON.PickingInfo) {
  28600. return null;
  28601. }
  28602. var pickingInfo = null;
  28603. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28604. var mesh = this.meshes[meshIndex];
  28605. if (predicate) {
  28606. if (!predicate(mesh)) {
  28607. continue;
  28608. }
  28609. }
  28610. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28611. continue;
  28612. }
  28613. var world = mesh.getWorldMatrix();
  28614. var ray = rayFunction(world);
  28615. var result = mesh.intersects(ray, fastCheck);
  28616. if (!result || !result.hit)
  28617. continue;
  28618. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28619. continue;
  28620. pickingInfo = result;
  28621. if (fastCheck) {
  28622. break;
  28623. }
  28624. }
  28625. return pickingInfo || new BABYLON.PickingInfo();
  28626. };
  28627. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28628. if (!BABYLON.PickingInfo) {
  28629. return null;
  28630. }
  28631. var pickingInfos = new Array();
  28632. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28633. var mesh = this.meshes[meshIndex];
  28634. if (predicate) {
  28635. if (!predicate(mesh)) {
  28636. continue;
  28637. }
  28638. }
  28639. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28640. continue;
  28641. }
  28642. var world = mesh.getWorldMatrix();
  28643. var ray = rayFunction(world);
  28644. var result = mesh.intersects(ray, false);
  28645. if (!result || !result.hit)
  28646. continue;
  28647. pickingInfos.push(result);
  28648. }
  28649. return pickingInfos;
  28650. };
  28651. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28652. if (!BABYLON.PickingInfo) {
  28653. return null;
  28654. }
  28655. var pickingInfo = null;
  28656. if (!camera) {
  28657. if (!this.activeCamera) {
  28658. return null;
  28659. }
  28660. camera = this.activeCamera;
  28661. }
  28662. if (this.spriteManagers.length > 0) {
  28663. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28664. var spriteManager = this.spriteManagers[spriteIndex];
  28665. if (!spriteManager.isPickable) {
  28666. continue;
  28667. }
  28668. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28669. if (!result || !result.hit)
  28670. continue;
  28671. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28672. continue;
  28673. pickingInfo = result;
  28674. if (fastCheck) {
  28675. break;
  28676. }
  28677. }
  28678. }
  28679. return pickingInfo || new BABYLON.PickingInfo();
  28680. };
  28681. /** Launch a ray to try to pick a mesh in the scene
  28682. * @param x position on screen
  28683. * @param y position on screen
  28684. * @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
  28685. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28686. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28687. * @returns a PickingInfo
  28688. */
  28689. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28690. var _this = this;
  28691. if (!BABYLON.PickingInfo) {
  28692. return null;
  28693. }
  28694. var result = this._internalPick(function (world) {
  28695. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28696. return _this._tempPickingRay;
  28697. }, predicate, fastCheck);
  28698. if (result) {
  28699. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28700. }
  28701. return result;
  28702. };
  28703. /** Launch a ray to try to pick a sprite in the scene
  28704. * @param x position on screen
  28705. * @param y position on screen
  28706. * @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
  28707. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28708. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28709. * @returns a PickingInfo
  28710. */
  28711. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28712. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28713. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28714. };
  28715. /** Use the given ray to pick a mesh in the scene
  28716. * @param ray The ray to use to pick meshes
  28717. * @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
  28718. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28719. * @returns a PickingInfo
  28720. */
  28721. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28722. var _this = this;
  28723. var result = this._internalPick(function (world) {
  28724. if (!_this._pickWithRayInverseMatrix) {
  28725. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28726. }
  28727. world.invertToRef(_this._pickWithRayInverseMatrix);
  28728. if (!_this._cachedRayForTransform) {
  28729. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28730. }
  28731. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28732. return _this._cachedRayForTransform;
  28733. }, predicate, fastCheck);
  28734. if (result) {
  28735. result.ray = ray;
  28736. }
  28737. return result;
  28738. };
  28739. /**
  28740. * Launch a ray to try to pick a mesh in the scene
  28741. * @param x X position on screen
  28742. * @param y Y position on screen
  28743. * @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
  28744. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28745. * @returns an array of PickingInfo
  28746. */
  28747. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28748. var _this = this;
  28749. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28750. };
  28751. /**
  28752. * Launch a ray to try to pick a mesh in the scene
  28753. * @param ray Ray to use
  28754. * @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
  28755. * @returns an array of PickingInfo
  28756. */
  28757. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28758. var _this = this;
  28759. return this._internalMultiPick(function (world) {
  28760. if (!_this._pickWithRayInverseMatrix) {
  28761. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28762. }
  28763. world.invertToRef(_this._pickWithRayInverseMatrix);
  28764. if (!_this._cachedRayForTransform) {
  28765. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28766. }
  28767. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28768. return _this._cachedRayForTransform;
  28769. }, predicate);
  28770. };
  28771. /**
  28772. * Force the value of meshUnderPointer
  28773. * @param mesh defines the mesh to use
  28774. */
  28775. Scene.prototype.setPointerOverMesh = function (mesh) {
  28776. if (this._pointerOverMesh === mesh) {
  28777. return;
  28778. }
  28779. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28780. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28781. }
  28782. this._pointerOverMesh = mesh;
  28783. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28784. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28785. }
  28786. };
  28787. /**
  28788. * Gets the mesh under the pointer
  28789. * @returns a Mesh or null if no mesh is under the pointer
  28790. */
  28791. Scene.prototype.getPointerOverMesh = function () {
  28792. return this._pointerOverMesh;
  28793. };
  28794. /**
  28795. * Force the sprite under the pointer
  28796. * @param sprite defines the sprite to use
  28797. */
  28798. Scene.prototype.setPointerOverSprite = function (sprite) {
  28799. if (this._pointerOverSprite === sprite) {
  28800. return;
  28801. }
  28802. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28803. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28804. }
  28805. this._pointerOverSprite = sprite;
  28806. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28807. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28808. }
  28809. };
  28810. /**
  28811. * Gets the sprite under the pointer
  28812. * @returns a Sprite or null if no sprite is under the pointer
  28813. */
  28814. Scene.prototype.getPointerOverSprite = function () {
  28815. return this._pointerOverSprite;
  28816. };
  28817. // Physics
  28818. /**
  28819. * Gets the current physics engine
  28820. * @returns a PhysicsEngine or null if none attached
  28821. */
  28822. Scene.prototype.getPhysicsEngine = function () {
  28823. return this._physicsEngine;
  28824. };
  28825. /**
  28826. * Enables physics to the current scene
  28827. * @param gravity defines the scene's gravity for the physics engine
  28828. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28829. * @return a boolean indicating if the physics engine was initialized
  28830. */
  28831. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28832. if (gravity === void 0) { gravity = null; }
  28833. if (this._physicsEngine) {
  28834. return true;
  28835. }
  28836. try {
  28837. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28838. return true;
  28839. }
  28840. catch (e) {
  28841. BABYLON.Tools.Error(e.message);
  28842. return false;
  28843. }
  28844. };
  28845. /**
  28846. * Disables and disposes the physics engine associated with the scene
  28847. */
  28848. Scene.prototype.disablePhysicsEngine = function () {
  28849. if (!this._physicsEngine) {
  28850. return;
  28851. }
  28852. this._physicsEngine.dispose();
  28853. this._physicsEngine = null;
  28854. };
  28855. /**
  28856. * Gets a boolean indicating if there is an active physics engine
  28857. * @returns a boolean indicating if there is an active physics engine
  28858. */
  28859. Scene.prototype.isPhysicsEnabled = function () {
  28860. return this._physicsEngine !== undefined;
  28861. };
  28862. /**
  28863. * Deletes a physics compound impostor
  28864. * @param compound defines the compound to delete
  28865. */
  28866. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28867. var mesh = compound.parts[0].mesh;
  28868. if (mesh.physicsImpostor) {
  28869. mesh.physicsImpostor.dispose( /*true*/);
  28870. mesh.physicsImpostor = null;
  28871. }
  28872. };
  28873. // Misc.
  28874. /** @hidden */
  28875. Scene.prototype._rebuildGeometries = function () {
  28876. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28877. var geometry = _a[_i];
  28878. geometry._rebuild();
  28879. }
  28880. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28881. var mesh = _c[_b];
  28882. mesh._rebuild();
  28883. }
  28884. if (this.postProcessManager) {
  28885. this.postProcessManager._rebuild();
  28886. }
  28887. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28888. var layer = _e[_d];
  28889. layer._rebuild();
  28890. }
  28891. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28892. var effectLayer = _g[_f];
  28893. effectLayer._rebuild();
  28894. }
  28895. if (this._boundingBoxRenderer) {
  28896. this._boundingBoxRenderer._rebuild();
  28897. }
  28898. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28899. var system = _j[_h];
  28900. system.rebuild();
  28901. }
  28902. if (this._postProcessRenderPipelineManager) {
  28903. this._postProcessRenderPipelineManager._rebuild();
  28904. }
  28905. };
  28906. /** @hidden */
  28907. Scene.prototype._rebuildTextures = function () {
  28908. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28909. var texture = _a[_i];
  28910. texture._rebuild();
  28911. }
  28912. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28913. };
  28914. /**
  28915. * Creates a default light for the scene.
  28916. * @param replace Whether to replace the existing lights in the scene.
  28917. */
  28918. Scene.prototype.createDefaultLight = function (replace) {
  28919. if (replace === void 0) { replace = false; }
  28920. // Dispose existing light in replace mode.
  28921. if (replace) {
  28922. if (this.lights) {
  28923. for (var i = 0; i < this.lights.length; i++) {
  28924. this.lights[i].dispose();
  28925. }
  28926. }
  28927. }
  28928. // Light
  28929. if (this.lights.length === 0) {
  28930. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28931. }
  28932. };
  28933. /**
  28934. * Creates a default camera for the scene.
  28935. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28936. * @param replace Whether to replace the existing active camera in the scene.
  28937. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28938. */
  28939. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28940. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28941. if (replace === void 0) { replace = false; }
  28942. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28943. // Dispose existing camera in replace mode.
  28944. if (replace) {
  28945. if (this.activeCamera) {
  28946. this.activeCamera.dispose();
  28947. this.activeCamera = null;
  28948. }
  28949. }
  28950. // Camera
  28951. if (!this.activeCamera) {
  28952. var worldExtends = this.getWorldExtends();
  28953. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28954. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28955. var camera;
  28956. var radius = worldSize.length() * 1.5;
  28957. // empty scene scenario!
  28958. if (!isFinite(radius)) {
  28959. radius = 1;
  28960. worldCenter.copyFromFloats(0, 0, 0);
  28961. }
  28962. if (createArcRotateCamera) {
  28963. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28964. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28965. arcRotateCamera.wheelPrecision = 100 / radius;
  28966. camera = arcRotateCamera;
  28967. }
  28968. else {
  28969. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28970. freeCamera.setTarget(worldCenter);
  28971. camera = freeCamera;
  28972. }
  28973. camera.minZ = radius * 0.01;
  28974. camera.maxZ = radius * 1000;
  28975. camera.speed = radius * 0.2;
  28976. this.activeCamera = camera;
  28977. var canvas = this.getEngine().getRenderingCanvas();
  28978. if (attachCameraControls && canvas) {
  28979. camera.attachControl(canvas);
  28980. }
  28981. }
  28982. };
  28983. /**
  28984. * Creates a default camera and a default light
  28985. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28986. * @param replace defines if the camera and/or light will replace the existing ones
  28987. * @param attachCameraControls defines if attachControl will be called on the new camera
  28988. */
  28989. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28990. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28991. if (replace === void 0) { replace = false; }
  28992. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28993. this.createDefaultLight(replace);
  28994. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28995. };
  28996. /**
  28997. * Creates a new sky box
  28998. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28999. * @param environmentTexture defines the texture to use as environment texture
  29000. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  29001. * @param scale defines the overall scale of the skybox
  29002. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  29003. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  29004. * @returns a new mesh holding the sky box
  29005. */
  29006. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  29007. if (pbr === void 0) { pbr = false; }
  29008. if (scale === void 0) { scale = 1000; }
  29009. if (blur === void 0) { blur = 0; }
  29010. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  29011. if (!environmentTexture) {
  29012. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  29013. return null;
  29014. }
  29015. if (setGlobalEnvTexture) {
  29016. if (environmentTexture) {
  29017. this.environmentTexture = environmentTexture;
  29018. }
  29019. }
  29020. // Skybox
  29021. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  29022. if (pbr) {
  29023. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  29024. hdrSkyboxMaterial.backFaceCulling = false;
  29025. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  29026. if (hdrSkyboxMaterial.reflectionTexture) {
  29027. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29028. }
  29029. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  29030. hdrSkyboxMaterial.disableLighting = true;
  29031. hdrSkyboxMaterial.twoSidedLighting = true;
  29032. hdrSkybox.infiniteDistance = true;
  29033. hdrSkybox.material = hdrSkyboxMaterial;
  29034. }
  29035. else {
  29036. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  29037. skyboxMaterial.backFaceCulling = false;
  29038. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  29039. if (skyboxMaterial.reflectionTexture) {
  29040. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29041. }
  29042. skyboxMaterial.disableLighting = true;
  29043. hdrSkybox.infiniteDistance = true;
  29044. hdrSkybox.material = skyboxMaterial;
  29045. }
  29046. return hdrSkybox;
  29047. };
  29048. /**
  29049. * Creates a new environment
  29050. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29051. * @param options defines the options you can use to configure the environment
  29052. * @returns the new EnvironmentHelper
  29053. */
  29054. Scene.prototype.createDefaultEnvironment = function (options) {
  29055. if (BABYLON.EnvironmentHelper) {
  29056. return new BABYLON.EnvironmentHelper(options, this);
  29057. }
  29058. return null;
  29059. };
  29060. /**
  29061. * Creates a new VREXperienceHelper
  29062. * @see http://doc.babylonjs.com/how_to/webvr_helper
  29063. * @param webVROptions defines the options used to create the new VREXperienceHelper
  29064. * @returns a new VREXperienceHelper
  29065. */
  29066. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  29067. if (webVROptions === void 0) { webVROptions = {}; }
  29068. return new BABYLON.VRExperienceHelper(this, webVROptions);
  29069. };
  29070. // Tags
  29071. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29072. if (tagsQuery === undefined) {
  29073. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29074. return list;
  29075. }
  29076. var listByTags = [];
  29077. forEach = forEach || (function (item) { return; });
  29078. for (var i in list) {
  29079. var item = list[i];
  29080. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29081. listByTags.push(item);
  29082. forEach(item);
  29083. }
  29084. }
  29085. return listByTags;
  29086. };
  29087. /**
  29088. * Get a list of meshes by tags
  29089. * @param tagsQuery defines the tags query to use
  29090. * @param forEach defines a predicate used to filter results
  29091. * @returns an array of Mesh
  29092. */
  29093. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29094. return this._getByTags(this.meshes, tagsQuery, forEach);
  29095. };
  29096. /**
  29097. * Get a list of cameras by tags
  29098. * @param tagsQuery defines the tags query to use
  29099. * @param forEach defines a predicate used to filter results
  29100. * @returns an array of Camera
  29101. */
  29102. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29103. return this._getByTags(this.cameras, tagsQuery, forEach);
  29104. };
  29105. /**
  29106. * Get a list of lights by tags
  29107. * @param tagsQuery defines the tags query to use
  29108. * @param forEach defines a predicate used to filter results
  29109. * @returns an array of Light
  29110. */
  29111. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29112. return this._getByTags(this.lights, tagsQuery, forEach);
  29113. };
  29114. /**
  29115. * Get a list of materials by tags
  29116. * @param tagsQuery defines the tags query to use
  29117. * @param forEach defines a predicate used to filter results
  29118. * @returns an array of Material
  29119. */
  29120. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29121. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29122. };
  29123. /**
  29124. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29125. * This allowed control for front to back rendering or reversly depending of the special needs.
  29126. *
  29127. * @param renderingGroupId The rendering group id corresponding to its index
  29128. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29129. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29130. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29131. */
  29132. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29133. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29134. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29135. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29136. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29137. };
  29138. /**
  29139. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29140. *
  29141. * @param renderingGroupId The rendering group id corresponding to its index
  29142. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29143. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29144. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29145. */
  29146. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29147. if (depth === void 0) { depth = true; }
  29148. if (stencil === void 0) { stencil = true; }
  29149. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29150. };
  29151. /**
  29152. * Will flag all materials as dirty to trigger new shader compilation
  29153. * @param flag defines the flag used to specify which material part must be marked as dirty
  29154. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29155. */
  29156. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29157. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29158. var material = _a[_i];
  29159. if (predicate && !predicate(material)) {
  29160. continue;
  29161. }
  29162. material.markAsDirty(flag);
  29163. }
  29164. };
  29165. /** @hidden */
  29166. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29167. var _this = this;
  29168. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29169. this._activeRequests.push(request);
  29170. request.onCompleteObservable.add(function (request) {
  29171. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29172. });
  29173. return request;
  29174. };
  29175. /** @hidden */
  29176. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29177. var _this = this;
  29178. return new Promise(function (resolve, reject) {
  29179. _this._loadFile(url, function (data) {
  29180. resolve(data);
  29181. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29182. reject(exception);
  29183. });
  29184. });
  29185. };
  29186. // Statics
  29187. Scene._FOGMODE_NONE = 0;
  29188. Scene._FOGMODE_EXP = 1;
  29189. Scene._FOGMODE_EXP2 = 2;
  29190. Scene._FOGMODE_LINEAR = 3;
  29191. Scene._uniqueIdCounter = 0;
  29192. /**
  29193. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29194. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29195. */
  29196. Scene.MinDeltaTime = 1.0;
  29197. /**
  29198. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29199. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29200. */
  29201. Scene.MaxDeltaTime = 1000.0;
  29202. /** The distance in pixel that you have to move to prevent some events */
  29203. Scene.DragMovementThreshold = 10; // in pixels
  29204. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29205. Scene.LongPressDelay = 500; // in milliseconds
  29206. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29207. Scene.DoubleClickDelay = 300; // in milliseconds
  29208. /** If you need to check double click without raising a single click at first click, enable this flag */
  29209. Scene.ExclusiveDoubleClickMode = false;
  29210. return Scene;
  29211. }());
  29212. BABYLON.Scene = Scene;
  29213. })(BABYLON || (BABYLON = {}));
  29214. //# sourceMappingURL=babylon.scene.js.map
  29215. var BABYLON;
  29216. (function (BABYLON) {
  29217. /**
  29218. * Set of assets to keep when moving a scene into an asset container.
  29219. */
  29220. var KeepAssets = /** @class */ (function () {
  29221. function KeepAssets() {
  29222. /**
  29223. * Cameras to keep.
  29224. */
  29225. this.cameras = new Array();
  29226. /**
  29227. * Lights to keep.
  29228. */
  29229. this.lights = new Array();
  29230. /**
  29231. * Meshes to keep.
  29232. */
  29233. this.meshes = new Array();
  29234. /**
  29235. * Skeletons to keep.
  29236. */
  29237. this.skeletons = new Array();
  29238. /**
  29239. * ParticleSystems to keep.
  29240. */
  29241. this.particleSystems = new Array();
  29242. /**
  29243. * Animations to keep.
  29244. */
  29245. this.animations = new Array();
  29246. /**
  29247. * AnimationGroups to keep.
  29248. */
  29249. this.animationGroups = new Array();
  29250. /**
  29251. * MultiMaterials to keep.
  29252. */
  29253. this.multiMaterials = new Array();
  29254. /**
  29255. * Materials to keep.
  29256. */
  29257. this.materials = new Array();
  29258. /**
  29259. * MorphTargetManagers to keep.
  29260. */
  29261. this.morphTargetManagers = new Array();
  29262. /**
  29263. * Geometries to keep.
  29264. */
  29265. this.geometries = new Array();
  29266. /**
  29267. * TransformNodes to keep.
  29268. */
  29269. this.transformNodes = new Array();
  29270. /**
  29271. * LensFlareSystems to keep.
  29272. */
  29273. this.lensFlareSystems = new Array();
  29274. /**
  29275. * ShadowGenerators to keep.
  29276. */
  29277. this.shadowGenerators = new Array();
  29278. /**
  29279. * ActionManagers to keep.
  29280. */
  29281. this.actionManagers = new Array();
  29282. /**
  29283. * Sounds to keep.
  29284. */
  29285. this.sounds = new Array();
  29286. /**
  29287. * Textures to keep.
  29288. */
  29289. this.textures = new Array();
  29290. /**
  29291. * Effect layers to keep.
  29292. */
  29293. this.effectLayers = new Array();
  29294. }
  29295. return KeepAssets;
  29296. }());
  29297. BABYLON.KeepAssets = KeepAssets;
  29298. /**
  29299. * Container with a set of assets that can be added or removed from a scene.
  29300. */
  29301. var AssetContainer = /** @class */ (function () {
  29302. /**
  29303. * Instantiates an AssetContainer.
  29304. * @param scene The scene the AssetContainer belongs to.
  29305. */
  29306. function AssetContainer(scene) {
  29307. // Objects
  29308. /**
  29309. * Cameras populated in the container.
  29310. */
  29311. this.cameras = new Array();
  29312. /**
  29313. * Lights populated in the container.
  29314. */
  29315. this.lights = new Array();
  29316. /**
  29317. * Meshes populated in the container.
  29318. */
  29319. this.meshes = new Array();
  29320. /**
  29321. * Skeletons populated in the container.
  29322. */
  29323. this.skeletons = new Array();
  29324. /**
  29325. * ParticleSystems populated in the container.
  29326. */
  29327. this.particleSystems = new Array();
  29328. /**
  29329. * Animations populated in the container.
  29330. */
  29331. this.animations = new Array();
  29332. /**
  29333. * AnimationGroups populated in the container.
  29334. */
  29335. this.animationGroups = new Array();
  29336. /**
  29337. * MultiMaterials populated in the container.
  29338. */
  29339. this.multiMaterials = new Array();
  29340. /**
  29341. * Materials populated in the container.
  29342. */
  29343. this.materials = new Array();
  29344. /**
  29345. * MorphTargetManagers populated in the container.
  29346. */
  29347. this.morphTargetManagers = new Array();
  29348. /**
  29349. * Geometries populated in the container.
  29350. */
  29351. this.geometries = new Array();
  29352. /**
  29353. * TransformNodes populated in the container.
  29354. */
  29355. this.transformNodes = new Array();
  29356. /**
  29357. * LensFlareSystems populated in the container.
  29358. */
  29359. this.lensFlareSystems = new Array();
  29360. /**
  29361. * ShadowGenerators populated in the container.
  29362. */
  29363. this.shadowGenerators = new Array();
  29364. /**
  29365. * ActionManagers populated in the container.
  29366. */
  29367. this.actionManagers = new Array();
  29368. /**
  29369. * Sounds populated in the container.
  29370. */
  29371. this.sounds = new Array();
  29372. /**
  29373. * Textures populated in the container.
  29374. */
  29375. this.textures = new Array();
  29376. /**
  29377. * Effect layers populated in the container.
  29378. */
  29379. this.effectLayers = new Array();
  29380. this.scene = scene;
  29381. }
  29382. /**
  29383. * Adds all the assets from the container to the scene.
  29384. */
  29385. AssetContainer.prototype.addAllToScene = function () {
  29386. var _this = this;
  29387. this.cameras.forEach(function (o) {
  29388. _this.scene.addCamera(o);
  29389. });
  29390. this.lights.forEach(function (o) {
  29391. _this.scene.addLight(o);
  29392. });
  29393. this.meshes.forEach(function (o) {
  29394. _this.scene.addMesh(o);
  29395. });
  29396. this.skeletons.forEach(function (o) {
  29397. _this.scene.addSkeleton(o);
  29398. });
  29399. this.particleSystems.forEach(function (o) {
  29400. _this.scene.addParticleSystem(o);
  29401. });
  29402. this.animations.forEach(function (o) {
  29403. _this.scene.addAnimation(o);
  29404. });
  29405. this.animationGroups.forEach(function (o) {
  29406. _this.scene.addAnimationGroup(o);
  29407. });
  29408. this.multiMaterials.forEach(function (o) {
  29409. _this.scene.addMultiMaterial(o);
  29410. });
  29411. this.materials.forEach(function (o) {
  29412. _this.scene.addMaterial(o);
  29413. });
  29414. this.morphTargetManagers.forEach(function (o) {
  29415. _this.scene.addMorphTargetManager(o);
  29416. });
  29417. this.geometries.forEach(function (o) {
  29418. _this.scene.addGeometry(o);
  29419. });
  29420. this.transformNodes.forEach(function (o) {
  29421. _this.scene.addTransformNode(o);
  29422. });
  29423. this.lensFlareSystems.forEach(function (o) {
  29424. _this.scene.addLensFlareSystem(o);
  29425. });
  29426. this.actionManagers.forEach(function (o) {
  29427. _this.scene.addActionManager(o);
  29428. });
  29429. this.sounds.forEach(function (o) {
  29430. o.play();
  29431. o.autoplay = true;
  29432. _this.scene.mainSoundTrack.AddSound(o);
  29433. });
  29434. this.textures.forEach(function (o) {
  29435. _this.scene.addTexture(o);
  29436. });
  29437. this.effectLayers.forEach(function (o) {
  29438. _this.scene.addEffectLayer(o);
  29439. });
  29440. };
  29441. /**
  29442. * Removes all the assets in the container from the scene
  29443. */
  29444. AssetContainer.prototype.removeAllFromScene = function () {
  29445. var _this = this;
  29446. this.cameras.forEach(function (o) {
  29447. _this.scene.removeCamera(o);
  29448. });
  29449. this.lights.forEach(function (o) {
  29450. _this.scene.removeLight(o);
  29451. });
  29452. this.meshes.forEach(function (o) {
  29453. _this.scene.removeMesh(o);
  29454. });
  29455. this.skeletons.forEach(function (o) {
  29456. _this.scene.removeSkeleton(o);
  29457. });
  29458. this.particleSystems.forEach(function (o) {
  29459. _this.scene.removeParticleSystem(o);
  29460. });
  29461. this.animations.forEach(function (o) {
  29462. _this.scene.removeAnimation(o);
  29463. });
  29464. this.animationGroups.forEach(function (o) {
  29465. _this.scene.removeAnimationGroup(o);
  29466. });
  29467. this.multiMaterials.forEach(function (o) {
  29468. _this.scene.removeMultiMaterial(o);
  29469. });
  29470. this.materials.forEach(function (o) {
  29471. _this.scene.removeMaterial(o);
  29472. });
  29473. this.morphTargetManagers.forEach(function (o) {
  29474. _this.scene.removeMorphTargetManager(o);
  29475. });
  29476. this.geometries.forEach(function (o) {
  29477. _this.scene.removeGeometry(o);
  29478. });
  29479. this.transformNodes.forEach(function (o) {
  29480. _this.scene.removeTransformNode(o);
  29481. });
  29482. this.lensFlareSystems.forEach(function (o) {
  29483. _this.scene.removeLensFlareSystem(o);
  29484. });
  29485. this.actionManagers.forEach(function (o) {
  29486. _this.scene.removeActionManager(o);
  29487. });
  29488. this.sounds.forEach(function (o) {
  29489. o.stop();
  29490. o.autoplay = false;
  29491. _this.scene.mainSoundTrack.RemoveSound(o);
  29492. });
  29493. this.textures.forEach(function (o) {
  29494. _this.scene.removeTexture(o);
  29495. });
  29496. this.effectLayers.forEach(function (o) {
  29497. _this.scene.removeEffectLayer(o);
  29498. });
  29499. };
  29500. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29501. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29502. var asset = sourceAssets_1[_i];
  29503. var move = true;
  29504. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29505. var keepAsset = keepAssets_1[_a];
  29506. if (asset === keepAsset) {
  29507. move = false;
  29508. break;
  29509. }
  29510. }
  29511. if (move) {
  29512. targetAssets.push(asset);
  29513. }
  29514. }
  29515. };
  29516. /**
  29517. * Removes all the assets contained in the scene and adds them to the container.
  29518. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29519. */
  29520. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29521. if (keepAssets === undefined) {
  29522. keepAssets = new KeepAssets();
  29523. }
  29524. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29525. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29526. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29527. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29528. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29529. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29530. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29531. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29532. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29533. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29534. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29535. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29536. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29537. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29538. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29539. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29540. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29541. this.removeAllFromScene();
  29542. };
  29543. /**
  29544. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  29545. * @returns the root mesh
  29546. */
  29547. AssetContainer.prototype.createRootMesh = function () {
  29548. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29549. this.meshes.forEach(function (m) {
  29550. if (!m.parent) {
  29551. rootMesh.addChild(m);
  29552. }
  29553. });
  29554. this.meshes.unshift(rootMesh);
  29555. return rootMesh;
  29556. };
  29557. return AssetContainer;
  29558. }());
  29559. BABYLON.AssetContainer = AssetContainer;
  29560. })(BABYLON || (BABYLON = {}));
  29561. //# sourceMappingURL=babylon.assetContainer.js.map
  29562. var BABYLON;
  29563. (function (BABYLON) {
  29564. var Buffer = /** @class */ (function () {
  29565. /**
  29566. * Constructor
  29567. * @param engine the engine
  29568. * @param data the data to use for this buffer
  29569. * @param updatable whether the data is updatable
  29570. * @param stride the stride (optional)
  29571. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29572. * @param instanced whether the buffer is instanced (optional)
  29573. * @param useBytes set to true if the stride in in bytes (optional)
  29574. */
  29575. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29576. if (stride === void 0) { stride = 0; }
  29577. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29578. if (instanced === void 0) { instanced = false; }
  29579. if (useBytes === void 0) { useBytes = false; }
  29580. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29581. this._engine = engine.getScene().getEngine();
  29582. }
  29583. else {
  29584. this._engine = engine;
  29585. }
  29586. this._updatable = updatable;
  29587. this._instanced = instanced;
  29588. this._data = data;
  29589. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29590. if (!postponeInternalCreation) { // by default
  29591. this.create();
  29592. }
  29593. }
  29594. /**
  29595. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29596. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29597. * @param offset defines offset in the buffer (0 by default)
  29598. * @param size defines the size in floats of attributes (position is 3 for instance)
  29599. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29600. * @param instanced defines if the vertex buffer contains indexed data
  29601. * @param useBytes defines if the offset and stride are in bytes
  29602. * @returns the new vertex buffer
  29603. */
  29604. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29605. if (useBytes === void 0) { useBytes = false; }
  29606. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29607. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29608. // a lot of these parameters are ignored as they are overriden by the buffer
  29609. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29610. };
  29611. // Properties
  29612. Buffer.prototype.isUpdatable = function () {
  29613. return this._updatable;
  29614. };
  29615. Buffer.prototype.getData = function () {
  29616. return this._data;
  29617. };
  29618. Buffer.prototype.getBuffer = function () {
  29619. return this._buffer;
  29620. };
  29621. /**
  29622. * Gets the stride in float32 units (i.e. byte stride / 4).
  29623. * May not be an integer if the byte stride is not divisible by 4.
  29624. * DEPRECATED. Use byteStride instead.
  29625. * @returns the stride in float32 units
  29626. */
  29627. Buffer.prototype.getStrideSize = function () {
  29628. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29629. };
  29630. // Methods
  29631. Buffer.prototype.create = function (data) {
  29632. if (data === void 0) { data = null; }
  29633. if (!data && this._buffer) {
  29634. return; // nothing to do
  29635. }
  29636. data = data || this._data;
  29637. if (!data) {
  29638. return;
  29639. }
  29640. if (!this._buffer) { // create buffer
  29641. if (this._updatable) {
  29642. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29643. this._data = data;
  29644. }
  29645. else {
  29646. this._buffer = this._engine.createVertexBuffer(data);
  29647. }
  29648. }
  29649. else if (this._updatable) { // update buffer
  29650. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29651. this._data = data;
  29652. }
  29653. };
  29654. Buffer.prototype._rebuild = function () {
  29655. this._buffer = null;
  29656. this.create(this._data);
  29657. };
  29658. Buffer.prototype.update = function (data) {
  29659. this.create(data);
  29660. };
  29661. /**
  29662. * Updates the data directly.
  29663. * @param data the new data
  29664. * @param offset the new offset
  29665. * @param vertexCount the vertex count (optional)
  29666. * @param useBytes set to true if the offset is in bytes
  29667. */
  29668. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29669. if (useBytes === void 0) { useBytes = false; }
  29670. if (!this._buffer) {
  29671. return;
  29672. }
  29673. if (this._updatable) { // update buffer
  29674. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29675. this._data = null;
  29676. }
  29677. };
  29678. Buffer.prototype.dispose = function () {
  29679. if (!this._buffer) {
  29680. return;
  29681. }
  29682. if (this._engine._releaseBuffer(this._buffer)) {
  29683. this._buffer = null;
  29684. }
  29685. };
  29686. return Buffer;
  29687. }());
  29688. BABYLON.Buffer = Buffer;
  29689. })(BABYLON || (BABYLON = {}));
  29690. //# sourceMappingURL=babylon.buffer.js.map
  29691. var BABYLON;
  29692. (function (BABYLON) {
  29693. var VertexBuffer = /** @class */ (function () {
  29694. /**
  29695. * Constructor
  29696. * @param engine the engine
  29697. * @param data the data to use for this vertex buffer
  29698. * @param kind the vertex buffer kind
  29699. * @param updatable whether the data is updatable
  29700. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29701. * @param stride the stride (optional)
  29702. * @param instanced whether the buffer is instanced (optional)
  29703. * @param offset the offset of the data (optional)
  29704. * @param size the number of components (optional)
  29705. * @param type the type of the component (optional)
  29706. * @param normalized whether the data contains normalized data (optional)
  29707. * @param useBytes set to true if stride and offset are in bytes (optional)
  29708. */
  29709. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29710. if (normalized === void 0) { normalized = false; }
  29711. if (useBytes === void 0) { useBytes = false; }
  29712. if (data instanceof BABYLON.Buffer) {
  29713. this._buffer = data;
  29714. this._ownsBuffer = false;
  29715. }
  29716. else {
  29717. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29718. this._ownsBuffer = true;
  29719. }
  29720. this._kind = kind;
  29721. if (type == undefined) {
  29722. var data_1 = this.getData();
  29723. this.type = VertexBuffer.FLOAT;
  29724. if (data_1 instanceof Int8Array)
  29725. this.type = VertexBuffer.BYTE;
  29726. else if (data_1 instanceof Uint8Array)
  29727. this.type = VertexBuffer.UNSIGNED_BYTE;
  29728. else if (data_1 instanceof Int16Array)
  29729. this.type = VertexBuffer.SHORT;
  29730. else if (data_1 instanceof Uint16Array)
  29731. this.type = VertexBuffer.UNSIGNED_SHORT;
  29732. else if (data_1 instanceof Int32Array)
  29733. this.type = VertexBuffer.INT;
  29734. else if (data_1 instanceof Uint32Array)
  29735. this.type = VertexBuffer.UNSIGNED_INT;
  29736. }
  29737. else {
  29738. this.type = type;
  29739. }
  29740. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29741. if (useBytes) {
  29742. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29743. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29744. this.byteOffset = offset || 0;
  29745. }
  29746. else {
  29747. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29748. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29749. this.byteOffset = (offset || 0) * typeByteLength;
  29750. }
  29751. this.normalized = normalized;
  29752. this._instanced = instanced !== undefined ? instanced : false;
  29753. this._instanceDivisor = instanced ? 1 : 0;
  29754. }
  29755. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29756. /**
  29757. * Gets or sets the instance divisor when in instanced mode
  29758. */
  29759. get: function () {
  29760. return this._instanceDivisor;
  29761. },
  29762. set: function (value) {
  29763. this._instanceDivisor = value;
  29764. if (value == 0) {
  29765. this._instanced = false;
  29766. }
  29767. else {
  29768. this._instanced = true;
  29769. }
  29770. },
  29771. enumerable: true,
  29772. configurable: true
  29773. });
  29774. VertexBuffer.prototype._rebuild = function () {
  29775. if (!this._buffer) {
  29776. return;
  29777. }
  29778. this._buffer._rebuild();
  29779. };
  29780. /**
  29781. * Returns the kind of the VertexBuffer (string).
  29782. */
  29783. VertexBuffer.prototype.getKind = function () {
  29784. return this._kind;
  29785. };
  29786. // Properties
  29787. /**
  29788. * Boolean : is the VertexBuffer updatable ?
  29789. */
  29790. VertexBuffer.prototype.isUpdatable = function () {
  29791. return this._buffer.isUpdatable();
  29792. };
  29793. /**
  29794. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29795. */
  29796. VertexBuffer.prototype.getData = function () {
  29797. return this._buffer.getData();
  29798. };
  29799. /**
  29800. * Returns the WebGLBuffer associated to the VertexBuffer.
  29801. */
  29802. VertexBuffer.prototype.getBuffer = function () {
  29803. return this._buffer.getBuffer();
  29804. };
  29805. /**
  29806. * Returns the stride as a multiple of the type byte length.
  29807. * DEPRECATED. Use byteStride instead.
  29808. */
  29809. VertexBuffer.prototype.getStrideSize = function () {
  29810. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29811. };
  29812. /**
  29813. * Returns the offset as a multiple of the type byte length.
  29814. * DEPRECATED. Use byteOffset instead.
  29815. */
  29816. VertexBuffer.prototype.getOffset = function () {
  29817. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29818. };
  29819. /**
  29820. * Returns the number of components per vertex attribute (integer).
  29821. */
  29822. VertexBuffer.prototype.getSize = function () {
  29823. return this._size;
  29824. };
  29825. /**
  29826. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29827. */
  29828. VertexBuffer.prototype.getIsInstanced = function () {
  29829. return this._instanced;
  29830. };
  29831. /**
  29832. * Returns the instancing divisor, zero for non-instanced (integer).
  29833. */
  29834. VertexBuffer.prototype.getInstanceDivisor = function () {
  29835. return this._instanceDivisor;
  29836. };
  29837. // Methods
  29838. /**
  29839. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29840. * Returns the created WebGLBuffer.
  29841. */
  29842. VertexBuffer.prototype.create = function (data) {
  29843. return this._buffer.create(data);
  29844. };
  29845. /**
  29846. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29847. * This function will create a new buffer if the current one is not updatable
  29848. * Returns the updated WebGLBuffer.
  29849. */
  29850. VertexBuffer.prototype.update = function (data) {
  29851. return this._buffer.update(data);
  29852. };
  29853. /**
  29854. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29855. * Returns the directly updated WebGLBuffer.
  29856. * @param data the new data
  29857. * @param offset the new offset
  29858. * @param useBytes set to true if the offset is in bytes
  29859. */
  29860. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29861. if (useBytes === void 0) { useBytes = false; }
  29862. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29863. };
  29864. /**
  29865. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29866. */
  29867. VertexBuffer.prototype.dispose = function () {
  29868. if (this._ownsBuffer) {
  29869. this._buffer.dispose();
  29870. }
  29871. };
  29872. /**
  29873. * Enumerates each value of this vertex buffer as numbers.
  29874. * @param count the number of values to enumerate
  29875. * @param callback the callback function called for each value
  29876. */
  29877. VertexBuffer.prototype.forEach = function (count, callback) {
  29878. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29879. };
  29880. Object.defineProperty(VertexBuffer, "PositionKind", {
  29881. get: function () {
  29882. return VertexBuffer._PositionKind;
  29883. },
  29884. enumerable: true,
  29885. configurable: true
  29886. });
  29887. Object.defineProperty(VertexBuffer, "NormalKind", {
  29888. get: function () {
  29889. return VertexBuffer._NormalKind;
  29890. },
  29891. enumerable: true,
  29892. configurable: true
  29893. });
  29894. Object.defineProperty(VertexBuffer, "TangentKind", {
  29895. get: function () {
  29896. return VertexBuffer._TangentKind;
  29897. },
  29898. enumerable: true,
  29899. configurable: true
  29900. });
  29901. Object.defineProperty(VertexBuffer, "UVKind", {
  29902. get: function () {
  29903. return VertexBuffer._UVKind;
  29904. },
  29905. enumerable: true,
  29906. configurable: true
  29907. });
  29908. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29909. get: function () {
  29910. return VertexBuffer._UV2Kind;
  29911. },
  29912. enumerable: true,
  29913. configurable: true
  29914. });
  29915. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29916. get: function () {
  29917. return VertexBuffer._UV3Kind;
  29918. },
  29919. enumerable: true,
  29920. configurable: true
  29921. });
  29922. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29923. get: function () {
  29924. return VertexBuffer._UV4Kind;
  29925. },
  29926. enumerable: true,
  29927. configurable: true
  29928. });
  29929. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29930. get: function () {
  29931. return VertexBuffer._UV5Kind;
  29932. },
  29933. enumerable: true,
  29934. configurable: true
  29935. });
  29936. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29937. get: function () {
  29938. return VertexBuffer._UV6Kind;
  29939. },
  29940. enumerable: true,
  29941. configurable: true
  29942. });
  29943. Object.defineProperty(VertexBuffer, "ColorKind", {
  29944. get: function () {
  29945. return VertexBuffer._ColorKind;
  29946. },
  29947. enumerable: true,
  29948. configurable: true
  29949. });
  29950. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29951. get: function () {
  29952. return VertexBuffer._MatricesIndicesKind;
  29953. },
  29954. enumerable: true,
  29955. configurable: true
  29956. });
  29957. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29958. get: function () {
  29959. return VertexBuffer._MatricesWeightsKind;
  29960. },
  29961. enumerable: true,
  29962. configurable: true
  29963. });
  29964. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29965. get: function () {
  29966. return VertexBuffer._MatricesIndicesExtraKind;
  29967. },
  29968. enumerable: true,
  29969. configurable: true
  29970. });
  29971. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29972. get: function () {
  29973. return VertexBuffer._MatricesWeightsExtraKind;
  29974. },
  29975. enumerable: true,
  29976. configurable: true
  29977. });
  29978. /**
  29979. * Deduces the stride given a kind.
  29980. * @param kind The kind string to deduce
  29981. * @returns The deduced stride
  29982. */
  29983. VertexBuffer.DeduceStride = function (kind) {
  29984. switch (kind) {
  29985. case VertexBuffer.UVKind:
  29986. case VertexBuffer.UV2Kind:
  29987. case VertexBuffer.UV3Kind:
  29988. case VertexBuffer.UV4Kind:
  29989. case VertexBuffer.UV5Kind:
  29990. case VertexBuffer.UV6Kind:
  29991. return 2;
  29992. case VertexBuffer.NormalKind:
  29993. case VertexBuffer.PositionKind:
  29994. return 3;
  29995. case VertexBuffer.ColorKind:
  29996. case VertexBuffer.MatricesIndicesKind:
  29997. case VertexBuffer.MatricesIndicesExtraKind:
  29998. case VertexBuffer.MatricesWeightsKind:
  29999. case VertexBuffer.MatricesWeightsExtraKind:
  30000. case VertexBuffer.TangentKind:
  30001. return 4;
  30002. default:
  30003. throw new Error("Invalid kind '" + kind + "'");
  30004. }
  30005. };
  30006. /**
  30007. * Gets the byte length of the given type.
  30008. * @param type the type
  30009. * @returns the number of bytes
  30010. */
  30011. VertexBuffer.GetTypeByteLength = function (type) {
  30012. switch (type) {
  30013. case VertexBuffer.BYTE:
  30014. case VertexBuffer.UNSIGNED_BYTE:
  30015. return 1;
  30016. case VertexBuffer.SHORT:
  30017. case VertexBuffer.UNSIGNED_SHORT:
  30018. return 2;
  30019. case VertexBuffer.INT:
  30020. case VertexBuffer.FLOAT:
  30021. return 4;
  30022. default:
  30023. throw new Error("Invalid type '" + type + "'");
  30024. }
  30025. };
  30026. /**
  30027. * Enumerates each value of the given parameters as numbers.
  30028. * @param data the data to enumerate
  30029. * @param byteOffset the byte offset of the data
  30030. * @param byteStride the byte stride of the data
  30031. * @param componentCount the number of components per element
  30032. * @param componentType the type of the component
  30033. * @param count the total number of components
  30034. * @param normalized whether the data is normalized
  30035. * @param callback the callback function called for each value
  30036. */
  30037. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30038. if (data instanceof Array) {
  30039. var offset = byteOffset / 4;
  30040. var stride = byteStride / 4;
  30041. for (var index = 0; index < count; index += componentCount) {
  30042. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30043. callback(data[offset + componentIndex], index + componentIndex);
  30044. }
  30045. offset += stride;
  30046. }
  30047. }
  30048. else {
  30049. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30050. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30051. for (var index = 0; index < count; index += componentCount) {
  30052. var componentByteOffset = byteOffset;
  30053. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30054. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30055. callback(value, index + componentIndex);
  30056. componentByteOffset += componentByteLength;
  30057. }
  30058. byteOffset += byteStride;
  30059. }
  30060. }
  30061. };
  30062. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30063. switch (type) {
  30064. case VertexBuffer.BYTE: {
  30065. var value = dataView.getInt8(byteOffset);
  30066. if (normalized) {
  30067. value = Math.max(value / 127, -1);
  30068. }
  30069. return value;
  30070. }
  30071. case VertexBuffer.UNSIGNED_BYTE: {
  30072. var value = dataView.getUint8(byteOffset);
  30073. if (normalized) {
  30074. value = value / 255;
  30075. }
  30076. return value;
  30077. }
  30078. case VertexBuffer.SHORT: {
  30079. var value = dataView.getInt16(byteOffset, true);
  30080. if (normalized) {
  30081. value = Math.max(value / 16383, -1);
  30082. }
  30083. return value;
  30084. }
  30085. case VertexBuffer.UNSIGNED_SHORT: {
  30086. var value = dataView.getUint16(byteOffset, true);
  30087. if (normalized) {
  30088. value = value / 65535;
  30089. }
  30090. return value;
  30091. }
  30092. case VertexBuffer.FLOAT: {
  30093. return dataView.getFloat32(byteOffset, true);
  30094. }
  30095. default: {
  30096. throw new Error("Invalid component type " + type);
  30097. }
  30098. }
  30099. };
  30100. /**
  30101. * The byte type.
  30102. */
  30103. VertexBuffer.BYTE = 5120;
  30104. /**
  30105. * The unsigned byte type.
  30106. */
  30107. VertexBuffer.UNSIGNED_BYTE = 5121;
  30108. /**
  30109. * The short type.
  30110. */
  30111. VertexBuffer.SHORT = 5122;
  30112. /**
  30113. * The unsigned short type.
  30114. */
  30115. VertexBuffer.UNSIGNED_SHORT = 5123;
  30116. /**
  30117. * The integer type.
  30118. */
  30119. VertexBuffer.INT = 5124;
  30120. /**
  30121. * The unsigned integer type.
  30122. */
  30123. VertexBuffer.UNSIGNED_INT = 5125;
  30124. /**
  30125. * The float type.
  30126. */
  30127. VertexBuffer.FLOAT = 5126;
  30128. // Enums
  30129. VertexBuffer._PositionKind = "position";
  30130. VertexBuffer._NormalKind = "normal";
  30131. VertexBuffer._TangentKind = "tangent";
  30132. VertexBuffer._UVKind = "uv";
  30133. VertexBuffer._UV2Kind = "uv2";
  30134. VertexBuffer._UV3Kind = "uv3";
  30135. VertexBuffer._UV4Kind = "uv4";
  30136. VertexBuffer._UV5Kind = "uv5";
  30137. VertexBuffer._UV6Kind = "uv6";
  30138. VertexBuffer._ColorKind = "color";
  30139. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30140. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30141. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30142. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30143. return VertexBuffer;
  30144. }());
  30145. BABYLON.VertexBuffer = VertexBuffer;
  30146. })(BABYLON || (BABYLON = {}));
  30147. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30148. var BABYLON;
  30149. (function (BABYLON) {
  30150. /**
  30151. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30152. */
  30153. var DummyInternalTextureTracker = /** @class */ (function () {
  30154. function DummyInternalTextureTracker() {
  30155. /**
  30156. * Gets or set the previous tracker in the list
  30157. */
  30158. this.previous = null;
  30159. /**
  30160. * Gets or set the next tracker in the list
  30161. */
  30162. this.next = null;
  30163. }
  30164. return DummyInternalTextureTracker;
  30165. }());
  30166. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30167. })(BABYLON || (BABYLON = {}));
  30168. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30169. var BABYLON;
  30170. (function (BABYLON) {
  30171. /**
  30172. * Class used to store data associated with WebGL texture data for the engine
  30173. * This class should not be used directly
  30174. */
  30175. var InternalTexture = /** @class */ (function () {
  30176. /**
  30177. * Creates a new InternalTexture
  30178. * @param engine defines the engine to use
  30179. * @param dataSource defines the type of data that will be used
  30180. */
  30181. function InternalTexture(engine, dataSource) {
  30182. /**
  30183. * Observable called when the texture is loaded
  30184. */
  30185. this.onLoadedObservable = new BABYLON.Observable();
  30186. /**
  30187. * Gets or set the previous tracker in the list
  30188. */
  30189. this.previous = null;
  30190. /**
  30191. * Gets or set the next tracker in the list
  30192. */
  30193. this.next = null;
  30194. // Private
  30195. /** @hidden */
  30196. this._initialSlot = -1;
  30197. /** @hidden */
  30198. this._designatedSlot = -1;
  30199. /** @hidden */
  30200. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30201. /** @hidden */
  30202. this._comparisonFunction = 0;
  30203. /** @hidden */
  30204. this._isRGBD = false;
  30205. /** @hidden */
  30206. this._references = 1;
  30207. this._engine = engine;
  30208. this._dataSource = dataSource;
  30209. this._webGLTexture = engine._createTexture();
  30210. }
  30211. /**
  30212. * Gets the Engine the texture belongs to.
  30213. * @returns The babylon engine
  30214. */
  30215. InternalTexture.prototype.getEngine = function () {
  30216. return this._engine;
  30217. };
  30218. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30219. /**
  30220. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30221. */
  30222. get: function () {
  30223. return this._dataSource;
  30224. },
  30225. enumerable: true,
  30226. configurable: true
  30227. });
  30228. /**
  30229. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30230. */
  30231. InternalTexture.prototype.incrementReferences = function () {
  30232. this._references++;
  30233. };
  30234. /**
  30235. * Change the size of the texture (not the size of the content)
  30236. * @param width defines the new width
  30237. * @param height defines the new height
  30238. * @param depth defines the new depth (1 by default)
  30239. */
  30240. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30241. if (depth === void 0) { depth = 1; }
  30242. this.width = width;
  30243. this.height = height;
  30244. this.depth = depth;
  30245. this.baseWidth = width;
  30246. this.baseHeight = height;
  30247. this.baseDepth = depth;
  30248. this._size = width * height * depth;
  30249. };
  30250. /** @hidden */
  30251. InternalTexture.prototype._rebuild = function () {
  30252. var _this = this;
  30253. var proxy;
  30254. this.isReady = false;
  30255. this._cachedCoordinatesMode = null;
  30256. this._cachedWrapU = null;
  30257. this._cachedWrapV = null;
  30258. this._cachedAnisotropicFilteringLevel = null;
  30259. switch (this._dataSource) {
  30260. case InternalTexture.DATASOURCE_TEMP:
  30261. return;
  30262. case InternalTexture.DATASOURCE_URL:
  30263. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30264. _this.isReady = true;
  30265. }, null, this._buffer, undefined, this.format);
  30266. proxy._swapAndDie(this);
  30267. return;
  30268. case InternalTexture.DATASOURCE_RAW:
  30269. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30270. proxy._swapAndDie(this);
  30271. this.isReady = true;
  30272. return;
  30273. case InternalTexture.DATASOURCE_RAW3D:
  30274. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30275. proxy._swapAndDie(this);
  30276. this.isReady = true;
  30277. return;
  30278. case InternalTexture.DATASOURCE_DYNAMIC:
  30279. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30280. proxy._swapAndDie(this);
  30281. // The engine will make sure to update content so no need to flag it as isReady = true
  30282. return;
  30283. case InternalTexture.DATASOURCE_RENDERTARGET:
  30284. var options = new BABYLON.RenderTargetCreationOptions();
  30285. options.generateDepthBuffer = this._generateDepthBuffer;
  30286. options.generateMipMaps = this.generateMipMaps;
  30287. options.generateStencilBuffer = this._generateStencilBuffer;
  30288. options.samplingMode = this.samplingMode;
  30289. options.type = this.type;
  30290. if (this.isCube) {
  30291. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30292. }
  30293. else {
  30294. var size = {
  30295. width: this.width,
  30296. height: this.height
  30297. };
  30298. proxy = this._engine.createRenderTargetTexture(size, options);
  30299. }
  30300. proxy._swapAndDie(this);
  30301. this.isReady = true;
  30302. return;
  30303. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30304. var depthTextureOptions = {
  30305. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30306. comparisonFunction: this._comparisonFunction,
  30307. generateStencil: this._generateStencilBuffer,
  30308. isCube: this.isCube
  30309. };
  30310. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30311. proxy._swapAndDie(this);
  30312. this.isReady = true;
  30313. return;
  30314. case InternalTexture.DATASOURCE_CUBE:
  30315. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30316. _this.isReady = true;
  30317. }, null, this.format, this._extension);
  30318. proxy._swapAndDie(this);
  30319. return;
  30320. case InternalTexture.DATASOURCE_CUBERAW:
  30321. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30322. proxy._swapAndDie(this);
  30323. this.isReady = true;
  30324. return;
  30325. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30326. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30327. if (proxy) {
  30328. proxy._swapAndDie(_this);
  30329. }
  30330. _this.isReady = true;
  30331. }, null, this.format, this._extension);
  30332. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30333. return;
  30334. }
  30335. };
  30336. InternalTexture.prototype._swapAndDie = function (target) {
  30337. target._webGLTexture = this._webGLTexture;
  30338. if (this._framebuffer) {
  30339. target._framebuffer = this._framebuffer;
  30340. }
  30341. if (this._depthStencilBuffer) {
  30342. target._depthStencilBuffer = this._depthStencilBuffer;
  30343. }
  30344. if (this._lodTextureHigh) {
  30345. if (target._lodTextureHigh) {
  30346. target._lodTextureHigh.dispose();
  30347. }
  30348. target._lodTextureHigh = this._lodTextureHigh;
  30349. }
  30350. if (this._lodTextureMid) {
  30351. if (target._lodTextureMid) {
  30352. target._lodTextureMid.dispose();
  30353. }
  30354. target._lodTextureMid = this._lodTextureMid;
  30355. }
  30356. if (this._lodTextureLow) {
  30357. if (target._lodTextureLow) {
  30358. target._lodTextureLow.dispose();
  30359. }
  30360. target._lodTextureLow = this._lodTextureLow;
  30361. }
  30362. var cache = this._engine.getLoadedTexturesCache();
  30363. var index = cache.indexOf(this);
  30364. if (index !== -1) {
  30365. cache.splice(index, 1);
  30366. }
  30367. };
  30368. /**
  30369. * Dispose the current allocated resources
  30370. */
  30371. InternalTexture.prototype.dispose = function () {
  30372. if (!this._webGLTexture) {
  30373. return;
  30374. }
  30375. this._references--;
  30376. if (this._references === 0) {
  30377. this._engine._releaseTexture(this);
  30378. this._webGLTexture = null;
  30379. this.previous = null;
  30380. this.next = null;
  30381. }
  30382. };
  30383. /**
  30384. * The source of the texture data is unknown
  30385. */
  30386. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30387. /**
  30388. * Texture data comes from an URL
  30389. */
  30390. InternalTexture.DATASOURCE_URL = 1;
  30391. /**
  30392. * Texture data is only used for temporary storage
  30393. */
  30394. InternalTexture.DATASOURCE_TEMP = 2;
  30395. /**
  30396. * Texture data comes from raw data (ArrayBuffer)
  30397. */
  30398. InternalTexture.DATASOURCE_RAW = 3;
  30399. /**
  30400. * Texture content is dynamic (video or dynamic texture)
  30401. */
  30402. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30403. /**
  30404. * Texture content is generated by rendering to it
  30405. */
  30406. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30407. /**
  30408. * Texture content is part of a multi render target process
  30409. */
  30410. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30411. /**
  30412. * Texture data comes from a cube data file
  30413. */
  30414. InternalTexture.DATASOURCE_CUBE = 7;
  30415. /**
  30416. * Texture data comes from a raw cube data
  30417. */
  30418. InternalTexture.DATASOURCE_CUBERAW = 8;
  30419. /**
  30420. * Texture data come from a prefiltered cube data file
  30421. */
  30422. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30423. /**
  30424. * Texture content is raw 3D data
  30425. */
  30426. InternalTexture.DATASOURCE_RAW3D = 10;
  30427. /**
  30428. * Texture content is a depth texture
  30429. */
  30430. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30431. return InternalTexture;
  30432. }());
  30433. BABYLON.InternalTexture = InternalTexture;
  30434. })(BABYLON || (BABYLON = {}));
  30435. //# sourceMappingURL=babylon.internalTexture.js.map
  30436. var BABYLON;
  30437. (function (BABYLON) {
  30438. var BaseTexture = /** @class */ (function () {
  30439. function BaseTexture(scene) {
  30440. this._hasAlpha = false;
  30441. this.getAlphaFromRGB = false;
  30442. this.level = 1;
  30443. this.coordinatesIndex = 0;
  30444. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30445. /**
  30446. * | Value | Type | Description |
  30447. * | ----- | ------------------ | ----------- |
  30448. * | 0 | CLAMP_ADDRESSMODE | |
  30449. * | 1 | WRAP_ADDRESSMODE | |
  30450. * | 2 | MIRROR_ADDRESSMODE | |
  30451. */
  30452. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30453. /**
  30454. * | Value | Type | Description |
  30455. * | ----- | ------------------ | ----------- |
  30456. * | 0 | CLAMP_ADDRESSMODE | |
  30457. * | 1 | WRAP_ADDRESSMODE | |
  30458. * | 2 | MIRROR_ADDRESSMODE | |
  30459. */
  30460. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30461. /**
  30462. * | Value | Type | Description |
  30463. * | ----- | ------------------ | ----------- |
  30464. * | 0 | CLAMP_ADDRESSMODE | |
  30465. * | 1 | WRAP_ADDRESSMODE | |
  30466. * | 2 | MIRROR_ADDRESSMODE | |
  30467. */
  30468. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30469. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30470. this.isCube = false;
  30471. this.is3D = false;
  30472. this.gammaSpace = true;
  30473. this.invertZ = false;
  30474. this.lodLevelInAlpha = false;
  30475. this.isRenderTarget = false;
  30476. this.animations = new Array();
  30477. /**
  30478. * An event triggered when the texture is disposed.
  30479. */
  30480. this.onDisposeObservable = new BABYLON.Observable();
  30481. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30482. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30483. if (this._scene) {
  30484. this._scene.textures.push(this);
  30485. }
  30486. this._uid = null;
  30487. }
  30488. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30489. get: function () {
  30490. return this._hasAlpha;
  30491. },
  30492. set: function (value) {
  30493. if (this._hasAlpha === value) {
  30494. return;
  30495. }
  30496. this._hasAlpha = value;
  30497. if (this._scene) {
  30498. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30499. }
  30500. },
  30501. enumerable: true,
  30502. configurable: true
  30503. });
  30504. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30505. get: function () {
  30506. return this._coordinatesMode;
  30507. },
  30508. /**
  30509. * How a texture is mapped.
  30510. *
  30511. * | Value | Type | Description |
  30512. * | ----- | ----------------------------------- | ----------- |
  30513. * | 0 | EXPLICIT_MODE | |
  30514. * | 1 | SPHERICAL_MODE | |
  30515. * | 2 | PLANAR_MODE | |
  30516. * | 3 | CUBIC_MODE | |
  30517. * | 4 | PROJECTION_MODE | |
  30518. * | 5 | SKYBOX_MODE | |
  30519. * | 6 | INVCUBIC_MODE | |
  30520. * | 7 | EQUIRECTANGULAR_MODE | |
  30521. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30522. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30523. */
  30524. set: function (value) {
  30525. if (this._coordinatesMode === value) {
  30526. return;
  30527. }
  30528. this._coordinatesMode = value;
  30529. if (this._scene) {
  30530. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30531. }
  30532. },
  30533. enumerable: true,
  30534. configurable: true
  30535. });
  30536. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30537. /**
  30538. * Gets whether or not the texture contains RGBD data.
  30539. */
  30540. get: function () {
  30541. return this._texture != null && this._texture._isRGBD;
  30542. },
  30543. enumerable: true,
  30544. configurable: true
  30545. });
  30546. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30547. get: function () {
  30548. if (this._texture)
  30549. return this._texture._lodGenerationOffset;
  30550. return 0.0;
  30551. },
  30552. set: function (value) {
  30553. if (this._texture)
  30554. this._texture._lodGenerationOffset = value;
  30555. },
  30556. enumerable: true,
  30557. configurable: true
  30558. });
  30559. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30560. get: function () {
  30561. if (this._texture)
  30562. return this._texture._lodGenerationScale;
  30563. return 0.0;
  30564. },
  30565. set: function (value) {
  30566. if (this._texture)
  30567. this._texture._lodGenerationScale = value;
  30568. },
  30569. enumerable: true,
  30570. configurable: true
  30571. });
  30572. Object.defineProperty(BaseTexture.prototype, "uid", {
  30573. get: function () {
  30574. if (!this._uid) {
  30575. this._uid = BABYLON.Tools.RandomId();
  30576. }
  30577. return this._uid;
  30578. },
  30579. enumerable: true,
  30580. configurable: true
  30581. });
  30582. BaseTexture.prototype.toString = function () {
  30583. return this.name;
  30584. };
  30585. BaseTexture.prototype.getClassName = function () {
  30586. return "BaseTexture";
  30587. };
  30588. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30589. set: function (callback) {
  30590. if (this._onDisposeObserver) {
  30591. this.onDisposeObservable.remove(this._onDisposeObserver);
  30592. }
  30593. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30594. },
  30595. enumerable: true,
  30596. configurable: true
  30597. });
  30598. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30599. get: function () {
  30600. return true;
  30601. },
  30602. enumerable: true,
  30603. configurable: true
  30604. });
  30605. BaseTexture.prototype.getScene = function () {
  30606. return this._scene;
  30607. };
  30608. BaseTexture.prototype.getTextureMatrix = function () {
  30609. return BABYLON.Matrix.IdentityReadOnly;
  30610. };
  30611. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30612. return BABYLON.Matrix.IdentityReadOnly;
  30613. };
  30614. BaseTexture.prototype.getInternalTexture = function () {
  30615. return this._texture;
  30616. };
  30617. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30618. return !this.isBlocking || this.isReady();
  30619. };
  30620. BaseTexture.prototype.isReady = function () {
  30621. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30622. this.delayLoad();
  30623. return false;
  30624. }
  30625. if (this._texture) {
  30626. return this._texture.isReady;
  30627. }
  30628. return false;
  30629. };
  30630. BaseTexture.prototype.getSize = function () {
  30631. if (this._texture && this._texture.width) {
  30632. return new BABYLON.Size(this._texture.width, this._texture.height);
  30633. }
  30634. if (this._texture && this._texture._size) {
  30635. return new BABYLON.Size(this._texture._size, this._texture._size);
  30636. }
  30637. return BABYLON.Size.Zero();
  30638. };
  30639. BaseTexture.prototype.getBaseSize = function () {
  30640. if (!this.isReady() || !this._texture)
  30641. return BABYLON.Size.Zero();
  30642. if (this._texture._size) {
  30643. return new BABYLON.Size(this._texture._size, this._texture._size);
  30644. }
  30645. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30646. };
  30647. BaseTexture.prototype.scale = function (ratio) {
  30648. };
  30649. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30650. get: function () {
  30651. return false;
  30652. },
  30653. enumerable: true,
  30654. configurable: true
  30655. });
  30656. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30657. if (!this._scene) {
  30658. return null;
  30659. }
  30660. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30661. for (var index = 0; index < texturesCache.length; index++) {
  30662. var texturesCacheEntry = texturesCache[index];
  30663. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30664. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30665. texturesCacheEntry.incrementReferences();
  30666. return texturesCacheEntry;
  30667. }
  30668. }
  30669. }
  30670. return null;
  30671. };
  30672. BaseTexture.prototype._rebuild = function () {
  30673. };
  30674. BaseTexture.prototype.delayLoad = function () {
  30675. };
  30676. BaseTexture.prototype.clone = function () {
  30677. return null;
  30678. };
  30679. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30680. get: function () {
  30681. if (!this._texture) {
  30682. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30683. }
  30684. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30685. },
  30686. enumerable: true,
  30687. configurable: true
  30688. });
  30689. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30690. get: function () {
  30691. if (!this._texture) {
  30692. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30693. }
  30694. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30695. },
  30696. enumerable: true,
  30697. configurable: true
  30698. });
  30699. /**
  30700. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30701. * This will returns an RGBA array buffer containing either in values (0-255) or
  30702. * float values (0-1) depending of the underlying buffer type.
  30703. * @param faceIndex The face of the texture to read (in case of cube texture)
  30704. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30705. * @returns The Array buffer containing the pixels data.
  30706. */
  30707. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30708. if (faceIndex === void 0) { faceIndex = 0; }
  30709. if (level === void 0) { level = 0; }
  30710. if (!this._texture) {
  30711. return null;
  30712. }
  30713. var size = this.getSize();
  30714. var width = size.width;
  30715. var height = size.height;
  30716. var scene = this.getScene();
  30717. if (!scene) {
  30718. return null;
  30719. }
  30720. var engine = scene.getEngine();
  30721. if (level != 0) {
  30722. width = width / Math.pow(2, level);
  30723. height = height / Math.pow(2, level);
  30724. width = Math.round(width);
  30725. height = Math.round(height);
  30726. }
  30727. if (this._texture.isCube) {
  30728. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30729. }
  30730. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30731. };
  30732. BaseTexture.prototype.releaseInternalTexture = function () {
  30733. if (this._texture) {
  30734. this._texture.dispose();
  30735. this._texture = null;
  30736. }
  30737. };
  30738. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30739. get: function () {
  30740. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30741. return null;
  30742. }
  30743. if (!this._texture._sphericalPolynomial) {
  30744. this._texture._sphericalPolynomial =
  30745. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30746. }
  30747. return this._texture._sphericalPolynomial;
  30748. },
  30749. set: function (value) {
  30750. if (this._texture) {
  30751. this._texture._sphericalPolynomial = value;
  30752. }
  30753. },
  30754. enumerable: true,
  30755. configurable: true
  30756. });
  30757. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30758. get: function () {
  30759. if (this._texture) {
  30760. return this._texture._lodTextureHigh;
  30761. }
  30762. return null;
  30763. },
  30764. enumerable: true,
  30765. configurable: true
  30766. });
  30767. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30768. get: function () {
  30769. if (this._texture) {
  30770. return this._texture._lodTextureMid;
  30771. }
  30772. return null;
  30773. },
  30774. enumerable: true,
  30775. configurable: true
  30776. });
  30777. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30778. get: function () {
  30779. if (this._texture) {
  30780. return this._texture._lodTextureLow;
  30781. }
  30782. return null;
  30783. },
  30784. enumerable: true,
  30785. configurable: true
  30786. });
  30787. BaseTexture.prototype.dispose = function () {
  30788. if (!this._scene) {
  30789. return;
  30790. }
  30791. // Animations
  30792. this._scene.stopAnimation(this);
  30793. // Remove from scene
  30794. this._scene._removePendingData(this);
  30795. var index = this._scene.textures.indexOf(this);
  30796. if (index >= 0) {
  30797. this._scene.textures.splice(index, 1);
  30798. }
  30799. if (this._texture === undefined) {
  30800. return;
  30801. }
  30802. // Release
  30803. this.releaseInternalTexture();
  30804. // Callback
  30805. this.onDisposeObservable.notifyObservers(this);
  30806. this.onDisposeObservable.clear();
  30807. };
  30808. BaseTexture.prototype.serialize = function () {
  30809. if (!this.name) {
  30810. return null;
  30811. }
  30812. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30813. // Animations
  30814. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30815. return serializationObject;
  30816. };
  30817. BaseTexture.WhenAllReady = function (textures, callback) {
  30818. var numRemaining = textures.length;
  30819. if (numRemaining === 0) {
  30820. callback();
  30821. return;
  30822. }
  30823. var _loop_1 = function () {
  30824. texture = textures[i];
  30825. if (texture.isReady()) {
  30826. if (--numRemaining === 0) {
  30827. callback();
  30828. }
  30829. }
  30830. else {
  30831. onLoadObservable = texture.onLoadObservable;
  30832. var onLoadCallback_1 = function () {
  30833. onLoadObservable.removeCallback(onLoadCallback_1);
  30834. if (--numRemaining === 0) {
  30835. callback();
  30836. }
  30837. };
  30838. onLoadObservable.add(onLoadCallback_1);
  30839. }
  30840. };
  30841. var texture, onLoadObservable;
  30842. for (var i = 0; i < textures.length; i++) {
  30843. _loop_1();
  30844. }
  30845. };
  30846. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30847. __decorate([
  30848. BABYLON.serialize()
  30849. ], BaseTexture.prototype, "name", void 0);
  30850. __decorate([
  30851. BABYLON.serialize("hasAlpha")
  30852. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30853. __decorate([
  30854. BABYLON.serialize()
  30855. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30856. __decorate([
  30857. BABYLON.serialize()
  30858. ], BaseTexture.prototype, "level", void 0);
  30859. __decorate([
  30860. BABYLON.serialize()
  30861. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30862. __decorate([
  30863. BABYLON.serialize("coordinatesMode")
  30864. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30865. __decorate([
  30866. BABYLON.serialize()
  30867. ], BaseTexture.prototype, "wrapU", void 0);
  30868. __decorate([
  30869. BABYLON.serialize()
  30870. ], BaseTexture.prototype, "wrapV", void 0);
  30871. __decorate([
  30872. BABYLON.serialize()
  30873. ], BaseTexture.prototype, "wrapR", void 0);
  30874. __decorate([
  30875. BABYLON.serialize()
  30876. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30877. __decorate([
  30878. BABYLON.serialize()
  30879. ], BaseTexture.prototype, "isCube", void 0);
  30880. __decorate([
  30881. BABYLON.serialize()
  30882. ], BaseTexture.prototype, "is3D", void 0);
  30883. __decorate([
  30884. BABYLON.serialize()
  30885. ], BaseTexture.prototype, "gammaSpace", void 0);
  30886. __decorate([
  30887. BABYLON.serialize()
  30888. ], BaseTexture.prototype, "invertZ", void 0);
  30889. __decorate([
  30890. BABYLON.serialize()
  30891. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30892. __decorate([
  30893. BABYLON.serialize()
  30894. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30895. __decorate([
  30896. BABYLON.serialize()
  30897. ], BaseTexture.prototype, "lodGenerationScale", null);
  30898. __decorate([
  30899. BABYLON.serialize()
  30900. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30901. return BaseTexture;
  30902. }());
  30903. BABYLON.BaseTexture = BaseTexture;
  30904. })(BABYLON || (BABYLON = {}));
  30905. //# sourceMappingURL=babylon.baseTexture.js.map
  30906. var BABYLON;
  30907. (function (BABYLON) {
  30908. var Texture = /** @class */ (function (_super) {
  30909. __extends(Texture, _super);
  30910. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30911. if (noMipmap === void 0) { noMipmap = false; }
  30912. if (invertY === void 0) { invertY = true; }
  30913. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30914. if (onLoad === void 0) { onLoad = null; }
  30915. if (onError === void 0) { onError = null; }
  30916. if (buffer === void 0) { buffer = null; }
  30917. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30918. var _this = _super.call(this, scene) || this;
  30919. _this.uOffset = 0;
  30920. _this.vOffset = 0;
  30921. _this.uScale = 1.0;
  30922. _this.vScale = 1.0;
  30923. _this.uAng = 0;
  30924. _this.vAng = 0;
  30925. _this.wAng = 0;
  30926. /**
  30927. * Defines the center of rotation (U)
  30928. */
  30929. _this.uRotationCenter = 0.5;
  30930. /**
  30931. * Defines the center of rotation (V)
  30932. */
  30933. _this.vRotationCenter = 0.5;
  30934. /**
  30935. * Defines the center of rotation (W)
  30936. */
  30937. _this.wRotationCenter = 0.5;
  30938. _this._isBlocking = true;
  30939. _this.name = url || "";
  30940. _this.url = url;
  30941. _this._noMipmap = noMipmap;
  30942. _this._invertY = invertY;
  30943. _this._samplingMode = samplingMode;
  30944. _this._buffer = buffer;
  30945. _this._deleteBuffer = deleteBuffer;
  30946. if (format) {
  30947. _this._format = format;
  30948. }
  30949. scene = _this.getScene();
  30950. if (!scene) {
  30951. return _this;
  30952. }
  30953. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30954. var load = function () {
  30955. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30956. _this.onLoadObservable.notifyObservers(_this);
  30957. }
  30958. if (onLoad) {
  30959. onLoad();
  30960. }
  30961. if (!_this.isBlocking && scene) {
  30962. scene.resetCachedMaterial();
  30963. }
  30964. };
  30965. if (!_this.url) {
  30966. _this._delayedOnLoad = load;
  30967. _this._delayedOnError = onError;
  30968. return _this;
  30969. }
  30970. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30971. if (!_this._texture) {
  30972. if (!scene.useDelayedTextureLoading) {
  30973. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30974. if (deleteBuffer) {
  30975. delete _this._buffer;
  30976. }
  30977. }
  30978. else {
  30979. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30980. _this._delayedOnLoad = load;
  30981. _this._delayedOnError = onError;
  30982. }
  30983. }
  30984. else {
  30985. if (_this._texture.isReady) {
  30986. BABYLON.Tools.SetImmediate(function () { return load(); });
  30987. }
  30988. else {
  30989. _this._texture.onLoadedObservable.add(load);
  30990. }
  30991. }
  30992. return _this;
  30993. }
  30994. Object.defineProperty(Texture.prototype, "noMipmap", {
  30995. get: function () {
  30996. return this._noMipmap;
  30997. },
  30998. enumerable: true,
  30999. configurable: true
  31000. });
  31001. Object.defineProperty(Texture.prototype, "isBlocking", {
  31002. get: function () {
  31003. return this._isBlocking;
  31004. },
  31005. set: function (value) {
  31006. this._isBlocking = value;
  31007. },
  31008. enumerable: true,
  31009. configurable: true
  31010. });
  31011. Object.defineProperty(Texture.prototype, "samplingMode", {
  31012. get: function () {
  31013. return this._samplingMode;
  31014. },
  31015. enumerable: true,
  31016. configurable: true
  31017. });
  31018. /**
  31019. * Update the url (and optional buffer) of this texture if url was null during construction.
  31020. * @param url the url of the texture
  31021. * @param buffer the buffer of the texture (defaults to null)
  31022. */
  31023. Texture.prototype.updateURL = function (url, buffer) {
  31024. if (buffer === void 0) { buffer = null; }
  31025. if (this.url) {
  31026. throw new Error("URL is already set");
  31027. }
  31028. this.url = url;
  31029. this._buffer = buffer;
  31030. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31031. this.delayLoad();
  31032. };
  31033. Texture.prototype.delayLoad = function () {
  31034. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31035. return;
  31036. }
  31037. var scene = this.getScene();
  31038. if (!scene) {
  31039. return;
  31040. }
  31041. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31042. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31043. if (!this._texture) {
  31044. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31045. if (this._deleteBuffer) {
  31046. delete this._buffer;
  31047. }
  31048. }
  31049. else {
  31050. if (this._delayedOnLoad) {
  31051. if (this._texture.isReady) {
  31052. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31053. }
  31054. else {
  31055. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31056. }
  31057. }
  31058. }
  31059. this._delayedOnLoad = null;
  31060. this._delayedOnError = null;
  31061. };
  31062. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31063. if (!this._texture) {
  31064. return;
  31065. }
  31066. var scene = this.getScene();
  31067. if (!scene) {
  31068. return;
  31069. }
  31070. this._samplingMode = samplingMode;
  31071. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31072. };
  31073. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31074. x *= this.uScale;
  31075. y *= this.vScale;
  31076. x -= this.uRotationCenter * this.uScale;
  31077. y -= this.vRotationCenter * this.vScale;
  31078. z -= this.wRotationCenter;
  31079. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31080. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31081. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31082. t.z += this.wRotationCenter;
  31083. };
  31084. Texture.prototype.getTextureMatrix = function () {
  31085. var _this = this;
  31086. if (this.uOffset === this._cachedUOffset &&
  31087. this.vOffset === this._cachedVOffset &&
  31088. this.uScale === this._cachedUScale &&
  31089. this.vScale === this._cachedVScale &&
  31090. this.uAng === this._cachedUAng &&
  31091. this.vAng === this._cachedVAng &&
  31092. this.wAng === this._cachedWAng) {
  31093. return this._cachedTextureMatrix;
  31094. }
  31095. this._cachedUOffset = this.uOffset;
  31096. this._cachedVOffset = this.vOffset;
  31097. this._cachedUScale = this.uScale;
  31098. this._cachedVScale = this.vScale;
  31099. this._cachedUAng = this.uAng;
  31100. this._cachedVAng = this.vAng;
  31101. this._cachedWAng = this.wAng;
  31102. if (!this._cachedTextureMatrix) {
  31103. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31104. this._rowGenerationMatrix = new BABYLON.Matrix();
  31105. this._t0 = BABYLON.Vector3.Zero();
  31106. this._t1 = BABYLON.Vector3.Zero();
  31107. this._t2 = BABYLON.Vector3.Zero();
  31108. }
  31109. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31110. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31111. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31112. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31113. this._t1.subtractInPlace(this._t0);
  31114. this._t2.subtractInPlace(this._t0);
  31115. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31116. this._cachedTextureMatrix.m[0] = this._t1.x;
  31117. this._cachedTextureMatrix.m[1] = this._t1.y;
  31118. this._cachedTextureMatrix.m[2] = this._t1.z;
  31119. this._cachedTextureMatrix.m[4] = this._t2.x;
  31120. this._cachedTextureMatrix.m[5] = this._t2.y;
  31121. this._cachedTextureMatrix.m[6] = this._t2.z;
  31122. this._cachedTextureMatrix.m[8] = this._t0.x;
  31123. this._cachedTextureMatrix.m[9] = this._t0.y;
  31124. this._cachedTextureMatrix.m[10] = this._t0.z;
  31125. var scene = this.getScene();
  31126. if (!scene) {
  31127. return this._cachedTextureMatrix;
  31128. }
  31129. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31130. return mat.hasTexture(_this);
  31131. });
  31132. return this._cachedTextureMatrix;
  31133. };
  31134. Texture.prototype.getReflectionTextureMatrix = function () {
  31135. var _this = this;
  31136. var scene = this.getScene();
  31137. if (!scene) {
  31138. return this._cachedTextureMatrix;
  31139. }
  31140. if (this.uOffset === this._cachedUOffset &&
  31141. this.vOffset === this._cachedVOffset &&
  31142. this.uScale === this._cachedUScale &&
  31143. this.vScale === this._cachedVScale &&
  31144. this.coordinatesMode === this._cachedCoordinatesMode) {
  31145. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31146. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31147. return this._cachedTextureMatrix;
  31148. }
  31149. }
  31150. else {
  31151. return this._cachedTextureMatrix;
  31152. }
  31153. }
  31154. if (!this._cachedTextureMatrix) {
  31155. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31156. }
  31157. if (!this._projectionModeMatrix) {
  31158. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31159. }
  31160. this._cachedUOffset = this.uOffset;
  31161. this._cachedVOffset = this.vOffset;
  31162. this._cachedUScale = this.uScale;
  31163. this._cachedVScale = this.vScale;
  31164. this._cachedCoordinatesMode = this.coordinatesMode;
  31165. switch (this.coordinatesMode) {
  31166. case Texture.PLANAR_MODE:
  31167. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31168. this._cachedTextureMatrix[0] = this.uScale;
  31169. this._cachedTextureMatrix[5] = this.vScale;
  31170. this._cachedTextureMatrix[12] = this.uOffset;
  31171. this._cachedTextureMatrix[13] = this.vOffset;
  31172. break;
  31173. case Texture.PROJECTION_MODE:
  31174. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31175. this._projectionModeMatrix.m[0] = 0.5;
  31176. this._projectionModeMatrix.m[5] = -0.5;
  31177. this._projectionModeMatrix.m[10] = 0.0;
  31178. this._projectionModeMatrix.m[12] = 0.5;
  31179. this._projectionModeMatrix.m[13] = 0.5;
  31180. this._projectionModeMatrix.m[14] = 1.0;
  31181. this._projectionModeMatrix.m[15] = 1.0;
  31182. var projectionMatrix = scene.getProjectionMatrix();
  31183. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31184. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31185. break;
  31186. default:
  31187. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31188. break;
  31189. }
  31190. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31191. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31192. });
  31193. return this._cachedTextureMatrix;
  31194. };
  31195. Texture.prototype.clone = function () {
  31196. var _this = this;
  31197. return BABYLON.SerializationHelper.Clone(function () {
  31198. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31199. }, this);
  31200. };
  31201. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31202. get: function () {
  31203. if (!this._onLoadObservable) {
  31204. this._onLoadObservable = new BABYLON.Observable();
  31205. }
  31206. return this._onLoadObservable;
  31207. },
  31208. enumerable: true,
  31209. configurable: true
  31210. });
  31211. Texture.prototype.serialize = function () {
  31212. var serializationObject = _super.prototype.serialize.call(this);
  31213. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31214. serializationObject.base64String = this._buffer;
  31215. serializationObject.name = serializationObject.name.replace("data:", "");
  31216. }
  31217. serializationObject.invertY = this._invertY;
  31218. serializationObject.samplingMode = this.samplingMode;
  31219. return serializationObject;
  31220. };
  31221. Texture.prototype.getClassName = function () {
  31222. return "Texture";
  31223. };
  31224. Texture.prototype.dispose = function () {
  31225. _super.prototype.dispose.call(this);
  31226. if (this.onLoadObservable) {
  31227. this.onLoadObservable.clear();
  31228. this._onLoadObservable = null;
  31229. }
  31230. this._delayedOnLoad = null;
  31231. this._delayedOnError = null;
  31232. };
  31233. // Statics
  31234. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31235. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31236. if (onLoad === void 0) { onLoad = null; }
  31237. if (onError === void 0) { onError = null; }
  31238. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31239. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31240. };
  31241. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31242. if (parsedTexture.customType) {
  31243. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31244. // Update Sampling Mode
  31245. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31246. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31247. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31248. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31249. }
  31250. }
  31251. return parsedCustomTexture;
  31252. }
  31253. if (parsedTexture.isCube) {
  31254. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31255. }
  31256. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31257. return null;
  31258. }
  31259. var texture = BABYLON.SerializationHelper.Parse(function () {
  31260. var generateMipMaps = true;
  31261. if (parsedTexture.noMipmap) {
  31262. generateMipMaps = false;
  31263. }
  31264. if (parsedTexture.mirrorPlane) {
  31265. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31266. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31267. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31268. return mirrorTexture;
  31269. }
  31270. else if (parsedTexture.isRenderTarget) {
  31271. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31272. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31273. return renderTargetTexture;
  31274. }
  31275. else {
  31276. var texture;
  31277. if (parsedTexture.base64String) {
  31278. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31279. }
  31280. else {
  31281. var url = rootUrl + parsedTexture.name;
  31282. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31283. url = parsedTexture.url;
  31284. }
  31285. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31286. }
  31287. return texture;
  31288. }
  31289. }, parsedTexture, scene);
  31290. // Update Sampling Mode
  31291. if (parsedTexture.samplingMode) {
  31292. var sampling = parsedTexture.samplingMode;
  31293. if (texture._samplingMode !== sampling) {
  31294. texture.updateSamplingMode(sampling);
  31295. }
  31296. }
  31297. // Animations
  31298. if (parsedTexture.animations) {
  31299. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31300. var parsedAnimation = parsedTexture.animations[animationIndex];
  31301. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31302. }
  31303. }
  31304. return texture;
  31305. };
  31306. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31307. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31308. if (noMipmap === void 0) { noMipmap = false; }
  31309. if (invertY === void 0) { invertY = true; }
  31310. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31311. if (onLoad === void 0) { onLoad = null; }
  31312. if (onError === void 0) { onError = null; }
  31313. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31314. if (name.substr(0, 5) !== "data:") {
  31315. name = "data:" + name;
  31316. }
  31317. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31318. };
  31319. // Constants
  31320. Texture.NEAREST_SAMPLINGMODE = 1;
  31321. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31322. Texture.BILINEAR_SAMPLINGMODE = 2;
  31323. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31324. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31325. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31326. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31327. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31328. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31329. Texture.NEAREST_LINEAR = 7;
  31330. Texture.NEAREST_NEAREST = 8;
  31331. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31332. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31333. Texture.LINEAR_LINEAR = 11;
  31334. Texture.LINEAR_NEAREST = 12;
  31335. Texture.EXPLICIT_MODE = 0;
  31336. Texture.SPHERICAL_MODE = 1;
  31337. Texture.PLANAR_MODE = 2;
  31338. Texture.CUBIC_MODE = 3;
  31339. Texture.PROJECTION_MODE = 4;
  31340. Texture.SKYBOX_MODE = 5;
  31341. Texture.INVCUBIC_MODE = 6;
  31342. Texture.EQUIRECTANGULAR_MODE = 7;
  31343. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31344. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31345. Texture.CLAMP_ADDRESSMODE = 0;
  31346. Texture.WRAP_ADDRESSMODE = 1;
  31347. Texture.MIRROR_ADDRESSMODE = 2;
  31348. /**
  31349. * 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
  31350. */
  31351. Texture.UseSerializedUrlIfAny = false;
  31352. __decorate([
  31353. BABYLON.serialize()
  31354. ], Texture.prototype, "url", void 0);
  31355. __decorate([
  31356. BABYLON.serialize()
  31357. ], Texture.prototype, "uOffset", void 0);
  31358. __decorate([
  31359. BABYLON.serialize()
  31360. ], Texture.prototype, "vOffset", void 0);
  31361. __decorate([
  31362. BABYLON.serialize()
  31363. ], Texture.prototype, "uScale", void 0);
  31364. __decorate([
  31365. BABYLON.serialize()
  31366. ], Texture.prototype, "vScale", void 0);
  31367. __decorate([
  31368. BABYLON.serialize()
  31369. ], Texture.prototype, "uAng", void 0);
  31370. __decorate([
  31371. BABYLON.serialize()
  31372. ], Texture.prototype, "vAng", void 0);
  31373. __decorate([
  31374. BABYLON.serialize()
  31375. ], Texture.prototype, "wAng", void 0);
  31376. __decorate([
  31377. BABYLON.serialize()
  31378. ], Texture.prototype, "uRotationCenter", void 0);
  31379. __decorate([
  31380. BABYLON.serialize()
  31381. ], Texture.prototype, "vRotationCenter", void 0);
  31382. __decorate([
  31383. BABYLON.serialize()
  31384. ], Texture.prototype, "wRotationCenter", void 0);
  31385. __decorate([
  31386. BABYLON.serialize()
  31387. ], Texture.prototype, "isBlocking", null);
  31388. return Texture;
  31389. }(BABYLON.BaseTexture));
  31390. BABYLON.Texture = Texture;
  31391. })(BABYLON || (BABYLON = {}));
  31392. //# sourceMappingURL=babylon.texture.js.map
  31393. var BABYLON;
  31394. (function (BABYLON) {
  31395. /**
  31396. * @hidden
  31397. **/
  31398. var _InstancesBatch = /** @class */ (function () {
  31399. function _InstancesBatch() {
  31400. this.mustReturn = false;
  31401. this.visibleInstances = new Array();
  31402. this.renderSelf = new Array();
  31403. }
  31404. return _InstancesBatch;
  31405. }());
  31406. BABYLON._InstancesBatch = _InstancesBatch;
  31407. var Mesh = /** @class */ (function (_super) {
  31408. __extends(Mesh, _super);
  31409. /**
  31410. * @constructor
  31411. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31412. * @param {Scene} scene The scene to add this mesh to.
  31413. * @param {Node} parent The parent of this mesh, if it has one
  31414. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31415. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31416. * When false, achieved by calling a clone(), also passing False.
  31417. * This will make creation of children, recursive.
  31418. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31419. */
  31420. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31421. if (scene === void 0) { scene = null; }
  31422. if (parent === void 0) { parent = null; }
  31423. if (source === void 0) { source = null; }
  31424. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31425. var _this = _super.call(this, name, scene) || this;
  31426. // Events
  31427. /**
  31428. * An event triggered before rendering the mesh
  31429. */
  31430. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31431. /**
  31432. * An event triggered after rendering the mesh
  31433. */
  31434. _this.onAfterRenderObservable = new BABYLON.Observable();
  31435. /**
  31436. * An event triggered before drawing the mesh
  31437. */
  31438. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31439. // Members
  31440. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31441. _this.instances = new Array();
  31442. _this._LODLevels = new Array();
  31443. _this._visibleInstances = {};
  31444. _this._renderIdForInstances = new Array();
  31445. _this._batchCache = new _InstancesBatch();
  31446. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31447. // Use by builder only to know what orientation were the mesh build in.
  31448. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31449. _this.overrideMaterialSideOrientation = null;
  31450. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31451. // Will be used to save a source mesh reference, If any
  31452. _this._source = null;
  31453. scene = _this.getScene();
  31454. if (source) {
  31455. // Geometry
  31456. if (source._geometry) {
  31457. source._geometry.applyToMesh(_this);
  31458. }
  31459. // Deep copy
  31460. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31461. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31462. // Source mesh
  31463. _this._source = source;
  31464. // Metadata
  31465. if (source.metadata && source.metadata.clone) {
  31466. _this.metadata = source.metadata.clone();
  31467. }
  31468. else {
  31469. _this.metadata = source.metadata;
  31470. }
  31471. // Tags
  31472. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31473. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31474. }
  31475. // Parent
  31476. _this.parent = source.parent;
  31477. // Pivot
  31478. _this.setPivotMatrix(source.getPivotMatrix());
  31479. _this.id = name + "." + source.id;
  31480. // Material
  31481. _this.material = source.material;
  31482. var index;
  31483. if (!doNotCloneChildren) {
  31484. // Children
  31485. var directDescendants = source.getDescendants(true);
  31486. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31487. var child = directDescendants[index_1];
  31488. if (child.clone) {
  31489. child.clone(name + "." + child.name, _this);
  31490. }
  31491. }
  31492. }
  31493. // Physics clone
  31494. var physicsEngine = _this.getScene().getPhysicsEngine();
  31495. if (clonePhysicsImpostor && physicsEngine) {
  31496. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31497. if (impostor) {
  31498. _this.physicsImpostor = impostor.clone(_this);
  31499. }
  31500. }
  31501. // Particles
  31502. for (index = 0; index < scene.particleSystems.length; index++) {
  31503. var system = scene.particleSystems[index];
  31504. if (system.emitter === source) {
  31505. system.clone(system.name, _this);
  31506. }
  31507. }
  31508. _this.computeWorldMatrix(true);
  31509. }
  31510. // Parent
  31511. if (parent !== null) {
  31512. _this.parent = parent;
  31513. }
  31514. return _this;
  31515. }
  31516. Object.defineProperty(Mesh, "FRONTSIDE", {
  31517. /**
  31518. * Mesh side orientation : usually the external or front surface
  31519. */
  31520. get: function () {
  31521. return Mesh._FRONTSIDE;
  31522. },
  31523. enumerable: true,
  31524. configurable: true
  31525. });
  31526. Object.defineProperty(Mesh, "BACKSIDE", {
  31527. /**
  31528. * Mesh side orientation : usually the internal or back surface
  31529. */
  31530. get: function () {
  31531. return Mesh._BACKSIDE;
  31532. },
  31533. enumerable: true,
  31534. configurable: true
  31535. });
  31536. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31537. /**
  31538. * Mesh side orientation : both internal and external or front and back surfaces
  31539. */
  31540. get: function () {
  31541. return Mesh._DOUBLESIDE;
  31542. },
  31543. enumerable: true,
  31544. configurable: true
  31545. });
  31546. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31547. /**
  31548. * Mesh side orientation : by default, `FRONTSIDE`
  31549. */
  31550. get: function () {
  31551. return Mesh._DEFAULTSIDE;
  31552. },
  31553. enumerable: true,
  31554. configurable: true
  31555. });
  31556. Object.defineProperty(Mesh, "NO_CAP", {
  31557. /**
  31558. * Mesh cap setting : no cap
  31559. */
  31560. get: function () {
  31561. return Mesh._NO_CAP;
  31562. },
  31563. enumerable: true,
  31564. configurable: true
  31565. });
  31566. Object.defineProperty(Mesh, "CAP_START", {
  31567. /**
  31568. * Mesh cap setting : one cap at the beginning of the mesh
  31569. */
  31570. get: function () {
  31571. return Mesh._CAP_START;
  31572. },
  31573. enumerable: true,
  31574. configurable: true
  31575. });
  31576. Object.defineProperty(Mesh, "CAP_END", {
  31577. /**
  31578. * Mesh cap setting : one cap at the end of the mesh
  31579. */
  31580. get: function () {
  31581. return Mesh._CAP_END;
  31582. },
  31583. enumerable: true,
  31584. configurable: true
  31585. });
  31586. Object.defineProperty(Mesh, "CAP_ALL", {
  31587. /**
  31588. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31589. */
  31590. get: function () {
  31591. return Mesh._CAP_ALL;
  31592. },
  31593. enumerable: true,
  31594. configurable: true
  31595. });
  31596. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31597. set: function (callback) {
  31598. if (this._onBeforeDrawObserver) {
  31599. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31600. }
  31601. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31602. },
  31603. enumerable: true,
  31604. configurable: true
  31605. });
  31606. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31607. get: function () {
  31608. return this._morphTargetManager;
  31609. },
  31610. set: function (value) {
  31611. if (this._morphTargetManager === value) {
  31612. return;
  31613. }
  31614. this._morphTargetManager = value;
  31615. this._syncGeometryWithMorphTargetManager();
  31616. },
  31617. enumerable: true,
  31618. configurable: true
  31619. });
  31620. Object.defineProperty(Mesh.prototype, "source", {
  31621. get: function () {
  31622. return this._source;
  31623. },
  31624. enumerable: true,
  31625. configurable: true
  31626. });
  31627. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31628. get: function () {
  31629. return this._unIndexed;
  31630. },
  31631. set: function (value) {
  31632. if (this._unIndexed !== value) {
  31633. this._unIndexed = value;
  31634. this._markSubMeshesAsAttributesDirty();
  31635. }
  31636. },
  31637. enumerable: true,
  31638. configurable: true
  31639. });
  31640. // Methods
  31641. /**
  31642. * Returns the string "Mesh".
  31643. */
  31644. Mesh.prototype.getClassName = function () {
  31645. return "Mesh";
  31646. };
  31647. /**
  31648. * Returns a string.
  31649. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31650. */
  31651. Mesh.prototype.toString = function (fullDetails) {
  31652. var ret = _super.prototype.toString.call(this, fullDetails);
  31653. ret += ", n vertices: " + this.getTotalVertices();
  31654. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31655. if (this.animations) {
  31656. for (var i = 0; i < this.animations.length; i++) {
  31657. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31658. }
  31659. }
  31660. if (fullDetails) {
  31661. if (this._geometry) {
  31662. var ib = this.getIndices();
  31663. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31664. if (vb && ib) {
  31665. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31666. }
  31667. }
  31668. else {
  31669. ret += ", flat shading: UNKNOWN";
  31670. }
  31671. }
  31672. return ret;
  31673. };
  31674. Mesh.prototype._unBindEffect = function () {
  31675. _super.prototype._unBindEffect.call(this);
  31676. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31677. var instance = _a[_i];
  31678. instance._unBindEffect();
  31679. }
  31680. };
  31681. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31682. /**
  31683. * True if the mesh has some Levels Of Details (LOD).
  31684. * Returns a boolean.
  31685. */
  31686. get: function () {
  31687. return this._LODLevels.length > 0;
  31688. },
  31689. enumerable: true,
  31690. configurable: true
  31691. });
  31692. /**
  31693. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31694. * @returns an array of {BABYLON.MeshLODLevel}
  31695. */
  31696. Mesh.prototype.getLODLevels = function () {
  31697. return this._LODLevels;
  31698. };
  31699. Mesh.prototype._sortLODLevels = function () {
  31700. this._LODLevels.sort(function (a, b) {
  31701. if (a.distance < b.distance) {
  31702. return 1;
  31703. }
  31704. if (a.distance > b.distance) {
  31705. return -1;
  31706. }
  31707. return 0;
  31708. });
  31709. };
  31710. /**
  31711. * Add a mesh as LOD level triggered at the given distance.
  31712. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31713. * @param distance The distance from the center of the object to show this level
  31714. * @param mesh The mesh to be added as LOD level (can be null)
  31715. * @return This mesh (for chaining)
  31716. */
  31717. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31718. if (mesh && mesh._masterMesh) {
  31719. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31720. return this;
  31721. }
  31722. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31723. this._LODLevels.push(level);
  31724. if (mesh) {
  31725. mesh._masterMesh = this;
  31726. }
  31727. this._sortLODLevels();
  31728. return this;
  31729. };
  31730. /**
  31731. * Returns the LOD level mesh at the passed distance or null if not found.
  31732. * It is related to the method `addLODLevel(distance, mesh)`.
  31733. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31734. * Returns an object Mesh or `null`.
  31735. */
  31736. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31737. for (var index = 0; index < this._LODLevels.length; index++) {
  31738. var level = this._LODLevels[index];
  31739. if (level.distance === distance) {
  31740. return level.mesh;
  31741. }
  31742. }
  31743. return null;
  31744. };
  31745. /**
  31746. * Remove a mesh from the LOD array
  31747. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31748. * @param {Mesh} mesh The mesh to be removed.
  31749. * @return {Mesh} This mesh (for chaining)
  31750. */
  31751. Mesh.prototype.removeLODLevel = function (mesh) {
  31752. for (var index = 0; index < this._LODLevels.length; index++) {
  31753. if (this._LODLevels[index].mesh === mesh) {
  31754. this._LODLevels.splice(index, 1);
  31755. if (mesh) {
  31756. mesh._masterMesh = null;
  31757. }
  31758. }
  31759. }
  31760. this._sortLODLevels();
  31761. return this;
  31762. };
  31763. /**
  31764. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31765. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31766. */
  31767. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31768. if (!this._LODLevels || this._LODLevels.length === 0) {
  31769. return this;
  31770. }
  31771. var bSphere;
  31772. if (boundingSphere) {
  31773. bSphere = boundingSphere;
  31774. }
  31775. else {
  31776. var boundingInfo = this.getBoundingInfo();
  31777. bSphere = boundingInfo.boundingSphere;
  31778. }
  31779. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31780. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31781. if (this.onLODLevelSelection) {
  31782. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31783. }
  31784. return this;
  31785. }
  31786. for (var index = 0; index < this._LODLevels.length; index++) {
  31787. var level = this._LODLevels[index];
  31788. if (level.distance < distanceToCamera) {
  31789. if (level.mesh) {
  31790. level.mesh._preActivate();
  31791. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31792. }
  31793. if (this.onLODLevelSelection) {
  31794. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31795. }
  31796. return level.mesh;
  31797. }
  31798. }
  31799. if (this.onLODLevelSelection) {
  31800. this.onLODLevelSelection(distanceToCamera, this, this);
  31801. }
  31802. return this;
  31803. };
  31804. Object.defineProperty(Mesh.prototype, "geometry", {
  31805. /**
  31806. * Returns the mesh internal Geometry object.
  31807. */
  31808. get: function () {
  31809. return this._geometry;
  31810. },
  31811. enumerable: true,
  31812. configurable: true
  31813. });
  31814. /**
  31815. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31816. */
  31817. Mesh.prototype.getTotalVertices = function () {
  31818. if (this._geometry === null || this._geometry === undefined) {
  31819. return 0;
  31820. }
  31821. return this._geometry.getTotalVertices();
  31822. };
  31823. /**
  31824. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31825. * 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.
  31826. * You can force the copy with forceCopy === true
  31827. * Returns null if the mesh has no geometry or no vertex buffer.
  31828. * Possible `kind` values :
  31829. * - BABYLON.VertexBuffer.PositionKind
  31830. * - BABYLON.VertexBuffer.UVKind
  31831. * - BABYLON.VertexBuffer.UV2Kind
  31832. * - BABYLON.VertexBuffer.UV3Kind
  31833. * - BABYLON.VertexBuffer.UV4Kind
  31834. * - BABYLON.VertexBuffer.UV5Kind
  31835. * - BABYLON.VertexBuffer.UV6Kind
  31836. * - BABYLON.VertexBuffer.ColorKind
  31837. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31838. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31839. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31840. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31841. */
  31842. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31843. if (!this._geometry) {
  31844. return null;
  31845. }
  31846. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31847. };
  31848. /**
  31849. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31850. * Returns `null` if the mesh has no geometry.
  31851. * Possible `kind` values :
  31852. * - BABYLON.VertexBuffer.PositionKind
  31853. * - BABYLON.VertexBuffer.UVKind
  31854. * - BABYLON.VertexBuffer.UV2Kind
  31855. * - BABYLON.VertexBuffer.UV3Kind
  31856. * - BABYLON.VertexBuffer.UV4Kind
  31857. * - BABYLON.VertexBuffer.UV5Kind
  31858. * - BABYLON.VertexBuffer.UV6Kind
  31859. * - BABYLON.VertexBuffer.ColorKind
  31860. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31861. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31862. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31863. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31864. */
  31865. Mesh.prototype.getVertexBuffer = function (kind) {
  31866. if (!this._geometry) {
  31867. return null;
  31868. }
  31869. return this._geometry.getVertexBuffer(kind);
  31870. };
  31871. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31872. if (!this._geometry) {
  31873. if (this._delayInfo) {
  31874. return this._delayInfo.indexOf(kind) !== -1;
  31875. }
  31876. return false;
  31877. }
  31878. return this._geometry.isVerticesDataPresent(kind);
  31879. };
  31880. /**
  31881. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31882. * Possible `kind` values :
  31883. * - BABYLON.VertexBuffer.PositionKind
  31884. * - BABYLON.VertexBuffer.UVKind
  31885. * - BABYLON.VertexBuffer.UV2Kind
  31886. * - BABYLON.VertexBuffer.UV3Kind
  31887. * - BABYLON.VertexBuffer.UV4Kind
  31888. * - BABYLON.VertexBuffer.UV5Kind
  31889. * - BABYLON.VertexBuffer.UV6Kind
  31890. * - BABYLON.VertexBuffer.ColorKind
  31891. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31892. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31893. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31894. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31895. */
  31896. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31897. if (!this._geometry) {
  31898. if (this._delayInfo) {
  31899. return this._delayInfo.indexOf(kind) !== -1;
  31900. }
  31901. return false;
  31902. }
  31903. return this._geometry.isVertexBufferUpdatable(kind);
  31904. };
  31905. /**
  31906. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31907. * Possible `kind` values :
  31908. * - BABYLON.VertexBuffer.PositionKind
  31909. * - BABYLON.VertexBuffer.UVKind
  31910. * - BABYLON.VertexBuffer.UV2Kind
  31911. * - BABYLON.VertexBuffer.UV3Kind
  31912. * - BABYLON.VertexBuffer.UV4Kind
  31913. * - BABYLON.VertexBuffer.UV5Kind
  31914. * - BABYLON.VertexBuffer.UV6Kind
  31915. * - BABYLON.VertexBuffer.ColorKind
  31916. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31917. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31918. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31919. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31920. */
  31921. Mesh.prototype.getVerticesDataKinds = function () {
  31922. if (!this._geometry) {
  31923. var result = new Array();
  31924. if (this._delayInfo) {
  31925. this._delayInfo.forEach(function (kind, index, array) {
  31926. result.push(kind);
  31927. });
  31928. }
  31929. return result;
  31930. }
  31931. return this._geometry.getVerticesDataKinds();
  31932. };
  31933. /**
  31934. * Returns a positive integer : the total number of indices in this mesh geometry.
  31935. * Returns zero if the mesh has no geometry.
  31936. */
  31937. Mesh.prototype.getTotalIndices = function () {
  31938. if (!this._geometry) {
  31939. return 0;
  31940. }
  31941. return this._geometry.getTotalIndices();
  31942. };
  31943. /**
  31944. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31945. * 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.
  31946. * Returns an empty array if the mesh has no geometry.
  31947. */
  31948. Mesh.prototype.getIndices = function (copyWhenShared) {
  31949. if (!this._geometry) {
  31950. return [];
  31951. }
  31952. return this._geometry.getIndices(copyWhenShared);
  31953. };
  31954. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31955. get: function () {
  31956. return this._masterMesh !== null && this._masterMesh !== undefined;
  31957. },
  31958. enumerable: true,
  31959. configurable: true
  31960. });
  31961. /**
  31962. * Determine if the current mesh is ready to be rendered
  31963. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31964. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31965. * @returns true if all associated assets are ready (material, textures, shaders)
  31966. */
  31967. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31968. if (completeCheck === void 0) { completeCheck = false; }
  31969. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31970. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31971. return false;
  31972. }
  31973. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31974. return false;
  31975. }
  31976. if (!this.subMeshes || this.subMeshes.length === 0) {
  31977. return true;
  31978. }
  31979. if (!completeCheck) {
  31980. return true;
  31981. }
  31982. var engine = this.getEngine();
  31983. var scene = this.getScene();
  31984. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31985. this.computeWorldMatrix();
  31986. var mat = this.material || scene.defaultMaterial;
  31987. if (mat) {
  31988. if (mat.storeEffectOnSubMeshes) {
  31989. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31990. var subMesh = _a[_i];
  31991. var effectiveMaterial = subMesh.getMaterial();
  31992. if (effectiveMaterial) {
  31993. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31994. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31995. return false;
  31996. }
  31997. }
  31998. else {
  31999. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32000. return false;
  32001. }
  32002. }
  32003. }
  32004. }
  32005. }
  32006. else {
  32007. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32008. return false;
  32009. }
  32010. }
  32011. }
  32012. // Shadows
  32013. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32014. var light = _c[_b];
  32015. var generator = light.getShadowGenerator();
  32016. if (generator) {
  32017. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32018. var subMesh = _e[_d];
  32019. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32020. return false;
  32021. }
  32022. }
  32023. }
  32024. }
  32025. // LOD
  32026. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32027. var lod = _g[_f];
  32028. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32029. return false;
  32030. }
  32031. }
  32032. return true;
  32033. };
  32034. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32035. /**
  32036. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  32037. * This property is pertinent only for updatable parametric shapes.
  32038. */
  32039. get: function () {
  32040. return this._areNormalsFrozen;
  32041. },
  32042. enumerable: true,
  32043. configurable: true
  32044. });
  32045. /**
  32046. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32047. * It has no effect at all on other shapes.
  32048. * It prevents the mesh normals from being recomputed on next `positions` array update.
  32049. * Returns the Mesh.
  32050. */
  32051. Mesh.prototype.freezeNormals = function () {
  32052. this._areNormalsFrozen = true;
  32053. return this;
  32054. };
  32055. /**
  32056. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32057. * It has no effect at all on other shapes.
  32058. * It reactivates the mesh normals computation if it was previously frozen.
  32059. * Returns the Mesh.
  32060. */
  32061. Mesh.prototype.unfreezeNormals = function () {
  32062. this._areNormalsFrozen = false;
  32063. return this;
  32064. };
  32065. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32066. /**
  32067. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32068. */
  32069. set: function (count) {
  32070. this._overridenInstanceCount = count;
  32071. },
  32072. enumerable: true,
  32073. configurable: true
  32074. });
  32075. // Methods
  32076. Mesh.prototype._preActivate = function () {
  32077. var sceneRenderId = this.getScene().getRenderId();
  32078. if (this._preActivateId === sceneRenderId) {
  32079. return this;
  32080. }
  32081. this._preActivateId = sceneRenderId;
  32082. this._visibleInstances = null;
  32083. return this;
  32084. };
  32085. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32086. if (this._visibleInstances) {
  32087. this._visibleInstances.intermediateDefaultRenderId = renderId;
  32088. }
  32089. return this;
  32090. };
  32091. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32092. if (!this._visibleInstances) {
  32093. this._visibleInstances = {};
  32094. this._visibleInstances.defaultRenderId = renderId;
  32095. this._visibleInstances.selfDefaultRenderId = this._renderId;
  32096. }
  32097. if (!this._visibleInstances[renderId]) {
  32098. this._visibleInstances[renderId] = new Array();
  32099. }
  32100. this._visibleInstances[renderId].push(instance);
  32101. return this;
  32102. };
  32103. /**
  32104. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32105. * This means the mesh underlying bounding box and sphere are recomputed.
  32106. * Returns the Mesh.
  32107. */
  32108. Mesh.prototype.refreshBoundingInfo = function () {
  32109. return this._refreshBoundingInfo(false);
  32110. };
  32111. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32112. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32113. return this;
  32114. }
  32115. var data = this._getPositionData(applySkeleton);
  32116. if (data) {
  32117. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32118. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32119. }
  32120. if (this.subMeshes) {
  32121. for (var index = 0; index < this.subMeshes.length; index++) {
  32122. this.subMeshes[index].refreshBoundingInfo();
  32123. }
  32124. }
  32125. this._updateBoundingInfo();
  32126. return this;
  32127. };
  32128. Mesh.prototype._getPositionData = function (applySkeleton) {
  32129. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32130. if (data && applySkeleton && this.skeleton) {
  32131. data = BABYLON.Tools.Slice(data);
  32132. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32133. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32134. if (matricesWeightsData && matricesIndicesData) {
  32135. var needExtras = this.numBoneInfluencers > 4;
  32136. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32137. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32138. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32139. var tempVector = BABYLON.Tmp.Vector3[0];
  32140. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32141. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32142. var matWeightIdx = 0;
  32143. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32144. finalMatrix.reset();
  32145. var inf;
  32146. var weight;
  32147. for (inf = 0; inf < 4; inf++) {
  32148. weight = matricesWeightsData[matWeightIdx + inf];
  32149. if (weight <= 0)
  32150. break;
  32151. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32152. finalMatrix.addToSelf(tempMatrix);
  32153. }
  32154. if (needExtras) {
  32155. for (inf = 0; inf < 4; inf++) {
  32156. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32157. if (weight <= 0)
  32158. break;
  32159. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32160. finalMatrix.addToSelf(tempMatrix);
  32161. }
  32162. }
  32163. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32164. tempVector.toArray(data, index);
  32165. }
  32166. }
  32167. }
  32168. return data;
  32169. };
  32170. Mesh.prototype._createGlobalSubMesh = function (force) {
  32171. var totalVertices = this.getTotalVertices();
  32172. if (!totalVertices || !this.getIndices()) {
  32173. return null;
  32174. }
  32175. // Check if we need to recreate the submeshes
  32176. if (this.subMeshes && this.subMeshes.length > 0) {
  32177. var ib = this.getIndices();
  32178. if (!ib) {
  32179. return null;
  32180. }
  32181. var totalIndices = ib.length;
  32182. var needToRecreate = false;
  32183. if (force) {
  32184. needToRecreate = true;
  32185. }
  32186. else {
  32187. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32188. var submesh = _a[_i];
  32189. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32190. needToRecreate = true;
  32191. break;
  32192. }
  32193. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32194. needToRecreate = true;
  32195. break;
  32196. }
  32197. }
  32198. }
  32199. if (!needToRecreate) {
  32200. return this.subMeshes[0];
  32201. }
  32202. }
  32203. this.releaseSubMeshes();
  32204. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32205. };
  32206. Mesh.prototype.subdivide = function (count) {
  32207. if (count < 1) {
  32208. return;
  32209. }
  32210. var totalIndices = this.getTotalIndices();
  32211. var subdivisionSize = (totalIndices / count) | 0;
  32212. var offset = 0;
  32213. // Ensure that subdivisionSize is a multiple of 3
  32214. while (subdivisionSize % 3 !== 0) {
  32215. subdivisionSize++;
  32216. }
  32217. this.releaseSubMeshes();
  32218. for (var index = 0; index < count; index++) {
  32219. if (offset >= totalIndices) {
  32220. break;
  32221. }
  32222. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32223. offset += subdivisionSize;
  32224. }
  32225. this.synchronizeInstances();
  32226. };
  32227. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32228. if (updatable === void 0) { updatable = false; }
  32229. if (!this._geometry) {
  32230. var vertexData = new BABYLON.VertexData();
  32231. vertexData.set(data, kind);
  32232. var scene = this.getScene();
  32233. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32234. }
  32235. else {
  32236. this._geometry.setVerticesData(kind, data, updatable, stride);
  32237. }
  32238. return this;
  32239. };
  32240. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32241. if (updatable === void 0) { updatable = true; }
  32242. var vb = this.getVertexBuffer(kind);
  32243. if (!vb || vb.isUpdatable() === updatable) {
  32244. return;
  32245. }
  32246. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32247. };
  32248. /**
  32249. * Sets the mesh VertexBuffer.
  32250. * Returns the Mesh.
  32251. */
  32252. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32253. if (!this._geometry) {
  32254. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32255. }
  32256. this._geometry.setVerticesBuffer(buffer);
  32257. return this;
  32258. };
  32259. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32260. if (!this._geometry) {
  32261. return this;
  32262. }
  32263. if (!makeItUnique) {
  32264. this._geometry.updateVerticesData(kind, data, updateExtends);
  32265. }
  32266. else {
  32267. this.makeGeometryUnique();
  32268. this.updateVerticesData(kind, data, updateExtends, false);
  32269. }
  32270. return this;
  32271. };
  32272. /**
  32273. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32274. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32275. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32276. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32277. * Returns the Mesh.
  32278. */
  32279. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32280. if (computeNormals === void 0) { computeNormals = true; }
  32281. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32282. if (!positions) {
  32283. return this;
  32284. }
  32285. positionFunction(positions);
  32286. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32287. if (computeNormals) {
  32288. var indices = this.getIndices();
  32289. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32290. if (!normals) {
  32291. return this;
  32292. }
  32293. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32294. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32295. }
  32296. return this;
  32297. };
  32298. /**
  32299. * Creates a un-shared specific occurence of the geometry for the mesh.
  32300. * Returns the Mesh.
  32301. */
  32302. Mesh.prototype.makeGeometryUnique = function () {
  32303. if (!this._geometry) {
  32304. return this;
  32305. }
  32306. var oldGeometry = this._geometry;
  32307. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32308. oldGeometry.releaseForMesh(this, true);
  32309. geometry.applyToMesh(this);
  32310. return this;
  32311. };
  32312. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32313. if (totalVertices === void 0) { totalVertices = null; }
  32314. if (updatable === void 0) { updatable = false; }
  32315. if (!this._geometry) {
  32316. var vertexData = new BABYLON.VertexData();
  32317. vertexData.indices = indices;
  32318. var scene = this.getScene();
  32319. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32320. }
  32321. else {
  32322. this._geometry.setIndices(indices, totalVertices, updatable);
  32323. }
  32324. return this;
  32325. };
  32326. /**
  32327. * Update the current index buffer
  32328. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32329. * Returns the Mesh.
  32330. */
  32331. Mesh.prototype.updateIndices = function (indices, offset) {
  32332. if (!this._geometry) {
  32333. return this;
  32334. }
  32335. this._geometry.updateIndices(indices, offset);
  32336. return this;
  32337. };
  32338. /**
  32339. * Invert the geometry to move from a right handed system to a left handed one.
  32340. * Returns the Mesh.
  32341. */
  32342. Mesh.prototype.toLeftHanded = function () {
  32343. if (!this._geometry) {
  32344. return this;
  32345. }
  32346. this._geometry.toLeftHanded();
  32347. return this;
  32348. };
  32349. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32350. if (!this._geometry) {
  32351. return this;
  32352. }
  32353. var engine = this.getScene().getEngine();
  32354. // Wireframe
  32355. var indexToBind;
  32356. if (this._unIndexed) {
  32357. indexToBind = null;
  32358. }
  32359. else {
  32360. switch (fillMode) {
  32361. case BABYLON.Material.PointFillMode:
  32362. indexToBind = null;
  32363. break;
  32364. case BABYLON.Material.WireFrameFillMode:
  32365. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32366. break;
  32367. default:
  32368. case BABYLON.Material.TriangleFillMode:
  32369. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32370. break;
  32371. }
  32372. }
  32373. // VBOs
  32374. this._geometry._bind(effect, indexToBind);
  32375. return this;
  32376. };
  32377. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32378. if (alternate === void 0) { alternate = false; }
  32379. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32380. return this;
  32381. }
  32382. this.onBeforeDrawObservable.notifyObservers(this);
  32383. var scene = this.getScene();
  32384. var engine = scene.getEngine();
  32385. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32386. // or triangles as points
  32387. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32388. }
  32389. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32390. // Triangles as wireframe
  32391. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32392. }
  32393. else {
  32394. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32395. }
  32396. if (scene._isAlternateRenderingEnabled && !alternate) {
  32397. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32398. if (!effect || !scene.activeCamera) {
  32399. return this;
  32400. }
  32401. scene._switchToAlternateCameraConfiguration(true);
  32402. this._effectiveMaterial.bindView(effect);
  32403. this._effectiveMaterial.bindViewProjection(effect);
  32404. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32405. this._draw(subMesh, fillMode, instancesCount, true);
  32406. engine.setViewport(scene.activeCamera.viewport);
  32407. scene._switchToAlternateCameraConfiguration(false);
  32408. this._effectiveMaterial.bindView(effect);
  32409. this._effectiveMaterial.bindViewProjection(effect);
  32410. }
  32411. return this;
  32412. };
  32413. /**
  32414. * Registers for this mesh a javascript function called just before the rendering process.
  32415. * This function is passed the current mesh.
  32416. * Return the Mesh.
  32417. */
  32418. Mesh.prototype.registerBeforeRender = function (func) {
  32419. this.onBeforeRenderObservable.add(func);
  32420. return this;
  32421. };
  32422. /**
  32423. * Disposes a previously registered javascript function called before the rendering.
  32424. * This function is passed the current mesh.
  32425. * Returns the Mesh.
  32426. */
  32427. Mesh.prototype.unregisterBeforeRender = function (func) {
  32428. this.onBeforeRenderObservable.removeCallback(func);
  32429. return this;
  32430. };
  32431. /**
  32432. * Registers for this mesh a javascript function called just after the rendering is complete.
  32433. * This function is passed the current mesh.
  32434. * Returns the Mesh.
  32435. */
  32436. Mesh.prototype.registerAfterRender = function (func) {
  32437. this.onAfterRenderObservable.add(func);
  32438. return this;
  32439. };
  32440. /**
  32441. * Disposes a previously registered javascript function called after the rendering.
  32442. * This function is passed the current mesh.
  32443. * Return the Mesh.
  32444. */
  32445. Mesh.prototype.unregisterAfterRender = function (func) {
  32446. this.onAfterRenderObservable.removeCallback(func);
  32447. return this;
  32448. };
  32449. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32450. var scene = this.getScene();
  32451. this._batchCache.mustReturn = false;
  32452. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32453. this._batchCache.visibleInstances[subMeshId] = null;
  32454. if (this._visibleInstances) {
  32455. var currentRenderId = scene.getRenderId();
  32456. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32457. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32458. var selfRenderId = this._renderId;
  32459. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32460. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32461. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32462. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32463. }
  32464. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32465. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32466. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32467. this._batchCache.mustReturn = true;
  32468. return this._batchCache;
  32469. }
  32470. if (currentRenderId !== selfRenderId) {
  32471. this._batchCache.renderSelf[subMeshId] = false;
  32472. }
  32473. }
  32474. this._renderIdForInstances[subMeshId] = currentRenderId;
  32475. }
  32476. return this._batchCache;
  32477. };
  32478. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32479. var visibleInstances = batch.visibleInstances[subMesh._id];
  32480. if (!visibleInstances) {
  32481. return this;
  32482. }
  32483. var matricesCount = visibleInstances.length + 1;
  32484. var bufferSize = matricesCount * 16 * 4;
  32485. var currentInstancesBufferSize = this._instancesBufferSize;
  32486. var instancesBuffer = this._instancesBuffer;
  32487. while (this._instancesBufferSize < bufferSize) {
  32488. this._instancesBufferSize *= 2;
  32489. }
  32490. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32491. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32492. }
  32493. var offset = 0;
  32494. var instancesCount = 0;
  32495. var world = this.getWorldMatrix();
  32496. if (batch.renderSelf[subMesh._id]) {
  32497. world.copyToArray(this._instancesData, offset);
  32498. offset += 16;
  32499. instancesCount++;
  32500. }
  32501. if (visibleInstances) {
  32502. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32503. var instance = visibleInstances[instanceIndex];
  32504. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32505. offset += 16;
  32506. instancesCount++;
  32507. }
  32508. }
  32509. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32510. if (instancesBuffer) {
  32511. instancesBuffer.dispose();
  32512. }
  32513. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32514. this._instancesBuffer = instancesBuffer;
  32515. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32516. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32517. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32518. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32519. }
  32520. else {
  32521. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32522. }
  32523. this._bind(subMesh, effect, fillMode);
  32524. this._draw(subMesh, fillMode, instancesCount);
  32525. engine.unbindInstanceAttributes();
  32526. return this;
  32527. };
  32528. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32529. var scene = this.getScene();
  32530. var engine = scene.getEngine();
  32531. if (hardwareInstancedRendering) {
  32532. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32533. }
  32534. else {
  32535. if (batch.renderSelf[subMesh._id]) {
  32536. // Draw
  32537. if (onBeforeDraw) {
  32538. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32539. }
  32540. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32541. }
  32542. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32543. if (visibleInstancesForSubMesh) {
  32544. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32545. var instance = visibleInstancesForSubMesh[instanceIndex];
  32546. // World
  32547. var world = instance.getWorldMatrix();
  32548. if (onBeforeDraw) {
  32549. onBeforeDraw(true, world, effectiveMaterial);
  32550. }
  32551. // Draw
  32552. this._draw(subMesh, fillMode);
  32553. }
  32554. }
  32555. }
  32556. return this;
  32557. };
  32558. /**
  32559. * Triggers the draw call for the mesh.
  32560. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32561. * Returns the Mesh.
  32562. */
  32563. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32564. this._checkOcclusionQuery();
  32565. if (this._isOccluded) {
  32566. return this;
  32567. }
  32568. var scene = this.getScene();
  32569. // Managing instances
  32570. var batch = this._getInstancesRenderList(subMesh._id);
  32571. if (batch.mustReturn) {
  32572. return this;
  32573. }
  32574. // Checking geometry state
  32575. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32576. return this;
  32577. }
  32578. this.onBeforeRenderObservable.notifyObservers(this);
  32579. var engine = scene.getEngine();
  32580. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32581. // Material
  32582. var material = subMesh.getMaterial();
  32583. if (!material) {
  32584. return this;
  32585. }
  32586. this._effectiveMaterial = material;
  32587. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32588. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32589. return this;
  32590. }
  32591. }
  32592. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32593. return this;
  32594. }
  32595. // Alpha mode
  32596. if (enableAlphaMode) {
  32597. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32598. }
  32599. // Outline - step 1
  32600. var savedDepthWrite = engine.getDepthWrite();
  32601. if (this.renderOutline) {
  32602. engine.setDepthWrite(false);
  32603. scene.getOutlineRenderer().render(subMesh, batch);
  32604. engine.setDepthWrite(savedDepthWrite);
  32605. }
  32606. var effect;
  32607. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32608. effect = subMesh.effect;
  32609. }
  32610. else {
  32611. effect = this._effectiveMaterial.getEffect();
  32612. }
  32613. if (!effect) {
  32614. return this;
  32615. }
  32616. var sideOrientation = this.overrideMaterialSideOrientation;
  32617. if (sideOrientation == null) {
  32618. sideOrientation = this._effectiveMaterial.sideOrientation;
  32619. if (this._getWorldMatrixDeterminant() < 0) {
  32620. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32621. }
  32622. }
  32623. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32624. if (this._effectiveMaterial.forceDepthWrite) {
  32625. engine.setDepthWrite(true);
  32626. }
  32627. // Bind
  32628. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32629. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32630. this._bind(subMesh, effect, fillMode);
  32631. }
  32632. var world = this.getWorldMatrix();
  32633. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32634. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32635. }
  32636. else {
  32637. this._effectiveMaterial.bind(world, this);
  32638. }
  32639. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32640. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32641. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32642. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32643. }
  32644. // Draw
  32645. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32646. // Unbind
  32647. this._effectiveMaterial.unbind();
  32648. // Outline - step 2
  32649. if (this.renderOutline && savedDepthWrite) {
  32650. engine.setDepthWrite(true);
  32651. engine.setColorWrite(false);
  32652. scene.getOutlineRenderer().render(subMesh, batch);
  32653. engine.setColorWrite(true);
  32654. }
  32655. // Overlay
  32656. if (this.renderOverlay) {
  32657. var currentMode = engine.getAlphaMode();
  32658. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32659. scene.getOutlineRenderer().render(subMesh, batch, true);
  32660. engine.setAlphaMode(currentMode);
  32661. }
  32662. this.onAfterRenderObservable.notifyObservers(this);
  32663. return this;
  32664. };
  32665. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32666. if (isInstance && effectiveMaterial) {
  32667. effectiveMaterial.bindOnlyWorldMatrix(world);
  32668. }
  32669. };
  32670. /**
  32671. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32672. */
  32673. Mesh.prototype.getEmittedParticleSystems = function () {
  32674. var results = new Array();
  32675. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32676. var particleSystem = this.getScene().particleSystems[index];
  32677. if (particleSystem.emitter === this) {
  32678. results.push(particleSystem);
  32679. }
  32680. }
  32681. return results;
  32682. };
  32683. /**
  32684. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32685. */
  32686. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32687. var results = new Array();
  32688. var descendants = this.getDescendants();
  32689. descendants.push(this);
  32690. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32691. var particleSystem = this.getScene().particleSystems[index];
  32692. var emitter = particleSystem.emitter;
  32693. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32694. results.push(particleSystem);
  32695. }
  32696. }
  32697. return results;
  32698. };
  32699. /**
  32700. * Normalize matrix weights so that all vertices have a total weight set to 1
  32701. */
  32702. Mesh.prototype.cleanMatrixWeights = function () {
  32703. var epsilon = 1e-3;
  32704. var noInfluenceBoneIndex = 0.0;
  32705. if (this.skeleton) {
  32706. noInfluenceBoneIndex = this.skeleton.bones.length;
  32707. }
  32708. else {
  32709. return;
  32710. }
  32711. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32712. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32713. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32714. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32715. var influencers = this.numBoneInfluencers;
  32716. var size = matricesWeights.length;
  32717. for (var i = 0; i < size; i += 4) {
  32718. var weight = 0.0;
  32719. var firstZeroWeight = -1;
  32720. for (var j = 0; j < 4; j++) {
  32721. var w = matricesWeights[i + j];
  32722. weight += w;
  32723. if (w < epsilon && firstZeroWeight < 0) {
  32724. firstZeroWeight = j;
  32725. }
  32726. }
  32727. if (matricesWeightsExtra) {
  32728. for (var j = 0; j < 4; j++) {
  32729. var w = matricesWeightsExtra[i + j];
  32730. weight += w;
  32731. if (w < epsilon && firstZeroWeight < 0) {
  32732. firstZeroWeight = j + 4;
  32733. }
  32734. }
  32735. }
  32736. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32737. firstZeroWeight = influencers - 1;
  32738. }
  32739. if (weight > epsilon) {
  32740. var mweight = 1.0 / weight;
  32741. for (var j = 0; j < 4; j++) {
  32742. matricesWeights[i + j] *= mweight;
  32743. }
  32744. if (matricesWeightsExtra) {
  32745. for (var j = 0; j < 4; j++) {
  32746. matricesWeightsExtra[i + j] *= mweight;
  32747. }
  32748. }
  32749. }
  32750. else {
  32751. if (firstZeroWeight >= 4) {
  32752. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32753. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32754. }
  32755. else {
  32756. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32757. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32758. }
  32759. }
  32760. }
  32761. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32762. if (matricesIndicesExtra) {
  32763. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32764. }
  32765. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32766. if (matricesWeightsExtra) {
  32767. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32768. }
  32769. };
  32770. Mesh.prototype._checkDelayState = function () {
  32771. var scene = this.getScene();
  32772. if (this._geometry) {
  32773. this._geometry.load(scene);
  32774. }
  32775. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32776. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32777. this._queueLoad(scene);
  32778. }
  32779. return this;
  32780. };
  32781. Mesh.prototype._queueLoad = function (scene) {
  32782. var _this = this;
  32783. scene._addPendingData(this);
  32784. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32785. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32786. if (data instanceof ArrayBuffer) {
  32787. _this._delayLoadingFunction(data, _this);
  32788. }
  32789. else {
  32790. _this._delayLoadingFunction(JSON.parse(data), _this);
  32791. }
  32792. _this.instances.forEach(function (instance) {
  32793. instance._syncSubMeshes();
  32794. });
  32795. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32796. scene._removePendingData(_this);
  32797. }, function () { }, scene.database, getBinaryData);
  32798. return this;
  32799. };
  32800. /**
  32801. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32802. */
  32803. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32804. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32805. return false;
  32806. }
  32807. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32808. return false;
  32809. }
  32810. this._checkDelayState();
  32811. return true;
  32812. };
  32813. /**
  32814. * Sets the mesh material by the material or multiMaterial `id` property.
  32815. * The material `id` is a string identifying the material or the multiMaterial.
  32816. * This method returns the Mesh.
  32817. */
  32818. Mesh.prototype.setMaterialByID = function (id) {
  32819. var materials = this.getScene().materials;
  32820. var index;
  32821. for (index = materials.length - 1; index > -1; index--) {
  32822. if (materials[index].id === id) {
  32823. this.material = materials[index];
  32824. return this;
  32825. }
  32826. }
  32827. // Multi
  32828. var multiMaterials = this.getScene().multiMaterials;
  32829. for (index = multiMaterials.length - 1; index > -1; index--) {
  32830. if (multiMaterials[index].id === id) {
  32831. this.material = multiMaterials[index];
  32832. return this;
  32833. }
  32834. }
  32835. return this;
  32836. };
  32837. /**
  32838. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32839. */
  32840. Mesh.prototype.getAnimatables = function () {
  32841. var results = new Array();
  32842. if (this.material) {
  32843. results.push(this.material);
  32844. }
  32845. if (this.skeleton) {
  32846. results.push(this.skeleton);
  32847. }
  32848. return results;
  32849. };
  32850. /**
  32851. * Modifies the mesh geometry according to the passed transformation matrix.
  32852. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32853. * The mesh normals are modified accordingly the same transformation.
  32854. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32855. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32856. * Returns the Mesh.
  32857. */
  32858. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32859. // Position
  32860. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32861. return this;
  32862. }
  32863. var submeshes = this.subMeshes.splice(0);
  32864. this._resetPointsArrayCache();
  32865. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32866. var temp = new Array();
  32867. var index;
  32868. for (index = 0; index < data.length; index += 3) {
  32869. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32870. }
  32871. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32872. // Normals
  32873. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32874. return this;
  32875. }
  32876. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32877. temp = [];
  32878. for (index = 0; index < data.length; index += 3) {
  32879. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32880. }
  32881. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32882. // flip faces?
  32883. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32884. this.flipFaces();
  32885. }
  32886. // Restore submeshes
  32887. this.releaseSubMeshes();
  32888. this.subMeshes = submeshes;
  32889. return this;
  32890. };
  32891. /**
  32892. * Modifies the mesh geometry according to its own current World Matrix.
  32893. * The mesh World Matrix is then reset.
  32894. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32895. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32896. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32897. * Returns the Mesh.
  32898. */
  32899. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32900. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32901. this.scaling.copyFromFloats(1, 1, 1);
  32902. this.position.copyFromFloats(0, 0, 0);
  32903. this.rotation.copyFromFloats(0, 0, 0);
  32904. //only if quaternion is already set
  32905. if (this.rotationQuaternion) {
  32906. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32907. }
  32908. this._worldMatrix = BABYLON.Matrix.Identity();
  32909. return this;
  32910. };
  32911. Object.defineProperty(Mesh.prototype, "_positions", {
  32912. // Cache
  32913. get: function () {
  32914. if (this._geometry) {
  32915. return this._geometry._positions;
  32916. }
  32917. return null;
  32918. },
  32919. enumerable: true,
  32920. configurable: true
  32921. });
  32922. Mesh.prototype._resetPointsArrayCache = function () {
  32923. if (this._geometry) {
  32924. this._geometry._resetPointsArrayCache();
  32925. }
  32926. return this;
  32927. };
  32928. Mesh.prototype._generatePointsArray = function () {
  32929. if (this._geometry) {
  32930. return this._geometry._generatePointsArray();
  32931. }
  32932. return false;
  32933. };
  32934. /**
  32935. * Returns a new Mesh object generated from the current mesh properties.
  32936. * This method must not get confused with createInstance().
  32937. * The parameter `name` is a string, the name given to the new mesh.
  32938. * The optional parameter `newParent` can be any Node object (default `null`).
  32939. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32940. * 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.
  32941. */
  32942. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32943. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32944. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32945. };
  32946. /**
  32947. * Releases resources associated with this mesh.
  32948. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32949. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32950. */
  32951. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32952. var _this = this;
  32953. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32954. this.morphTargetManager = null;
  32955. if (this._geometry) {
  32956. this._geometry.releaseForMesh(this, true);
  32957. }
  32958. // Sources
  32959. var meshes = this.getScene().meshes;
  32960. meshes.forEach(function (abstractMesh) {
  32961. var mesh = abstractMesh;
  32962. if (mesh._source && mesh._source === _this) {
  32963. mesh._source = null;
  32964. }
  32965. });
  32966. this._source = null;
  32967. // Instances
  32968. if (this._instancesBuffer) {
  32969. this._instancesBuffer.dispose();
  32970. this._instancesBuffer = null;
  32971. }
  32972. while (this.instances.length) {
  32973. this.instances[0].dispose();
  32974. }
  32975. // Effect layers.
  32976. var effectLayers = this.getScene().effectLayers;
  32977. for (var i = 0; i < effectLayers.length; i++) {
  32978. var effectLayer = effectLayers[i];
  32979. if (effectLayer) {
  32980. effectLayer._disposeMesh(this);
  32981. }
  32982. }
  32983. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32984. };
  32985. /**
  32986. * Modifies the mesh geometry according to a displacement map.
  32987. * 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.
  32988. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32989. * This method returns nothing.
  32990. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32991. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32992. * 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.
  32993. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32994. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32995. *
  32996. * Returns the Mesh.
  32997. */
  32998. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32999. var _this = this;
  33000. var scene = this.getScene();
  33001. var onload = function (img) {
  33002. // Getting height map data
  33003. var canvas = document.createElement("canvas");
  33004. var context = canvas.getContext("2d");
  33005. var heightMapWidth = img.width;
  33006. var heightMapHeight = img.height;
  33007. canvas.width = heightMapWidth;
  33008. canvas.height = heightMapHeight;
  33009. context.drawImage(img, 0, 0);
  33010. // Create VertexData from map data
  33011. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33012. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33013. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  33014. //execute success callback, if set
  33015. if (onSuccess) {
  33016. onSuccess(_this);
  33017. }
  33018. };
  33019. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33020. return this;
  33021. };
  33022. /**
  33023. * Modifies the mesh geometry according to a displacementMap buffer.
  33024. * 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.
  33025. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33026. * This method returns nothing.
  33027. * 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.
  33028. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  33029. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33030. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33031. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33032. *
  33033. * Returns the Mesh.
  33034. */
  33035. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  33036. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33037. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33038. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33039. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33040. return this;
  33041. }
  33042. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33043. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33044. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33045. var position = BABYLON.Vector3.Zero();
  33046. var normal = BABYLON.Vector3.Zero();
  33047. var uv = BABYLON.Vector2.Zero();
  33048. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33049. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33050. for (var index = 0; index < positions.length; index += 3) {
  33051. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33052. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33053. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33054. // Compute height
  33055. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33056. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33057. var pos = (u + v * heightMapWidth) * 4;
  33058. var r = buffer[pos] / 255.0;
  33059. var g = buffer[pos + 1] / 255.0;
  33060. var b = buffer[pos + 2] / 255.0;
  33061. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33062. normal.normalize();
  33063. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33064. position = position.add(normal);
  33065. position.toArray(positions, index);
  33066. }
  33067. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33068. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33069. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33070. return this;
  33071. };
  33072. /**
  33073. * Modify the mesh to get a flat shading rendering.
  33074. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33075. * This method returns the Mesh.
  33076. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33077. */
  33078. Mesh.prototype.convertToFlatShadedMesh = function () {
  33079. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  33080. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33081. var kinds = this.getVerticesDataKinds();
  33082. var vbs = {};
  33083. var data = {};
  33084. var newdata = {};
  33085. var updatableNormals = false;
  33086. var kindIndex;
  33087. var kind;
  33088. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33089. kind = kinds[kindIndex];
  33090. var vertexBuffer = this.getVertexBuffer(kind);
  33091. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33092. updatableNormals = vertexBuffer.isUpdatable();
  33093. kinds.splice(kindIndex, 1);
  33094. kindIndex--;
  33095. continue;
  33096. }
  33097. vbs[kind] = vertexBuffer;
  33098. data[kind] = vbs[kind].getData();
  33099. newdata[kind] = [];
  33100. }
  33101. // Save previous submeshes
  33102. var previousSubmeshes = this.subMeshes.slice(0);
  33103. var indices = this.getIndices();
  33104. var totalIndices = this.getTotalIndices();
  33105. // Generating unique vertices per face
  33106. var index;
  33107. for (index = 0; index < totalIndices; index++) {
  33108. var vertexIndex = indices[index];
  33109. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33110. kind = kinds[kindIndex];
  33111. var stride = vbs[kind].getStrideSize();
  33112. for (var offset = 0; offset < stride; offset++) {
  33113. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33114. }
  33115. }
  33116. }
  33117. // Updating faces & normal
  33118. var normals = [];
  33119. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33120. for (index = 0; index < totalIndices; index += 3) {
  33121. indices[index] = index;
  33122. indices[index + 1] = index + 1;
  33123. indices[index + 2] = index + 2;
  33124. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33125. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33126. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33127. var p1p2 = p1.subtract(p2);
  33128. var p3p2 = p3.subtract(p2);
  33129. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33130. // Store same normals for every vertex
  33131. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33132. normals.push(normal.x);
  33133. normals.push(normal.y);
  33134. normals.push(normal.z);
  33135. }
  33136. }
  33137. this.setIndices(indices);
  33138. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33139. // Updating vertex buffers
  33140. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33141. kind = kinds[kindIndex];
  33142. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33143. }
  33144. // Updating submeshes
  33145. this.releaseSubMeshes();
  33146. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33147. var previousOne = previousSubmeshes[submeshIndex];
  33148. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33149. }
  33150. this.synchronizeInstances();
  33151. return this;
  33152. };
  33153. /**
  33154. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33155. * In other words, more vertices, no more indices and a single bigger VBO.
  33156. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33157. * Returns the Mesh.
  33158. */
  33159. Mesh.prototype.convertToUnIndexedMesh = function () {
  33160. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33161. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33162. var kinds = this.getVerticesDataKinds();
  33163. var vbs = {};
  33164. var data = {};
  33165. var newdata = {};
  33166. var kindIndex;
  33167. var kind;
  33168. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33169. kind = kinds[kindIndex];
  33170. var vertexBuffer = this.getVertexBuffer(kind);
  33171. vbs[kind] = vertexBuffer;
  33172. data[kind] = vbs[kind].getData();
  33173. newdata[kind] = [];
  33174. }
  33175. // Save previous submeshes
  33176. var previousSubmeshes = this.subMeshes.slice(0);
  33177. var indices = this.getIndices();
  33178. var totalIndices = this.getTotalIndices();
  33179. // Generating unique vertices per face
  33180. var index;
  33181. for (index = 0; index < totalIndices; index++) {
  33182. var vertexIndex = indices[index];
  33183. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33184. kind = kinds[kindIndex];
  33185. var stride = vbs[kind].getStrideSize();
  33186. for (var offset = 0; offset < stride; offset++) {
  33187. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33188. }
  33189. }
  33190. }
  33191. // Updating indices
  33192. for (index = 0; index < totalIndices; index += 3) {
  33193. indices[index] = index;
  33194. indices[index + 1] = index + 1;
  33195. indices[index + 2] = index + 2;
  33196. }
  33197. this.setIndices(indices);
  33198. // Updating vertex buffers
  33199. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33200. kind = kinds[kindIndex];
  33201. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33202. }
  33203. // Updating submeshes
  33204. this.releaseSubMeshes();
  33205. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33206. var previousOne = previousSubmeshes[submeshIndex];
  33207. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33208. }
  33209. this._unIndexed = true;
  33210. this.synchronizeInstances();
  33211. return this;
  33212. };
  33213. /**
  33214. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33215. * This method returns the Mesh.
  33216. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33217. */
  33218. Mesh.prototype.flipFaces = function (flipNormals) {
  33219. if (flipNormals === void 0) { flipNormals = false; }
  33220. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33221. var i;
  33222. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33223. for (i = 0; i < vertex_data.normals.length; i++) {
  33224. vertex_data.normals[i] *= -1;
  33225. }
  33226. }
  33227. if (vertex_data.indices) {
  33228. var temp;
  33229. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33230. // reassign indices
  33231. temp = vertex_data.indices[i + 1];
  33232. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33233. vertex_data.indices[i + 2] = temp;
  33234. }
  33235. }
  33236. vertex_data.applyToMesh(this);
  33237. return this;
  33238. };
  33239. // Instances
  33240. /**
  33241. * Creates a new InstancedMesh object from the mesh model.
  33242. * An instance shares the same properties and the same material than its model.
  33243. * Only these properties of each instance can then be set individually :
  33244. * - position
  33245. * - rotation
  33246. * - rotationQuaternion
  33247. * - setPivotMatrix
  33248. * - scaling
  33249. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33250. * Warning : this method is not supported for Line mesh and LineSystem
  33251. */
  33252. Mesh.prototype.createInstance = function (name) {
  33253. return new BABYLON.InstancedMesh(name, this);
  33254. };
  33255. /**
  33256. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33257. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33258. * This method returns the Mesh.
  33259. */
  33260. Mesh.prototype.synchronizeInstances = function () {
  33261. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33262. var instance = this.instances[instanceIndex];
  33263. instance._syncSubMeshes();
  33264. }
  33265. return this;
  33266. };
  33267. /**
  33268. * Simplify the mesh according to the given array of settings.
  33269. * Function will return immediately and will simplify async. It returns the Mesh.
  33270. * @param settings a collection of simplification settings.
  33271. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33272. * @param type the type of simplification to run.
  33273. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33274. */
  33275. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33276. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33277. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33278. this.getScene().simplificationQueue.addTask({
  33279. settings: settings,
  33280. parallelProcessing: parallelProcessing,
  33281. mesh: this,
  33282. simplificationType: simplificationType,
  33283. successCallback: successCallback
  33284. });
  33285. return this;
  33286. };
  33287. /**
  33288. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33289. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33290. * This should be used together with the simplification to avoid disappearing triangles.
  33291. * Returns the Mesh.
  33292. * @param successCallback an optional success callback to be called after the optimization finished.
  33293. */
  33294. Mesh.prototype.optimizeIndices = function (successCallback) {
  33295. var _this = this;
  33296. var indices = this.getIndices();
  33297. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33298. if (!positions || !indices) {
  33299. return this;
  33300. }
  33301. var vectorPositions = new Array();
  33302. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33303. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33304. }
  33305. var dupes = new Array();
  33306. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33307. var realPos = vectorPositions.length - 1 - iteration;
  33308. var testedPosition = vectorPositions[realPos];
  33309. for (var j = 0; j < realPos; ++j) {
  33310. var againstPosition = vectorPositions[j];
  33311. if (testedPosition.equals(againstPosition)) {
  33312. dupes[realPos] = j;
  33313. break;
  33314. }
  33315. }
  33316. }, function () {
  33317. for (var i = 0; i < indices.length; ++i) {
  33318. indices[i] = dupes[indices[i]] || indices[i];
  33319. }
  33320. //indices are now reordered
  33321. var originalSubMeshes = _this.subMeshes.slice(0);
  33322. _this.setIndices(indices);
  33323. _this.subMeshes = originalSubMeshes;
  33324. if (successCallback) {
  33325. successCallback(_this);
  33326. }
  33327. });
  33328. return this;
  33329. };
  33330. Mesh.prototype.serialize = function (serializationObject) {
  33331. serializationObject.name = this.name;
  33332. serializationObject.id = this.id;
  33333. serializationObject.type = this.getClassName();
  33334. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33335. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33336. }
  33337. serializationObject.position = this.position.asArray();
  33338. if (this.rotationQuaternion) {
  33339. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33340. }
  33341. else if (this.rotation) {
  33342. serializationObject.rotation = this.rotation.asArray();
  33343. }
  33344. serializationObject.scaling = this.scaling.asArray();
  33345. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33346. serializationObject.isEnabled = this.isEnabled(false);
  33347. serializationObject.isVisible = this.isVisible;
  33348. serializationObject.infiniteDistance = this.infiniteDistance;
  33349. serializationObject.pickable = this.isPickable;
  33350. serializationObject.receiveShadows = this.receiveShadows;
  33351. serializationObject.billboardMode = this.billboardMode;
  33352. serializationObject.visibility = this.visibility;
  33353. serializationObject.checkCollisions = this.checkCollisions;
  33354. serializationObject.isBlocker = this.isBlocker;
  33355. // Parent
  33356. if (this.parent) {
  33357. serializationObject.parentId = this.parent.id;
  33358. }
  33359. // Geometry
  33360. serializationObject.isUnIndexed = this.isUnIndexed;
  33361. var geometry = this._geometry;
  33362. if (geometry) {
  33363. var geometryId = geometry.id;
  33364. serializationObject.geometryId = geometryId;
  33365. // SubMeshes
  33366. serializationObject.subMeshes = [];
  33367. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33368. var subMesh = this.subMeshes[subIndex];
  33369. serializationObject.subMeshes.push({
  33370. materialIndex: subMesh.materialIndex,
  33371. verticesStart: subMesh.verticesStart,
  33372. verticesCount: subMesh.verticesCount,
  33373. indexStart: subMesh.indexStart,
  33374. indexCount: subMesh.indexCount
  33375. });
  33376. }
  33377. }
  33378. // Material
  33379. if (this.material) {
  33380. serializationObject.materialId = this.material.id;
  33381. }
  33382. else {
  33383. this.material = null;
  33384. }
  33385. // Morph targets
  33386. if (this.morphTargetManager) {
  33387. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33388. }
  33389. // Skeleton
  33390. if (this.skeleton) {
  33391. serializationObject.skeletonId = this.skeleton.id;
  33392. }
  33393. // Physics
  33394. //TODO implement correct serialization for physics impostors.
  33395. var impostor = this.getPhysicsImpostor();
  33396. if (impostor) {
  33397. serializationObject.physicsMass = impostor.getParam("mass");
  33398. serializationObject.physicsFriction = impostor.getParam("friction");
  33399. serializationObject.physicsRestitution = impostor.getParam("mass");
  33400. serializationObject.physicsImpostor = impostor.type;
  33401. }
  33402. // Metadata
  33403. if (this.metadata) {
  33404. serializationObject.metadata = this.metadata;
  33405. }
  33406. // Instances
  33407. serializationObject.instances = [];
  33408. for (var index = 0; index < this.instances.length; index++) {
  33409. var instance = this.instances[index];
  33410. var serializationInstance = {
  33411. name: instance.name,
  33412. id: instance.id,
  33413. position: instance.position.asArray(),
  33414. scaling: instance.scaling.asArray()
  33415. };
  33416. if (instance.rotationQuaternion) {
  33417. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33418. }
  33419. else if (instance.rotation) {
  33420. serializationInstance.rotation = instance.rotation.asArray();
  33421. }
  33422. serializationObject.instances.push(serializationInstance);
  33423. // Animations
  33424. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33425. serializationInstance.ranges = instance.serializeAnimationRanges();
  33426. }
  33427. //
  33428. // Animations
  33429. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33430. serializationObject.ranges = this.serializeAnimationRanges();
  33431. // Layer mask
  33432. serializationObject.layerMask = this.layerMask;
  33433. // Alpha
  33434. serializationObject.alphaIndex = this.alphaIndex;
  33435. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33436. // Overlay
  33437. serializationObject.overlayAlpha = this.overlayAlpha;
  33438. serializationObject.overlayColor = this.overlayColor.asArray();
  33439. serializationObject.renderOverlay = this.renderOverlay;
  33440. // Fog
  33441. serializationObject.applyFog = this.applyFog;
  33442. // Action Manager
  33443. if (this.actionManager) {
  33444. serializationObject.actions = this.actionManager.serialize(this.name);
  33445. }
  33446. };
  33447. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33448. if (!this.geometry) {
  33449. return;
  33450. }
  33451. this._markSubMeshesAsAttributesDirty();
  33452. var morphTargetManager = this._morphTargetManager;
  33453. if (morphTargetManager && morphTargetManager.vertexCount) {
  33454. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33455. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33456. this.morphTargetManager = null;
  33457. return;
  33458. }
  33459. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33460. var morphTarget = morphTargetManager.getActiveTarget(index);
  33461. var positions = morphTarget.getPositions();
  33462. if (!positions) {
  33463. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33464. return;
  33465. }
  33466. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33467. var normals = morphTarget.getNormals();
  33468. if (normals) {
  33469. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33470. }
  33471. var tangents = morphTarget.getTangents();
  33472. if (tangents) {
  33473. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33474. }
  33475. }
  33476. }
  33477. else {
  33478. var index = 0;
  33479. // Positions
  33480. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33481. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33482. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33483. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33484. }
  33485. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33486. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33487. }
  33488. index++;
  33489. }
  33490. }
  33491. };
  33492. // Statics
  33493. /**
  33494. * Returns a new Mesh object parsed from the source provided.
  33495. * The parameter `parsedMesh` is the source.
  33496. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33497. */
  33498. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33499. var mesh;
  33500. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33501. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33502. }
  33503. else {
  33504. mesh = new Mesh(parsedMesh.name, scene);
  33505. }
  33506. mesh.id = parsedMesh.id;
  33507. if (BABYLON.Tags) {
  33508. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33509. }
  33510. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33511. if (parsedMesh.metadata !== undefined) {
  33512. mesh.metadata = parsedMesh.metadata;
  33513. }
  33514. if (parsedMesh.rotationQuaternion) {
  33515. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33516. }
  33517. else if (parsedMesh.rotation) {
  33518. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33519. }
  33520. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33521. if (parsedMesh.localMatrix) {
  33522. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33523. }
  33524. else if (parsedMesh.pivotMatrix) {
  33525. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33526. }
  33527. mesh.setEnabled(parsedMesh.isEnabled);
  33528. mesh.isVisible = parsedMesh.isVisible;
  33529. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33530. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33531. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33532. if (parsedMesh.applyFog !== undefined) {
  33533. mesh.applyFog = parsedMesh.applyFog;
  33534. }
  33535. if (parsedMesh.pickable !== undefined) {
  33536. mesh.isPickable = parsedMesh.pickable;
  33537. }
  33538. if (parsedMesh.alphaIndex !== undefined) {
  33539. mesh.alphaIndex = parsedMesh.alphaIndex;
  33540. }
  33541. mesh.receiveShadows = parsedMesh.receiveShadows;
  33542. mesh.billboardMode = parsedMesh.billboardMode;
  33543. if (parsedMesh.visibility !== undefined) {
  33544. mesh.visibility = parsedMesh.visibility;
  33545. }
  33546. mesh.checkCollisions = parsedMesh.checkCollisions;
  33547. if (parsedMesh.isBlocker !== undefined) {
  33548. mesh.isBlocker = parsedMesh.isBlocker;
  33549. }
  33550. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33551. // freezeWorldMatrix
  33552. if (parsedMesh.freezeWorldMatrix) {
  33553. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33554. }
  33555. // Parent
  33556. if (parsedMesh.parentId) {
  33557. mesh._waitingParentId = parsedMesh.parentId;
  33558. }
  33559. // Actions
  33560. if (parsedMesh.actions !== undefined) {
  33561. mesh._waitingActions = parsedMesh.actions;
  33562. }
  33563. // Overlay
  33564. if (parsedMesh.overlayAlpha !== undefined) {
  33565. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33566. }
  33567. if (parsedMesh.overlayColor !== undefined) {
  33568. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33569. }
  33570. if (parsedMesh.renderOverlay !== undefined) {
  33571. mesh.renderOverlay = parsedMesh.renderOverlay;
  33572. }
  33573. // Geometry
  33574. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33575. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33576. if (parsedMesh.delayLoadingFile) {
  33577. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33578. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33579. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33580. if (parsedMesh._binaryInfo) {
  33581. mesh._binaryInfo = parsedMesh._binaryInfo;
  33582. }
  33583. mesh._delayInfo = [];
  33584. if (parsedMesh.hasUVs) {
  33585. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33586. }
  33587. if (parsedMesh.hasUVs2) {
  33588. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33589. }
  33590. if (parsedMesh.hasUVs3) {
  33591. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33592. }
  33593. if (parsedMesh.hasUVs4) {
  33594. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33595. }
  33596. if (parsedMesh.hasUVs5) {
  33597. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33598. }
  33599. if (parsedMesh.hasUVs6) {
  33600. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33601. }
  33602. if (parsedMesh.hasColors) {
  33603. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33604. }
  33605. if (parsedMesh.hasMatricesIndices) {
  33606. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33607. }
  33608. if (parsedMesh.hasMatricesWeights) {
  33609. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33610. }
  33611. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33612. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33613. mesh._checkDelayState();
  33614. }
  33615. }
  33616. else {
  33617. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33618. }
  33619. // Material
  33620. if (parsedMesh.materialId) {
  33621. mesh.setMaterialByID(parsedMesh.materialId);
  33622. }
  33623. else {
  33624. mesh.material = null;
  33625. }
  33626. // Morph targets
  33627. if (parsedMesh.morphTargetManagerId > -1) {
  33628. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33629. }
  33630. // Skeleton
  33631. if (parsedMesh.skeletonId > -1) {
  33632. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33633. if (parsedMesh.numBoneInfluencers) {
  33634. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33635. }
  33636. }
  33637. // Animations
  33638. if (parsedMesh.animations) {
  33639. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33640. var parsedAnimation = parsedMesh.animations[animationIndex];
  33641. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33642. }
  33643. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33644. }
  33645. if (parsedMesh.autoAnimate) {
  33646. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33647. }
  33648. // Layer Mask
  33649. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33650. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33651. }
  33652. else {
  33653. mesh.layerMask = 0x0FFFFFFF;
  33654. }
  33655. // Physics
  33656. if (parsedMesh.physicsImpostor) {
  33657. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33658. mass: parsedMesh.physicsMass,
  33659. friction: parsedMesh.physicsFriction,
  33660. restitution: parsedMesh.physicsRestitution
  33661. }, scene);
  33662. }
  33663. // Instances
  33664. if (parsedMesh.instances) {
  33665. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33666. var parsedInstance = parsedMesh.instances[index];
  33667. var instance = mesh.createInstance(parsedInstance.name);
  33668. if (parsedInstance.id) {
  33669. instance.id = parsedInstance.id;
  33670. }
  33671. if (BABYLON.Tags) {
  33672. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33673. }
  33674. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33675. if (parsedInstance.parentId) {
  33676. instance._waitingParentId = parsedInstance.parentId;
  33677. }
  33678. if (parsedInstance.rotationQuaternion) {
  33679. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33680. }
  33681. else if (parsedInstance.rotation) {
  33682. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33683. }
  33684. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33685. instance.checkCollisions = mesh.checkCollisions;
  33686. if (parsedMesh.animations) {
  33687. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33688. parsedAnimation = parsedMesh.animations[animationIndex];
  33689. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33690. }
  33691. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33692. }
  33693. }
  33694. }
  33695. return mesh;
  33696. };
  33697. /**
  33698. * Creates a ribbon mesh.
  33699. * Please consider using the same method from the MeshBuilder class instead.
  33700. * 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.
  33701. *
  33702. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33703. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33704. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33705. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33706. * 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.
  33707. * 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.
  33708. * 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
  33709. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33710. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33711. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33712. */
  33713. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33714. if (closeArray === void 0) { closeArray = false; }
  33715. if (updatable === void 0) { updatable = false; }
  33716. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33717. pathArray: pathArray,
  33718. closeArray: closeArray,
  33719. closePath: closePath,
  33720. offset: offset,
  33721. updatable: updatable,
  33722. sideOrientation: sideOrientation,
  33723. instance: instance
  33724. }, scene);
  33725. };
  33726. /**
  33727. * Creates a plane polygonal mesh. By default, this is a disc.
  33728. * Please consider using the same method from the MeshBuilder class instead.
  33729. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33730. * 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.
  33731. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33732. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33733. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33734. */
  33735. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33736. if (scene === void 0) { scene = null; }
  33737. var options = {
  33738. radius: radius,
  33739. tessellation: tessellation,
  33740. sideOrientation: sideOrientation,
  33741. updatable: updatable
  33742. };
  33743. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33744. };
  33745. /**
  33746. * Creates a box mesh.
  33747. * Please consider using the same method from the MeshBuilder class instead.
  33748. * The parameter `size` sets the size (float) of each box side (default 1).
  33749. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33750. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33751. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33752. */
  33753. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33754. if (scene === void 0) { scene = null; }
  33755. var options = {
  33756. size: size,
  33757. sideOrientation: sideOrientation,
  33758. updatable: updatable
  33759. };
  33760. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33761. };
  33762. /**
  33763. * Creates a sphere mesh.
  33764. * Please consider using the same method from the MeshBuilder class instead.
  33765. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33766. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33767. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33768. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33769. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33770. */
  33771. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33772. var options = {
  33773. segments: segments,
  33774. diameterX: diameter,
  33775. diameterY: diameter,
  33776. diameterZ: diameter,
  33777. sideOrientation: sideOrientation,
  33778. updatable: updatable
  33779. };
  33780. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33781. };
  33782. /**
  33783. * Creates a cylinder or a cone mesh.
  33784. * Please consider using the same method from the MeshBuilder class instead.
  33785. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33786. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33787. * 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.
  33788. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33789. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33790. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33791. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33792. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33793. */
  33794. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33795. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33796. if (scene !== undefined) {
  33797. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33798. updatable = scene;
  33799. }
  33800. scene = subdivisions;
  33801. subdivisions = 1;
  33802. }
  33803. var options = {
  33804. height: height,
  33805. diameterTop: diameterTop,
  33806. diameterBottom: diameterBottom,
  33807. tessellation: tessellation,
  33808. subdivisions: subdivisions,
  33809. sideOrientation: sideOrientation,
  33810. updatable: updatable
  33811. };
  33812. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33813. };
  33814. // Torus (Code from SharpDX.org)
  33815. /**
  33816. * Creates a torus mesh.
  33817. * Please consider using the same method from the MeshBuilder class instead.
  33818. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33819. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33820. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33821. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33822. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33823. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33824. */
  33825. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33826. var options = {
  33827. diameter: diameter,
  33828. thickness: thickness,
  33829. tessellation: tessellation,
  33830. sideOrientation: sideOrientation,
  33831. updatable: updatable
  33832. };
  33833. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33834. };
  33835. /**
  33836. * Creates a torus knot mesh.
  33837. * Please consider using the same method from the MeshBuilder class instead.
  33838. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33839. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33840. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33841. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33842. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33843. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33844. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33845. */
  33846. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33847. var options = {
  33848. radius: radius,
  33849. tube: tube,
  33850. radialSegments: radialSegments,
  33851. tubularSegments: tubularSegments,
  33852. p: p,
  33853. q: q,
  33854. sideOrientation: sideOrientation,
  33855. updatable: updatable
  33856. };
  33857. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33858. };
  33859. /**
  33860. * Creates a line mesh.
  33861. * Please consider using the same method from the MeshBuilder class instead.
  33862. * 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.
  33863. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33864. * The parameter `points` is an array successive Vector3.
  33865. * 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
  33866. * When updating an instance, remember that only point positions can change, not the number of points.
  33867. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33868. */
  33869. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33870. if (scene === void 0) { scene = null; }
  33871. if (updatable === void 0) { updatable = false; }
  33872. if (instance === void 0) { instance = null; }
  33873. var options = {
  33874. points: points,
  33875. updatable: updatable,
  33876. instance: instance
  33877. };
  33878. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33879. };
  33880. /**
  33881. * Creates a dashed line mesh.
  33882. * Please consider using the same method from the MeshBuilder class instead.
  33883. * 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.
  33884. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33885. * The parameter `points` is an array successive Vector3.
  33886. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33887. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33888. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33889. * 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
  33890. * When updating an instance, remember that only point positions can change, not the number of points.
  33891. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33892. */
  33893. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33894. if (scene === void 0) { scene = null; }
  33895. var options = {
  33896. points: points,
  33897. dashSize: dashSize,
  33898. gapSize: gapSize,
  33899. dashNb: dashNb,
  33900. updatable: updatable,
  33901. instance: instance
  33902. };
  33903. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33904. };
  33905. /**
  33906. * Creates a polygon mesh.
  33907. * Please consider using the same method from the MeshBuilder class instead.
  33908. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33909. * 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.
  33910. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33911. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33912. * Remember you can only change the shape positions, not their number when updating a polygon.
  33913. */
  33914. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33915. var options = {
  33916. shape: shape,
  33917. holes: holes,
  33918. updatable: updatable,
  33919. sideOrientation: sideOrientation
  33920. };
  33921. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33922. };
  33923. /**
  33924. * Creates an extruded polygon mesh, with depth in the Y direction.
  33925. * Please consider using the same method from the MeshBuilder class instead.
  33926. */
  33927. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33928. var options = {
  33929. shape: shape,
  33930. holes: holes,
  33931. depth: depth,
  33932. updatable: updatable,
  33933. sideOrientation: sideOrientation
  33934. };
  33935. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33936. };
  33937. /**
  33938. * Creates an extruded shape mesh.
  33939. * 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.
  33940. * Please consider using the same method from the MeshBuilder class instead.
  33941. *
  33942. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33943. * 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
  33944. * extruded along the Z axis.
  33945. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33946. * 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.
  33947. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33948. * 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
  33949. * 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
  33950. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33951. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33952. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33953. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33954. */
  33955. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33956. if (scene === void 0) { scene = null; }
  33957. var options = {
  33958. shape: shape,
  33959. path: path,
  33960. scale: scale,
  33961. rotation: rotation,
  33962. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33963. sideOrientation: sideOrientation,
  33964. instance: instance,
  33965. updatable: updatable
  33966. };
  33967. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33968. };
  33969. /**
  33970. * Creates an custom extruded shape mesh.
  33971. * 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.
  33972. * Please consider using the same method from the MeshBuilder class instead.
  33973. *
  33974. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33975. * 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
  33976. * extruded along the Z axis.
  33977. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33978. * 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
  33979. * and the distance of this point from the begining of the path :
  33980. * ```javascript
  33981. * var rotationFunction = function(i, distance) {
  33982. * // do things
  33983. * return rotationValue; }
  33984. * ```
  33985. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33986. * 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
  33987. * and the distance of this point from the begining of the path :
  33988. * ```javascript
  33989. * var scaleFunction = function(i, distance) {
  33990. * // do things
  33991. * return scaleValue;}
  33992. * ```
  33993. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33994. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33995. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33996. * 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
  33997. * 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
  33998. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33999. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34000. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34001. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34002. */
  34003. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34004. var options = {
  34005. shape: shape,
  34006. path: path,
  34007. scaleFunction: scaleFunction,
  34008. rotationFunction: rotationFunction,
  34009. ribbonCloseArray: ribbonCloseArray,
  34010. ribbonClosePath: ribbonClosePath,
  34011. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34012. sideOrientation: sideOrientation,
  34013. instance: instance,
  34014. updatable: updatable
  34015. };
  34016. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34017. };
  34018. /**
  34019. * Creates lathe mesh.
  34020. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34021. * Please consider using the same method from the MeshBuilder class instead.
  34022. * 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
  34023. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  34024. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  34025. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  34026. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34027. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34028. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34029. */
  34030. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34031. var options = {
  34032. shape: shape,
  34033. radius: radius,
  34034. tessellation: tessellation,
  34035. sideOrientation: sideOrientation,
  34036. updatable: updatable
  34037. };
  34038. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34039. };
  34040. /**
  34041. * Creates a plane mesh.
  34042. * Please consider using the same method from the MeshBuilder class instead.
  34043. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  34044. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34045. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34046. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34047. */
  34048. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34049. var options = {
  34050. size: size,
  34051. width: size,
  34052. height: size,
  34053. sideOrientation: sideOrientation,
  34054. updatable: updatable
  34055. };
  34056. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34057. };
  34058. /**
  34059. * Creates a ground mesh.
  34060. * Please consider using the same method from the MeshBuilder class instead.
  34061. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  34062. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  34063. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34064. */
  34065. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34066. var options = {
  34067. width: width,
  34068. height: height,
  34069. subdivisions: subdivisions,
  34070. updatable: updatable
  34071. };
  34072. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34073. };
  34074. /**
  34075. * Creates a tiled ground mesh.
  34076. * Please consider using the same method from the MeshBuilder class instead.
  34077. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  34078. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  34079. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  34080. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  34081. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  34082. * numbers of subdivisions on the ground width and height of each tile.
  34083. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34084. */
  34085. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34086. var options = {
  34087. xmin: xmin,
  34088. zmin: zmin,
  34089. xmax: xmax,
  34090. zmax: zmax,
  34091. subdivisions: subdivisions,
  34092. precision: precision,
  34093. updatable: updatable
  34094. };
  34095. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34096. };
  34097. /**
  34098. * Creates a ground mesh from a height map.
  34099. * tuto : http://doc.babylonjs.com/babylon101/height_map
  34100. * Please consider using the same method from the MeshBuilder class instead.
  34101. * The parameter `url` sets the URL of the height map image resource.
  34102. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  34103. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  34104. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  34105. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  34106. * 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).
  34107. * This function is passed the newly built mesh :
  34108. * ```javascript
  34109. * function(mesh) { // do things
  34110. * return; }
  34111. * ```
  34112. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34113. */
  34114. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34115. var options = {
  34116. width: width,
  34117. height: height,
  34118. subdivisions: subdivisions,
  34119. minHeight: minHeight,
  34120. maxHeight: maxHeight,
  34121. updatable: updatable,
  34122. onReady: onReady
  34123. };
  34124. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34125. };
  34126. /**
  34127. * Creates a tube mesh.
  34128. * 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.
  34129. * Please consider using the same method from the MeshBuilder class instead.
  34130. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34131. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34132. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34133. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34134. * 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.
  34135. * It must return a radius value (positive float) :
  34136. * ```javascript
  34137. * var radiusFunction = function(i, distance) {
  34138. * // do things
  34139. * return radius; }
  34140. * ```
  34141. * 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
  34142. * 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
  34143. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34144. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34145. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34146. */
  34147. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34148. var options = {
  34149. path: path,
  34150. radius: radius,
  34151. tessellation: tessellation,
  34152. radiusFunction: radiusFunction,
  34153. arc: 1,
  34154. cap: cap,
  34155. updatable: updatable,
  34156. sideOrientation: sideOrientation,
  34157. instance: instance
  34158. };
  34159. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34160. };
  34161. /**
  34162. * Creates a polyhedron mesh.
  34163. * Please consider using the same method from the MeshBuilder class instead.
  34164. * 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
  34165. * to choose the wanted type.
  34166. * The parameter `size` (positive float, default 1) sets the polygon size.
  34167. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34168. * 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`.
  34169. * 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
  34170. * 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)`).
  34171. * 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
  34172. * 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.
  34173. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34174. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34175. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34176. */
  34177. Mesh.CreatePolyhedron = function (name, options, scene) {
  34178. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34179. };
  34180. /**
  34181. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34182. * Please consider using the same method from the MeshBuilder class instead.
  34183. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34184. * 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`).
  34185. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34186. * 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.
  34187. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34188. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34189. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34190. */
  34191. Mesh.CreateIcoSphere = function (name, options, scene) {
  34192. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34193. };
  34194. /**
  34195. * Creates a decal mesh.
  34196. * Please consider using the same method from the MeshBuilder class instead.
  34197. * 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.
  34198. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34199. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34200. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34201. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34202. */
  34203. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34204. var options = {
  34205. position: position,
  34206. normal: normal,
  34207. size: size,
  34208. angle: angle
  34209. };
  34210. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34211. };
  34212. // Skeletons
  34213. /**
  34214. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34215. */
  34216. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34217. if (!this._sourcePositions) {
  34218. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34219. if (!source) {
  34220. return this._sourcePositions;
  34221. }
  34222. this._sourcePositions = new Float32Array(source);
  34223. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34224. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34225. }
  34226. }
  34227. return this._sourcePositions;
  34228. };
  34229. /**
  34230. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34231. */
  34232. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34233. if (!this._sourceNormals) {
  34234. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34235. if (!source) {
  34236. return this._sourceNormals;
  34237. }
  34238. this._sourceNormals = new Float32Array(source);
  34239. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34240. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34241. }
  34242. }
  34243. return this._sourceNormals;
  34244. };
  34245. /**
  34246. * Updates the vertex buffer by applying transformation from the bones.
  34247. * Returns the Mesh.
  34248. *
  34249. * @param {skeleton} skeleton to apply
  34250. */
  34251. Mesh.prototype.applySkeleton = function (skeleton) {
  34252. if (!this.geometry) {
  34253. return this;
  34254. }
  34255. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34256. return this;
  34257. }
  34258. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34259. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34260. return this;
  34261. }
  34262. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34263. return this;
  34264. }
  34265. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34266. return this;
  34267. }
  34268. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34269. return this;
  34270. }
  34271. if (!this._sourcePositions) {
  34272. var submeshes = this.subMeshes.slice();
  34273. this.setPositionsForCPUSkinning();
  34274. this.subMeshes = submeshes;
  34275. }
  34276. if (!this._sourceNormals) {
  34277. this.setNormalsForCPUSkinning();
  34278. }
  34279. // positionsData checks for not being Float32Array will only pass at most once
  34280. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34281. if (!positionsData) {
  34282. return this;
  34283. }
  34284. if (!(positionsData instanceof Float32Array)) {
  34285. positionsData = new Float32Array(positionsData);
  34286. }
  34287. // normalsData checks for not being Float32Array will only pass at most once
  34288. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34289. if (!normalsData) {
  34290. return this;
  34291. }
  34292. if (!(normalsData instanceof Float32Array)) {
  34293. normalsData = new Float32Array(normalsData);
  34294. }
  34295. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34296. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34297. if (!matricesWeightsData || !matricesIndicesData) {
  34298. return this;
  34299. }
  34300. var needExtras = this.numBoneInfluencers > 4;
  34301. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34302. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34303. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34304. var tempVector3 = BABYLON.Vector3.Zero();
  34305. var finalMatrix = new BABYLON.Matrix();
  34306. var tempMatrix = new BABYLON.Matrix();
  34307. var matWeightIdx = 0;
  34308. var inf;
  34309. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34310. var weight;
  34311. for (inf = 0; inf < 4; inf++) {
  34312. weight = matricesWeightsData[matWeightIdx + inf];
  34313. if (weight > 0) {
  34314. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34315. finalMatrix.addToSelf(tempMatrix);
  34316. }
  34317. else
  34318. break;
  34319. }
  34320. if (needExtras) {
  34321. for (inf = 0; inf < 4; inf++) {
  34322. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34323. if (weight > 0) {
  34324. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34325. finalMatrix.addToSelf(tempMatrix);
  34326. }
  34327. else
  34328. break;
  34329. }
  34330. }
  34331. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34332. tempVector3.toArray(positionsData, index);
  34333. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34334. tempVector3.toArray(normalsData, index);
  34335. finalMatrix.reset();
  34336. }
  34337. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34338. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34339. return this;
  34340. };
  34341. // Tools
  34342. /**
  34343. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34344. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34345. */
  34346. Mesh.MinMax = function (meshes) {
  34347. var minVector = null;
  34348. var maxVector = null;
  34349. meshes.forEach(function (mesh, index, array) {
  34350. var boundingInfo = mesh.getBoundingInfo();
  34351. var boundingBox = boundingInfo.boundingBox;
  34352. if (!minVector || !maxVector) {
  34353. minVector = boundingBox.minimumWorld;
  34354. maxVector = boundingBox.maximumWorld;
  34355. }
  34356. else {
  34357. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34358. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34359. }
  34360. });
  34361. if (!minVector || !maxVector) {
  34362. return {
  34363. min: BABYLON.Vector3.Zero(),
  34364. max: BABYLON.Vector3.Zero()
  34365. };
  34366. }
  34367. return {
  34368. min: minVector,
  34369. max: maxVector
  34370. };
  34371. };
  34372. /**
  34373. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34374. */
  34375. Mesh.Center = function (meshesOrMinMaxVector) {
  34376. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34377. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34378. };
  34379. /**
  34380. * Merge the array of meshes into a single mesh for performance reasons.
  34381. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34382. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34383. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34384. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34385. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34386. */
  34387. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34388. if (disposeSource === void 0) { disposeSource = true; }
  34389. var index;
  34390. if (!allow32BitsIndices) {
  34391. var totalVertices = 0;
  34392. // Counting vertices
  34393. for (index = 0; index < meshes.length; index++) {
  34394. if (meshes[index]) {
  34395. totalVertices += meshes[index].getTotalVertices();
  34396. if (totalVertices > 65536) {
  34397. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34398. return null;
  34399. }
  34400. }
  34401. }
  34402. }
  34403. // Merge
  34404. var vertexData = null;
  34405. var otherVertexData;
  34406. var indiceArray = new Array();
  34407. var source = null;
  34408. for (index = 0; index < meshes.length; index++) {
  34409. if (meshes[index]) {
  34410. meshes[index].computeWorldMatrix(true);
  34411. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34412. otherVertexData.transform(meshes[index].getWorldMatrix());
  34413. if (vertexData) {
  34414. vertexData.merge(otherVertexData);
  34415. }
  34416. else {
  34417. vertexData = otherVertexData;
  34418. source = meshes[index];
  34419. }
  34420. if (subdivideWithSubMeshes) {
  34421. indiceArray.push(meshes[index].getTotalIndices());
  34422. }
  34423. }
  34424. }
  34425. source = source;
  34426. if (!meshSubclass) {
  34427. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34428. }
  34429. vertexData.applyToMesh(meshSubclass);
  34430. // Setting properties
  34431. meshSubclass.material = source.material;
  34432. meshSubclass.checkCollisions = source.checkCollisions;
  34433. // Cleaning
  34434. if (disposeSource) {
  34435. for (index = 0; index < meshes.length; index++) {
  34436. if (meshes[index]) {
  34437. meshes[index].dispose();
  34438. }
  34439. }
  34440. }
  34441. // Subdivide
  34442. if (subdivideWithSubMeshes) {
  34443. //-- removal of global submesh
  34444. meshSubclass.releaseSubMeshes();
  34445. index = 0;
  34446. var offset = 0;
  34447. //-- apply subdivision according to index table
  34448. while (index < indiceArray.length) {
  34449. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34450. offset += indiceArray[index];
  34451. index++;
  34452. }
  34453. }
  34454. return meshSubclass;
  34455. };
  34456. // Consts
  34457. Mesh._FRONTSIDE = 0;
  34458. Mesh._BACKSIDE = 1;
  34459. Mesh._DOUBLESIDE = 2;
  34460. Mesh._DEFAULTSIDE = 0;
  34461. Mesh._NO_CAP = 0;
  34462. Mesh._CAP_START = 1;
  34463. Mesh._CAP_END = 2;
  34464. Mesh._CAP_ALL = 3;
  34465. return Mesh;
  34466. }(BABYLON.AbstractMesh));
  34467. BABYLON.Mesh = Mesh;
  34468. })(BABYLON || (BABYLON = {}));
  34469. //# sourceMappingURL=babylon.mesh.js.map
  34470. var BABYLON;
  34471. (function (BABYLON) {
  34472. var BaseSubMesh = /** @class */ (function () {
  34473. function BaseSubMesh() {
  34474. }
  34475. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34476. get: function () {
  34477. return this._materialEffect;
  34478. },
  34479. enumerable: true,
  34480. configurable: true
  34481. });
  34482. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34483. if (defines === void 0) { defines = null; }
  34484. if (this._materialEffect === effect) {
  34485. if (!effect) {
  34486. this._materialDefines = null;
  34487. }
  34488. return;
  34489. }
  34490. this._materialDefines = defines;
  34491. this._materialEffect = effect;
  34492. };
  34493. return BaseSubMesh;
  34494. }());
  34495. BABYLON.BaseSubMesh = BaseSubMesh;
  34496. var SubMesh = /** @class */ (function (_super) {
  34497. __extends(SubMesh, _super);
  34498. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34499. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34500. var _this = _super.call(this) || this;
  34501. _this.materialIndex = materialIndex;
  34502. _this.verticesStart = verticesStart;
  34503. _this.verticesCount = verticesCount;
  34504. _this.indexStart = indexStart;
  34505. _this.indexCount = indexCount;
  34506. _this._renderId = 0;
  34507. _this._mesh = mesh;
  34508. _this._renderingMesh = renderingMesh || mesh;
  34509. mesh.subMeshes.push(_this);
  34510. _this._trianglePlanes = [];
  34511. _this._id = mesh.subMeshes.length - 1;
  34512. if (createBoundingBox) {
  34513. _this.refreshBoundingInfo();
  34514. mesh.computeWorldMatrix(true);
  34515. }
  34516. return _this;
  34517. }
  34518. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34519. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34520. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34521. };
  34522. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34523. get: function () {
  34524. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34525. },
  34526. enumerable: true,
  34527. configurable: true
  34528. });
  34529. /**
  34530. * Returns the submesh BoudingInfo object.
  34531. */
  34532. SubMesh.prototype.getBoundingInfo = function () {
  34533. if (this.IsGlobal) {
  34534. return this._mesh.getBoundingInfo();
  34535. }
  34536. return this._boundingInfo;
  34537. };
  34538. /**
  34539. * Sets the submesh BoundingInfo.
  34540. * Return the SubMesh.
  34541. */
  34542. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34543. this._boundingInfo = boundingInfo;
  34544. return this;
  34545. };
  34546. /**
  34547. * Returns the mesh of the current submesh.
  34548. */
  34549. SubMesh.prototype.getMesh = function () {
  34550. return this._mesh;
  34551. };
  34552. /**
  34553. * Returns the rendering mesh of the submesh.
  34554. */
  34555. SubMesh.prototype.getRenderingMesh = function () {
  34556. return this._renderingMesh;
  34557. };
  34558. /**
  34559. * Returns the submesh material.
  34560. */
  34561. SubMesh.prototype.getMaterial = function () {
  34562. var rootMaterial = this._renderingMesh.material;
  34563. if (rootMaterial === null || rootMaterial === undefined) {
  34564. return this._mesh.getScene().defaultMaterial;
  34565. }
  34566. else if (rootMaterial.getSubMaterial) {
  34567. var multiMaterial = rootMaterial;
  34568. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34569. if (this._currentMaterial !== effectiveMaterial) {
  34570. this._currentMaterial = effectiveMaterial;
  34571. this._materialDefines = null;
  34572. }
  34573. return effectiveMaterial;
  34574. }
  34575. return rootMaterial;
  34576. };
  34577. // Methods
  34578. /**
  34579. * Sets a new updated BoundingInfo object to the submesh.
  34580. * Returns the SubMesh.
  34581. */
  34582. SubMesh.prototype.refreshBoundingInfo = function () {
  34583. this._lastColliderWorldVertices = null;
  34584. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34585. return this;
  34586. }
  34587. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34588. if (!data) {
  34589. this._boundingInfo = this._mesh.getBoundingInfo();
  34590. return this;
  34591. }
  34592. var indices = this._renderingMesh.getIndices();
  34593. var extend;
  34594. //is this the only submesh?
  34595. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34596. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34597. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34598. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34599. }
  34600. else {
  34601. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34602. }
  34603. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34604. return this;
  34605. };
  34606. SubMesh.prototype._checkCollision = function (collider) {
  34607. var boundingInfo = this.getBoundingInfo();
  34608. return boundingInfo._checkCollision(collider);
  34609. };
  34610. /**
  34611. * Updates the submesh BoundingInfo.
  34612. * Returns the Submesh.
  34613. */
  34614. SubMesh.prototype.updateBoundingInfo = function (world) {
  34615. var boundingInfo = this.getBoundingInfo();
  34616. if (!boundingInfo) {
  34617. this.refreshBoundingInfo();
  34618. boundingInfo = this.getBoundingInfo();
  34619. }
  34620. boundingInfo.update(world);
  34621. return this;
  34622. };
  34623. /**
  34624. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34625. * Boolean returned.
  34626. */
  34627. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34628. var boundingInfo = this.getBoundingInfo();
  34629. if (!boundingInfo) {
  34630. return false;
  34631. }
  34632. return boundingInfo.isInFrustum(frustumPlanes);
  34633. };
  34634. /**
  34635. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34636. * Boolean returned.
  34637. */
  34638. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34639. var boundingInfo = this.getBoundingInfo();
  34640. if (!boundingInfo) {
  34641. return false;
  34642. }
  34643. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34644. };
  34645. /**
  34646. * Renders the submesh.
  34647. * Returns it.
  34648. */
  34649. SubMesh.prototype.render = function (enableAlphaMode) {
  34650. this._renderingMesh.render(this, enableAlphaMode);
  34651. return this;
  34652. };
  34653. /**
  34654. * Returns a new Index Buffer.
  34655. * Type returned : WebGLBuffer.
  34656. */
  34657. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34658. if (!this._linesIndexBuffer) {
  34659. var linesIndices = [];
  34660. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34661. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34662. }
  34663. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34664. this.linesIndexCount = linesIndices.length;
  34665. }
  34666. return this._linesIndexBuffer;
  34667. };
  34668. /**
  34669. * True is the passed Ray intersects the submesh bounding box.
  34670. * Boolean returned.
  34671. */
  34672. SubMesh.prototype.canIntersects = function (ray) {
  34673. var boundingInfo = this.getBoundingInfo();
  34674. if (!boundingInfo) {
  34675. return false;
  34676. }
  34677. return ray.intersectsBox(boundingInfo.boundingBox);
  34678. };
  34679. /**
  34680. * Returns an object IntersectionInfo.
  34681. */
  34682. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34683. var intersectInfo = null;
  34684. var material = this.getMaterial();
  34685. if (!material) {
  34686. return null;
  34687. }
  34688. switch (material.fillMode) {
  34689. case BABYLON.Material.PointListDrawMode:
  34690. case BABYLON.Material.LineListDrawMode:
  34691. case BABYLON.Material.LineLoopDrawMode:
  34692. case BABYLON.Material.LineStripDrawMode:
  34693. case BABYLON.Material.TriangleFanDrawMode:
  34694. case BABYLON.Material.TriangleStripDrawMode:
  34695. return null;
  34696. }
  34697. // LineMesh first as it's also a Mesh...
  34698. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34699. var lineMesh = this._mesh;
  34700. // Line test
  34701. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34702. var p0 = positions[indices[index]];
  34703. var p1 = positions[indices[index + 1]];
  34704. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34705. if (length < 0) {
  34706. continue;
  34707. }
  34708. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34709. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34710. if (fastCheck) {
  34711. break;
  34712. }
  34713. }
  34714. }
  34715. }
  34716. else {
  34717. // Triangles test
  34718. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34719. var p0 = positions[indices[index]];
  34720. var p1 = positions[indices[index + 1]];
  34721. var p2 = positions[indices[index + 2]];
  34722. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34723. if (currentIntersectInfo) {
  34724. if (currentIntersectInfo.distance < 0) {
  34725. continue;
  34726. }
  34727. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34728. intersectInfo = currentIntersectInfo;
  34729. intersectInfo.faceId = index / 3;
  34730. if (fastCheck) {
  34731. break;
  34732. }
  34733. }
  34734. }
  34735. }
  34736. }
  34737. return intersectInfo;
  34738. };
  34739. SubMesh.prototype._rebuild = function () {
  34740. if (this._linesIndexBuffer) {
  34741. this._linesIndexBuffer = null;
  34742. }
  34743. };
  34744. // Clone
  34745. /**
  34746. * Creates a new Submesh from the passed Mesh.
  34747. */
  34748. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34749. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34750. if (!this.IsGlobal) {
  34751. var boundingInfo = this.getBoundingInfo();
  34752. if (!boundingInfo) {
  34753. return result;
  34754. }
  34755. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34756. }
  34757. return result;
  34758. };
  34759. // Dispose
  34760. /**
  34761. * Disposes the Submesh.
  34762. * Returns nothing.
  34763. */
  34764. SubMesh.prototype.dispose = function () {
  34765. if (this._linesIndexBuffer) {
  34766. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34767. this._linesIndexBuffer = null;
  34768. }
  34769. // Remove from mesh
  34770. var index = this._mesh.subMeshes.indexOf(this);
  34771. this._mesh.subMeshes.splice(index, 1);
  34772. };
  34773. // Statics
  34774. /**
  34775. * Creates a new Submesh from the passed parameters :
  34776. * - materialIndex (integer) : the index of the main mesh material.
  34777. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34778. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34779. * - mesh (Mesh) : the main mesh to create the submesh from.
  34780. * - renderingMesh (optional Mesh) : rendering mesh.
  34781. */
  34782. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34783. var minVertexIndex = Number.MAX_VALUE;
  34784. var maxVertexIndex = -Number.MAX_VALUE;
  34785. renderingMesh = (renderingMesh || mesh);
  34786. var indices = renderingMesh.getIndices();
  34787. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34788. var vertexIndex = indices[index];
  34789. if (vertexIndex < minVertexIndex)
  34790. minVertexIndex = vertexIndex;
  34791. if (vertexIndex > maxVertexIndex)
  34792. maxVertexIndex = vertexIndex;
  34793. }
  34794. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34795. };
  34796. return SubMesh;
  34797. }(BaseSubMesh));
  34798. BABYLON.SubMesh = SubMesh;
  34799. })(BABYLON || (BABYLON = {}));
  34800. //# sourceMappingURL=babylon.subMesh.js.map
  34801. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34802. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34803. s = arguments[i];
  34804. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34805. t[p] = s[p];
  34806. }
  34807. return t;
  34808. };
  34809. var BABYLON;
  34810. (function (BABYLON) {
  34811. /**
  34812. * Manages the defines for the Material
  34813. */
  34814. var MaterialDefines = /** @class */ (function () {
  34815. function MaterialDefines() {
  34816. this._isDirty = true;
  34817. /** @hidden */
  34818. this._areLightsDirty = true;
  34819. /** @hidden */
  34820. this._areAttributesDirty = true;
  34821. /** @hidden */
  34822. this._areTexturesDirty = true;
  34823. /** @hidden */
  34824. this._areFresnelDirty = true;
  34825. /** @hidden */
  34826. this._areMiscDirty = true;
  34827. /** @hidden */
  34828. this._areImageProcessingDirty = true;
  34829. /** @hidden */
  34830. this._normals = false;
  34831. /** @hidden */
  34832. this._uvs = false;
  34833. /** @hidden */
  34834. this._needNormals = false;
  34835. /** @hidden */
  34836. this._needUVs = false;
  34837. }
  34838. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34839. /**
  34840. * Specifies if the material needs to be re-calculated
  34841. */
  34842. get: function () {
  34843. return this._isDirty;
  34844. },
  34845. enumerable: true,
  34846. configurable: true
  34847. });
  34848. /**
  34849. * Marks the material to indicate that it has been re-calculated
  34850. */
  34851. MaterialDefines.prototype.markAsProcessed = function () {
  34852. this._isDirty = false;
  34853. this._areAttributesDirty = false;
  34854. this._areTexturesDirty = false;
  34855. this._areFresnelDirty = false;
  34856. this._areLightsDirty = false;
  34857. this._areMiscDirty = false;
  34858. this._areImageProcessingDirty = false;
  34859. };
  34860. /**
  34861. * Marks the material to indicate that it needs to be re-calculated
  34862. */
  34863. MaterialDefines.prototype.markAsUnprocessed = function () {
  34864. this._isDirty = true;
  34865. };
  34866. /**
  34867. * Marks the material to indicate all of its defines need to be re-calculated
  34868. */
  34869. MaterialDefines.prototype.markAllAsDirty = function () {
  34870. this._areTexturesDirty = true;
  34871. this._areAttributesDirty = true;
  34872. this._areLightsDirty = true;
  34873. this._areFresnelDirty = true;
  34874. this._areMiscDirty = true;
  34875. this._areImageProcessingDirty = true;
  34876. this._isDirty = true;
  34877. };
  34878. /**
  34879. * Marks the material to indicate that image processing needs to be re-calculated
  34880. */
  34881. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34882. this._areImageProcessingDirty = true;
  34883. this._isDirty = true;
  34884. };
  34885. /**
  34886. * Marks the material to indicate the lights need to be re-calculated
  34887. */
  34888. MaterialDefines.prototype.markAsLightDirty = function () {
  34889. this._areLightsDirty = true;
  34890. this._isDirty = true;
  34891. };
  34892. /**
  34893. * Marks the attribute state as changed
  34894. */
  34895. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34896. this._areAttributesDirty = true;
  34897. this._isDirty = true;
  34898. };
  34899. /**
  34900. * Marks the texture state as changed
  34901. */
  34902. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34903. this._areTexturesDirty = true;
  34904. this._isDirty = true;
  34905. };
  34906. /**
  34907. * Marks the fresnel state as changed
  34908. */
  34909. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34910. this._areFresnelDirty = true;
  34911. this._isDirty = true;
  34912. };
  34913. /**
  34914. * Marks the misc state as changed
  34915. */
  34916. MaterialDefines.prototype.markAsMiscDirty = function () {
  34917. this._areMiscDirty = true;
  34918. this._isDirty = true;
  34919. };
  34920. /**
  34921. * Rebuilds the material defines
  34922. */
  34923. MaterialDefines.prototype.rebuild = function () {
  34924. if (this._keys) {
  34925. delete this._keys;
  34926. }
  34927. this._keys = [];
  34928. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34929. var key = _a[_i];
  34930. if (key[0] === "_") {
  34931. continue;
  34932. }
  34933. this._keys.push(key);
  34934. }
  34935. };
  34936. /**
  34937. * Specifies if two material defines are equal
  34938. * @param other - A material define instance to compare to
  34939. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34940. */
  34941. MaterialDefines.prototype.isEqual = function (other) {
  34942. if (this._keys.length !== other._keys.length) {
  34943. return false;
  34944. }
  34945. for (var index = 0; index < this._keys.length; index++) {
  34946. var prop = this._keys[index];
  34947. if (this[prop] !== other[prop]) {
  34948. return false;
  34949. }
  34950. }
  34951. return true;
  34952. };
  34953. /**
  34954. * Clones this instance's defines to another instance
  34955. * @param other - material defines to clone values to
  34956. */
  34957. MaterialDefines.prototype.cloneTo = function (other) {
  34958. if (this._keys.length !== other._keys.length) {
  34959. other._keys = this._keys.slice(0);
  34960. }
  34961. for (var index = 0; index < this._keys.length; index++) {
  34962. var prop = this._keys[index];
  34963. other[prop] = this[prop];
  34964. }
  34965. };
  34966. /**
  34967. * Resets the material define values
  34968. */
  34969. MaterialDefines.prototype.reset = function () {
  34970. for (var index = 0; index < this._keys.length; index++) {
  34971. var prop = this._keys[index];
  34972. var type = typeof this[prop];
  34973. switch (type) {
  34974. case "number":
  34975. this[prop] = 0;
  34976. break;
  34977. case "string":
  34978. this[prop] = "";
  34979. break;
  34980. default:
  34981. this[prop] = false;
  34982. break;
  34983. }
  34984. }
  34985. };
  34986. /**
  34987. * Converts the material define values to a string
  34988. * @returns - String of material define information
  34989. */
  34990. MaterialDefines.prototype.toString = function () {
  34991. var result = "";
  34992. for (var index = 0; index < this._keys.length; index++) {
  34993. var prop = this._keys[index];
  34994. var value = this[prop];
  34995. var type = typeof value;
  34996. switch (type) {
  34997. case "number":
  34998. case "string":
  34999. result += "#define " + prop + " " + value + "\n";
  35000. break;
  35001. default:
  35002. if (value) {
  35003. result += "#define " + prop + "\n";
  35004. }
  35005. break;
  35006. }
  35007. }
  35008. return result;
  35009. };
  35010. return MaterialDefines;
  35011. }());
  35012. BABYLON.MaterialDefines = MaterialDefines;
  35013. /**
  35014. * Base class for the main features of a material in Babylon.js
  35015. */
  35016. var Material = /** @class */ (function () {
  35017. /**
  35018. * Creates a material instance
  35019. * @param name defines the name of the material
  35020. * @param scene defines the scene to reference
  35021. * @param doNotAdd specifies if the material should be added to the scene
  35022. */
  35023. function Material(name, scene, doNotAdd) {
  35024. /**
  35025. * Specifies if the ready state should be checked on each call
  35026. */
  35027. this.checkReadyOnEveryCall = false;
  35028. /**
  35029. * Specifies if the ready state should be checked once
  35030. */
  35031. this.checkReadyOnlyOnce = false;
  35032. /**
  35033. * The state of the material
  35034. */
  35035. this.state = "";
  35036. /**
  35037. * The alpha value of the material
  35038. */
  35039. this._alpha = 1.0;
  35040. /**
  35041. * Specifies if back face culling is enabled
  35042. */
  35043. this._backFaceCulling = true;
  35044. /**
  35045. * Specifies if the material should be serialized
  35046. */
  35047. this.doNotSerialize = false;
  35048. /**
  35049. * Specifies if the effect should be stored on sub meshes
  35050. */
  35051. this.storeEffectOnSubMeshes = false;
  35052. /**
  35053. * An event triggered when the material is disposed
  35054. */
  35055. this.onDisposeObservable = new BABYLON.Observable();
  35056. /**
  35057. * An event triggered when the material is bound
  35058. */
  35059. this.onBindObservable = new BABYLON.Observable();
  35060. /**
  35061. * An event triggered when the material is unbound
  35062. */
  35063. this.onUnBindObservable = new BABYLON.Observable();
  35064. /**
  35065. * Stores the value of the alpha mode
  35066. */
  35067. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35068. /**
  35069. * Stores the state of the need depth pre-pass value
  35070. */
  35071. this._needDepthPrePass = false;
  35072. /**
  35073. * Specifies if depth writing should be disabled
  35074. */
  35075. this.disableDepthWrite = false;
  35076. /**
  35077. * Specifies if depth writing should be forced
  35078. */
  35079. this.forceDepthWrite = false;
  35080. /**
  35081. * Specifies if there should be a separate pass for culling
  35082. */
  35083. this.separateCullingPass = false;
  35084. /**
  35085. * Stores the state specifing if fog should be enabled
  35086. */
  35087. this._fogEnabled = true;
  35088. /**
  35089. * Stores the size of points
  35090. */
  35091. this.pointSize = 1.0;
  35092. /**
  35093. * Stores the z offset value
  35094. */
  35095. this.zOffset = 0;
  35096. /**
  35097. * Specifies if the material was previously ready
  35098. */
  35099. this._wasPreviouslyReady = false;
  35100. /**
  35101. * Stores the fill mode state
  35102. */
  35103. this._fillMode = Material.TriangleFillMode;
  35104. this.name = name;
  35105. this.id = name || BABYLON.Tools.RandomId();
  35106. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35107. this.uniqueId = this._scene.getUniqueId();
  35108. if (this._scene.useRightHandedSystem) {
  35109. this.sideOrientation = Material.ClockWiseSideOrientation;
  35110. }
  35111. else {
  35112. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35113. }
  35114. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35115. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35116. if (!doNotAdd) {
  35117. this._scene.materials.push(this);
  35118. }
  35119. }
  35120. Object.defineProperty(Material, "TriangleFillMode", {
  35121. /**
  35122. * Returns the triangle fill mode
  35123. */
  35124. get: function () {
  35125. return Material._TriangleFillMode;
  35126. },
  35127. enumerable: true,
  35128. configurable: true
  35129. });
  35130. Object.defineProperty(Material, "WireFrameFillMode", {
  35131. /**
  35132. * Returns the wireframe mode
  35133. */
  35134. get: function () {
  35135. return Material._WireFrameFillMode;
  35136. },
  35137. enumerable: true,
  35138. configurable: true
  35139. });
  35140. Object.defineProperty(Material, "PointFillMode", {
  35141. /**
  35142. * Returns the point fill mode
  35143. */
  35144. get: function () {
  35145. return Material._PointFillMode;
  35146. },
  35147. enumerable: true,
  35148. configurable: true
  35149. });
  35150. Object.defineProperty(Material, "PointListDrawMode", {
  35151. /**
  35152. * Returns the point list draw mode
  35153. */
  35154. get: function () {
  35155. return Material._PointListDrawMode;
  35156. },
  35157. enumerable: true,
  35158. configurable: true
  35159. });
  35160. Object.defineProperty(Material, "LineListDrawMode", {
  35161. /**
  35162. * Returns the line list draw mode
  35163. */
  35164. get: function () {
  35165. return Material._LineListDrawMode;
  35166. },
  35167. enumerable: true,
  35168. configurable: true
  35169. });
  35170. Object.defineProperty(Material, "LineLoopDrawMode", {
  35171. /**
  35172. * Returns the line loop draw mode
  35173. */
  35174. get: function () {
  35175. return Material._LineLoopDrawMode;
  35176. },
  35177. enumerable: true,
  35178. configurable: true
  35179. });
  35180. Object.defineProperty(Material, "LineStripDrawMode", {
  35181. /**
  35182. * Returns the line strip draw mode
  35183. */
  35184. get: function () {
  35185. return Material._LineStripDrawMode;
  35186. },
  35187. enumerable: true,
  35188. configurable: true
  35189. });
  35190. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35191. /**
  35192. * Returns the triangle strip draw mode
  35193. */
  35194. get: function () {
  35195. return Material._TriangleStripDrawMode;
  35196. },
  35197. enumerable: true,
  35198. configurable: true
  35199. });
  35200. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35201. /**
  35202. * Returns the triangle fan draw mode
  35203. */
  35204. get: function () {
  35205. return Material._TriangleFanDrawMode;
  35206. },
  35207. enumerable: true,
  35208. configurable: true
  35209. });
  35210. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35211. /**
  35212. * Returns the clock-wise side orientation
  35213. */
  35214. get: function () {
  35215. return Material._ClockWiseSideOrientation;
  35216. },
  35217. enumerable: true,
  35218. configurable: true
  35219. });
  35220. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35221. /**
  35222. * Returns the counter clock-wise side orientation
  35223. */
  35224. get: function () {
  35225. return Material._CounterClockWiseSideOrientation;
  35226. },
  35227. enumerable: true,
  35228. configurable: true
  35229. });
  35230. Object.defineProperty(Material, "TextureDirtyFlag", {
  35231. /**
  35232. * Returns the dirty texture flag value
  35233. */
  35234. get: function () {
  35235. return Material._TextureDirtyFlag;
  35236. },
  35237. enumerable: true,
  35238. configurable: true
  35239. });
  35240. Object.defineProperty(Material, "LightDirtyFlag", {
  35241. /**
  35242. * Returns the dirty light flag value
  35243. */
  35244. get: function () {
  35245. return Material._LightDirtyFlag;
  35246. },
  35247. enumerable: true,
  35248. configurable: true
  35249. });
  35250. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35251. /**
  35252. * Returns the dirty fresnel flag value
  35253. */
  35254. get: function () {
  35255. return Material._FresnelDirtyFlag;
  35256. },
  35257. enumerable: true,
  35258. configurable: true
  35259. });
  35260. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35261. /**
  35262. * Returns the dirty attributes flag value
  35263. */
  35264. get: function () {
  35265. return Material._AttributesDirtyFlag;
  35266. },
  35267. enumerable: true,
  35268. configurable: true
  35269. });
  35270. Object.defineProperty(Material, "MiscDirtyFlag", {
  35271. /**
  35272. * Returns the dirty misc flag value
  35273. */
  35274. get: function () {
  35275. return Material._MiscDirtyFlag;
  35276. },
  35277. enumerable: true,
  35278. configurable: true
  35279. });
  35280. Object.defineProperty(Material.prototype, "alpha", {
  35281. /**
  35282. * Gets the alpha value of the material
  35283. */
  35284. get: function () {
  35285. return this._alpha;
  35286. },
  35287. /**
  35288. * Sets the alpha value of the material
  35289. */
  35290. set: function (value) {
  35291. if (this._alpha === value) {
  35292. return;
  35293. }
  35294. this._alpha = value;
  35295. this.markAsDirty(Material.MiscDirtyFlag);
  35296. },
  35297. enumerable: true,
  35298. configurable: true
  35299. });
  35300. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35301. /**
  35302. * Gets the back-face culling state
  35303. */
  35304. get: function () {
  35305. return this._backFaceCulling;
  35306. },
  35307. /**
  35308. * Sets the back-face culling state
  35309. */
  35310. set: function (value) {
  35311. if (this._backFaceCulling === value) {
  35312. return;
  35313. }
  35314. this._backFaceCulling = value;
  35315. this.markAsDirty(Material.TextureDirtyFlag);
  35316. },
  35317. enumerable: true,
  35318. configurable: true
  35319. });
  35320. Object.defineProperty(Material.prototype, "onDispose", {
  35321. /**
  35322. * Called during a dispose event
  35323. */
  35324. set: function (callback) {
  35325. if (this._onDisposeObserver) {
  35326. this.onDisposeObservable.remove(this._onDisposeObserver);
  35327. }
  35328. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35329. },
  35330. enumerable: true,
  35331. configurable: true
  35332. });
  35333. Object.defineProperty(Material.prototype, "onBind", {
  35334. /**
  35335. * Called during a bind event
  35336. */
  35337. set: function (callback) {
  35338. if (this._onBindObserver) {
  35339. this.onBindObservable.remove(this._onBindObserver);
  35340. }
  35341. this._onBindObserver = this.onBindObservable.add(callback);
  35342. },
  35343. enumerable: true,
  35344. configurable: true
  35345. });
  35346. Object.defineProperty(Material.prototype, "alphaMode", {
  35347. /**
  35348. * Gets the value of the alpha mode
  35349. */
  35350. get: function () {
  35351. return this._alphaMode;
  35352. },
  35353. /**
  35354. * Sets the value of the alpha mode.
  35355. *
  35356. * | Value | Type | Description |
  35357. * | --- | --- | --- |
  35358. * | 0 | ALPHA_DISABLE | |
  35359. * | 1 | ALPHA_ADD | |
  35360. * | 2 | ALPHA_COMBINE | |
  35361. * | 3 | ALPHA_SUBTRACT | |
  35362. * | 4 | ALPHA_MULTIPLY | |
  35363. * | 5 | ALPHA_MAXIMIZED | |
  35364. * | 6 | ALPHA_ONEONE | |
  35365. * | 7 | ALPHA_PREMULTIPLIED | |
  35366. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35367. * | 9 | ALPHA_INTERPOLATE | |
  35368. * | 10 | ALPHA_SCREENMODE | |
  35369. *
  35370. */
  35371. set: function (value) {
  35372. if (this._alphaMode === value) {
  35373. return;
  35374. }
  35375. this._alphaMode = value;
  35376. this.markAsDirty(Material.TextureDirtyFlag);
  35377. },
  35378. enumerable: true,
  35379. configurable: true
  35380. });
  35381. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35382. /**
  35383. * Gets the depth pre-pass value
  35384. */
  35385. get: function () {
  35386. return this._needDepthPrePass;
  35387. },
  35388. /**
  35389. * Sets the need depth pre-pass value
  35390. */
  35391. set: function (value) {
  35392. if (this._needDepthPrePass === value) {
  35393. return;
  35394. }
  35395. this._needDepthPrePass = value;
  35396. if (this._needDepthPrePass) {
  35397. this.checkReadyOnEveryCall = true;
  35398. }
  35399. },
  35400. enumerable: true,
  35401. configurable: true
  35402. });
  35403. Object.defineProperty(Material.prototype, "fogEnabled", {
  35404. /**
  35405. * Gets the value of the fog enabled state
  35406. */
  35407. get: function () {
  35408. return this._fogEnabled;
  35409. },
  35410. /**
  35411. * Sets the state for enabling fog
  35412. */
  35413. set: function (value) {
  35414. if (this._fogEnabled === value) {
  35415. return;
  35416. }
  35417. this._fogEnabled = value;
  35418. this.markAsDirty(Material.MiscDirtyFlag);
  35419. },
  35420. enumerable: true,
  35421. configurable: true
  35422. });
  35423. Object.defineProperty(Material.prototype, "wireframe", {
  35424. /**
  35425. * Gets a value specifying if wireframe mode is enabled
  35426. */
  35427. get: function () {
  35428. switch (this._fillMode) {
  35429. case Material.WireFrameFillMode:
  35430. case Material.LineListDrawMode:
  35431. case Material.LineLoopDrawMode:
  35432. case Material.LineStripDrawMode:
  35433. return true;
  35434. }
  35435. return this._scene.forceWireframe;
  35436. },
  35437. /**
  35438. * Sets the state of wireframe mode
  35439. */
  35440. set: function (value) {
  35441. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35442. },
  35443. enumerable: true,
  35444. configurable: true
  35445. });
  35446. Object.defineProperty(Material.prototype, "pointsCloud", {
  35447. /**
  35448. * Gets the value specifying if point clouds are enabled
  35449. */
  35450. get: function () {
  35451. switch (this._fillMode) {
  35452. case Material.PointFillMode:
  35453. case Material.PointListDrawMode:
  35454. return true;
  35455. }
  35456. return this._scene.forcePointsCloud;
  35457. },
  35458. /**
  35459. * Sets the state of point cloud mode
  35460. */
  35461. set: function (value) {
  35462. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35463. },
  35464. enumerable: true,
  35465. configurable: true
  35466. });
  35467. Object.defineProperty(Material.prototype, "fillMode", {
  35468. /**
  35469. * Gets the material fill mode
  35470. */
  35471. get: function () {
  35472. return this._fillMode;
  35473. },
  35474. /**
  35475. * Sets the material fill mode
  35476. */
  35477. set: function (value) {
  35478. if (this._fillMode === value) {
  35479. return;
  35480. }
  35481. this._fillMode = value;
  35482. this.markAsDirty(Material.MiscDirtyFlag);
  35483. },
  35484. enumerable: true,
  35485. configurable: true
  35486. });
  35487. /**
  35488. * Returns a string representation of the current material
  35489. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35490. * @returns a string with material information
  35491. */
  35492. Material.prototype.toString = function (fullDetails) {
  35493. var ret = "Name: " + this.name;
  35494. if (fullDetails) {
  35495. }
  35496. return ret;
  35497. };
  35498. /**
  35499. * Gets the class name of the material
  35500. * @returns a string with the class name of the material
  35501. */
  35502. Material.prototype.getClassName = function () {
  35503. return "Material";
  35504. };
  35505. Object.defineProperty(Material.prototype, "isFrozen", {
  35506. /**
  35507. * Specifies if updates for the material been locked
  35508. */
  35509. get: function () {
  35510. return this.checkReadyOnlyOnce;
  35511. },
  35512. enumerable: true,
  35513. configurable: true
  35514. });
  35515. /**
  35516. * Locks updates for the material
  35517. */
  35518. Material.prototype.freeze = function () {
  35519. this.checkReadyOnlyOnce = true;
  35520. };
  35521. /**
  35522. * Unlocks updates for the material
  35523. */
  35524. Material.prototype.unfreeze = function () {
  35525. this.checkReadyOnlyOnce = false;
  35526. };
  35527. /**
  35528. * Specifies if the material is ready to be used
  35529. * @param mesh defines the mesh to check
  35530. * @param useInstances specifies if instances should be used
  35531. * @returns a boolean indicating if the material is ready to be used
  35532. */
  35533. Material.prototype.isReady = function (mesh, useInstances) {
  35534. return true;
  35535. };
  35536. /**
  35537. * Specifies that the submesh is ready to be used
  35538. * @param mesh defines the mesh to check
  35539. * @param subMesh defines which submesh to check
  35540. * @param useInstances specifies that instances should be used
  35541. * @returns a boolean indicating that the submesh is ready or not
  35542. */
  35543. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35544. return false;
  35545. };
  35546. /**
  35547. * Returns the material effect
  35548. * @returns the effect associated with the material
  35549. */
  35550. Material.prototype.getEffect = function () {
  35551. return this._effect;
  35552. };
  35553. /**
  35554. * Returns the current scene
  35555. * @returns a Scene
  35556. */
  35557. Material.prototype.getScene = function () {
  35558. return this._scene;
  35559. };
  35560. /**
  35561. * Specifies if the material will require alpha blending
  35562. * @returns a boolean specifying if alpha blending is needed
  35563. */
  35564. Material.prototype.needAlphaBlending = function () {
  35565. return (this.alpha < 1.0);
  35566. };
  35567. /**
  35568. * Specifies if the mesh will require alpha blending
  35569. * @param mesh defines the mesh to check
  35570. * @returns a boolean specifying if alpha blending is needed for the mesh
  35571. */
  35572. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35573. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35574. };
  35575. /**
  35576. * Specifies if this material should be rendered in alpha test mode
  35577. * @returns a boolean specifying if an alpha test is needed.
  35578. */
  35579. Material.prototype.needAlphaTesting = function () {
  35580. return false;
  35581. };
  35582. /**
  35583. * Gets the texture used for the alpha test
  35584. * @returns the texture to use for alpha testing
  35585. */
  35586. Material.prototype.getAlphaTestTexture = function () {
  35587. return null;
  35588. };
  35589. /**
  35590. * Marks the material to indicate that it needs to be re-calculated
  35591. */
  35592. Material.prototype.markDirty = function () {
  35593. this._wasPreviouslyReady = false;
  35594. };
  35595. /** @hidden */
  35596. Material.prototype._preBind = function (effect, overrideOrientation) {
  35597. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35598. var engine = this._scene.getEngine();
  35599. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35600. var reverse = orientation === Material.ClockWiseSideOrientation;
  35601. engine.enableEffect(effect ? effect : this._effect);
  35602. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35603. return reverse;
  35604. };
  35605. /**
  35606. * Binds the material to the mesh
  35607. * @param world defines the world transformation matrix
  35608. * @param mesh defines the mesh to bind the material to
  35609. */
  35610. Material.prototype.bind = function (world, mesh) {
  35611. };
  35612. /**
  35613. * Binds the submesh to the material
  35614. * @param world defines the world transformation matrix
  35615. * @param mesh defines the mesh containing the submesh
  35616. * @param subMesh defines the submesh to bind the material to
  35617. */
  35618. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35619. };
  35620. /**
  35621. * Binds the world matrix to the material
  35622. * @param world defines the world transformation matrix
  35623. */
  35624. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35625. };
  35626. /**
  35627. * Binds the scene's uniform buffer to the effect.
  35628. * @param effect defines the effect to bind to the scene uniform buffer
  35629. * @param sceneUbo defines the uniform buffer storing scene data
  35630. */
  35631. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35632. sceneUbo.bindToEffect(effect, "Scene");
  35633. };
  35634. /**
  35635. * Binds the view matrix to the effect
  35636. * @param effect defines the effect to bind the view matrix to
  35637. */
  35638. Material.prototype.bindView = function (effect) {
  35639. if (!this._useUBO) {
  35640. effect.setMatrix("view", this.getScene().getViewMatrix());
  35641. }
  35642. else {
  35643. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35644. }
  35645. };
  35646. /**
  35647. * Binds the view projection matrix to the effect
  35648. * @param effect defines the effect to bind the view projection matrix to
  35649. */
  35650. Material.prototype.bindViewProjection = function (effect) {
  35651. if (!this._useUBO) {
  35652. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35653. }
  35654. else {
  35655. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35656. }
  35657. };
  35658. /**
  35659. * Specifies if material alpha testing should be turned on for the mesh
  35660. * @param mesh defines the mesh to check
  35661. */
  35662. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35663. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35664. };
  35665. /**
  35666. * Processes to execute after binding the material to a mesh
  35667. * @param mesh defines the rendered mesh
  35668. */
  35669. Material.prototype._afterBind = function (mesh) {
  35670. this._scene._cachedMaterial = this;
  35671. if (mesh) {
  35672. this._scene._cachedVisibility = mesh.visibility;
  35673. }
  35674. else {
  35675. this._scene._cachedVisibility = 1;
  35676. }
  35677. if (mesh) {
  35678. this.onBindObservable.notifyObservers(mesh);
  35679. }
  35680. if (this.disableDepthWrite) {
  35681. var engine = this._scene.getEngine();
  35682. this._cachedDepthWriteState = engine.getDepthWrite();
  35683. engine.setDepthWrite(false);
  35684. }
  35685. };
  35686. /**
  35687. * Unbinds the material from the mesh
  35688. */
  35689. Material.prototype.unbind = function () {
  35690. this.onUnBindObservable.notifyObservers(this);
  35691. if (this.disableDepthWrite) {
  35692. var engine = this._scene.getEngine();
  35693. engine.setDepthWrite(this._cachedDepthWriteState);
  35694. }
  35695. };
  35696. /**
  35697. * Gets the active textures from the material
  35698. * @returns an array of textures
  35699. */
  35700. Material.prototype.getActiveTextures = function () {
  35701. return [];
  35702. };
  35703. /**
  35704. * Specifies if the material uses a texture
  35705. * @param texture defines the texture to check against the material
  35706. * @returns a boolean specifying if the material uses the texture
  35707. */
  35708. Material.prototype.hasTexture = function (texture) {
  35709. return false;
  35710. };
  35711. /**
  35712. * Makes a duplicate of the material, and gives it a new name
  35713. * @param name defines the new name for the duplicated material
  35714. * @returns the cloned material
  35715. */
  35716. Material.prototype.clone = function (name) {
  35717. return null;
  35718. };
  35719. /**
  35720. * Gets the meshes bound to the material
  35721. * @returns an array of meshes bound to the material
  35722. */
  35723. Material.prototype.getBindedMeshes = function () {
  35724. var result = new Array();
  35725. for (var index = 0; index < this._scene.meshes.length; index++) {
  35726. var mesh = this._scene.meshes[index];
  35727. if (mesh.material === this) {
  35728. result.push(mesh);
  35729. }
  35730. }
  35731. return result;
  35732. };
  35733. /**
  35734. * Force shader compilation
  35735. * @param mesh defines the mesh associated with this material
  35736. * @param onCompiled defines a function to execute once the material is compiled
  35737. * @param options defines the options to configure the compilation
  35738. */
  35739. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35740. var _this = this;
  35741. var localOptions = __assign({ clipPlane: false }, options);
  35742. var subMesh = new BABYLON.BaseSubMesh();
  35743. var scene = this.getScene();
  35744. var checkReady = function () {
  35745. if (!_this._scene || !_this._scene.getEngine()) {
  35746. return;
  35747. }
  35748. if (subMesh._materialDefines) {
  35749. subMesh._materialDefines._renderId = -1;
  35750. }
  35751. var clipPlaneState = scene.clipPlane;
  35752. if (localOptions.clipPlane) {
  35753. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35754. }
  35755. if (_this.storeEffectOnSubMeshes) {
  35756. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35757. if (onCompiled) {
  35758. onCompiled(_this);
  35759. }
  35760. }
  35761. else {
  35762. setTimeout(checkReady, 16);
  35763. }
  35764. }
  35765. else {
  35766. if (_this.isReady(mesh)) {
  35767. if (onCompiled) {
  35768. onCompiled(_this);
  35769. }
  35770. }
  35771. else {
  35772. setTimeout(checkReady, 16);
  35773. }
  35774. }
  35775. if (localOptions.clipPlane) {
  35776. scene.clipPlane = clipPlaneState;
  35777. }
  35778. };
  35779. checkReady();
  35780. };
  35781. /**
  35782. * Force shader compilation
  35783. * @param mesh defines the mesh that will use this material
  35784. * @param options defines additional options for compiling the shaders
  35785. * @returns a promise that resolves when the compilation completes
  35786. */
  35787. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35788. var _this = this;
  35789. return new Promise(function (resolve) {
  35790. _this.forceCompilation(mesh, function () {
  35791. resolve();
  35792. }, options);
  35793. });
  35794. };
  35795. /**
  35796. * Marks a define in the material to indicate that it needs to be re-computed
  35797. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35798. */
  35799. Material.prototype.markAsDirty = function (flag) {
  35800. if (flag & Material.TextureDirtyFlag) {
  35801. this._markAllSubMeshesAsTexturesDirty();
  35802. }
  35803. if (flag & Material.LightDirtyFlag) {
  35804. this._markAllSubMeshesAsLightsDirty();
  35805. }
  35806. if (flag & Material.FresnelDirtyFlag) {
  35807. this._markAllSubMeshesAsFresnelDirty();
  35808. }
  35809. if (flag & Material.AttributesDirtyFlag) {
  35810. this._markAllSubMeshesAsAttributesDirty();
  35811. }
  35812. if (flag & Material.MiscDirtyFlag) {
  35813. this._markAllSubMeshesAsMiscDirty();
  35814. }
  35815. this.getScene().resetCachedMaterial();
  35816. };
  35817. /**
  35818. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35819. * @param func defines a function which checks material defines against the submeshes
  35820. */
  35821. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35822. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35823. var mesh = _a[_i];
  35824. if (!mesh.subMeshes) {
  35825. continue;
  35826. }
  35827. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35828. var subMesh = _c[_b];
  35829. if (subMesh.getMaterial() !== this) {
  35830. continue;
  35831. }
  35832. if (!subMesh._materialDefines) {
  35833. continue;
  35834. }
  35835. func(subMesh._materialDefines);
  35836. }
  35837. }
  35838. };
  35839. /**
  35840. * Indicates that image processing needs to be re-calculated for all submeshes
  35841. */
  35842. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35843. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35844. };
  35845. /**
  35846. * Indicates that textures need to be re-calculated for all submeshes
  35847. */
  35848. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35849. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35850. };
  35851. /**
  35852. * Indicates that fresnel needs to be re-calculated for all submeshes
  35853. */
  35854. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35855. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35856. };
  35857. /**
  35858. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35859. */
  35860. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35861. this._markAllSubMeshesAsDirty(function (defines) {
  35862. defines.markAsFresnelDirty();
  35863. defines.markAsMiscDirty();
  35864. });
  35865. };
  35866. /**
  35867. * Indicates that lights need to be re-calculated for all submeshes
  35868. */
  35869. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35870. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35871. };
  35872. /**
  35873. * Indicates that attributes need to be re-calculated for all submeshes
  35874. */
  35875. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35876. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35877. };
  35878. /**
  35879. * Indicates that misc needs to be re-calculated for all submeshes
  35880. */
  35881. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35882. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35883. };
  35884. /**
  35885. * Indicates that textures and misc need to be re-calculated for all submeshes
  35886. */
  35887. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35888. this._markAllSubMeshesAsDirty(function (defines) {
  35889. defines.markAsTexturesDirty();
  35890. defines.markAsMiscDirty();
  35891. });
  35892. };
  35893. /**
  35894. * Disposes the material
  35895. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35896. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35897. */
  35898. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35899. // Animations
  35900. this.getScene().stopAnimation(this);
  35901. this.getScene().freeProcessedMaterials();
  35902. // Remove from scene
  35903. var index = this._scene.materials.indexOf(this);
  35904. if (index >= 0) {
  35905. this._scene.materials.splice(index, 1);
  35906. }
  35907. // Remove from meshes
  35908. for (index = 0; index < this._scene.meshes.length; index++) {
  35909. var mesh = this._scene.meshes[index];
  35910. if (mesh.material === this) {
  35911. mesh.material = null;
  35912. if (mesh.geometry) {
  35913. var geometry = (mesh.geometry);
  35914. if (this.storeEffectOnSubMeshes) {
  35915. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35916. var subMesh = _a[_i];
  35917. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35918. if (forceDisposeEffect && subMesh._materialEffect) {
  35919. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35920. }
  35921. }
  35922. }
  35923. else {
  35924. geometry._releaseVertexArrayObject(this._effect);
  35925. }
  35926. }
  35927. }
  35928. }
  35929. this._uniformBuffer.dispose();
  35930. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35931. if (forceDisposeEffect && this._effect) {
  35932. if (!this.storeEffectOnSubMeshes) {
  35933. this._scene.getEngine()._releaseEffect(this._effect);
  35934. }
  35935. this._effect = null;
  35936. }
  35937. // Callback
  35938. this.onDisposeObservable.notifyObservers(this);
  35939. this.onDisposeObservable.clear();
  35940. this.onBindObservable.clear();
  35941. this.onUnBindObservable.clear();
  35942. };
  35943. /**
  35944. * Serializes this material
  35945. * @returns the serialized material object
  35946. */
  35947. Material.prototype.serialize = function () {
  35948. return BABYLON.SerializationHelper.Serialize(this);
  35949. };
  35950. /**
  35951. * Creates a MultiMaterial from parsed MultiMaterial data.
  35952. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35953. * @param scene defines the hosting scene
  35954. * @returns a new MultiMaterial
  35955. */
  35956. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35957. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35958. multiMaterial.id = parsedMultiMaterial.id;
  35959. if (BABYLON.Tags) {
  35960. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35961. }
  35962. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35963. var subMatId = parsedMultiMaterial.materials[matIndex];
  35964. if (subMatId) {
  35965. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35966. }
  35967. else {
  35968. multiMaterial.subMaterials.push(null);
  35969. }
  35970. }
  35971. return multiMaterial;
  35972. };
  35973. /**
  35974. * Creates a material from parsed material data
  35975. * @param parsedMaterial defines parsed material data
  35976. * @param scene defines the hosting scene
  35977. * @param rootUrl defines the root URL to use to load textures
  35978. * @returns a new material
  35979. */
  35980. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35981. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35982. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35983. }
  35984. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35985. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35986. if (!BABYLON.LegacyPBRMaterial) {
  35987. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35988. return;
  35989. }
  35990. }
  35991. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35992. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35993. };
  35994. // Triangle views
  35995. Material._TriangleFillMode = 0;
  35996. Material._WireFrameFillMode = 1;
  35997. Material._PointFillMode = 2;
  35998. // Draw modes
  35999. Material._PointListDrawMode = 3;
  36000. Material._LineListDrawMode = 4;
  36001. Material._LineLoopDrawMode = 5;
  36002. Material._LineStripDrawMode = 6;
  36003. Material._TriangleStripDrawMode = 7;
  36004. Material._TriangleFanDrawMode = 8;
  36005. /**
  36006. * Stores the clock-wise side orientation
  36007. */
  36008. Material._ClockWiseSideOrientation = 0;
  36009. /**
  36010. * Stores the counter clock-wise side orientation
  36011. */
  36012. Material._CounterClockWiseSideOrientation = 1;
  36013. /**
  36014. * The dirty texture flag value
  36015. */
  36016. Material._TextureDirtyFlag = 1;
  36017. /**
  36018. * The dirty light flag value
  36019. */
  36020. Material._LightDirtyFlag = 2;
  36021. /**
  36022. * The dirty fresnel flag value
  36023. */
  36024. Material._FresnelDirtyFlag = 4;
  36025. /**
  36026. * The dirty attribute flag value
  36027. */
  36028. Material._AttributesDirtyFlag = 8;
  36029. /**
  36030. * The dirty misc flag value
  36031. */
  36032. Material._MiscDirtyFlag = 16;
  36033. __decorate([
  36034. BABYLON.serialize()
  36035. ], Material.prototype, "id", void 0);
  36036. __decorate([
  36037. BABYLON.serialize()
  36038. ], Material.prototype, "uniqueId", void 0);
  36039. __decorate([
  36040. BABYLON.serialize()
  36041. ], Material.prototype, "name", void 0);
  36042. __decorate([
  36043. BABYLON.serialize()
  36044. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36045. __decorate([
  36046. BABYLON.serialize()
  36047. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36048. __decorate([
  36049. BABYLON.serialize()
  36050. ], Material.prototype, "state", void 0);
  36051. __decorate([
  36052. BABYLON.serialize("alpha")
  36053. ], Material.prototype, "_alpha", void 0);
  36054. __decorate([
  36055. BABYLON.serialize("backFaceCulling")
  36056. ], Material.prototype, "_backFaceCulling", void 0);
  36057. __decorate([
  36058. BABYLON.serialize()
  36059. ], Material.prototype, "sideOrientation", void 0);
  36060. __decorate([
  36061. BABYLON.serialize("alphaMode")
  36062. ], Material.prototype, "_alphaMode", void 0);
  36063. __decorate([
  36064. BABYLON.serialize()
  36065. ], Material.prototype, "_needDepthPrePass", void 0);
  36066. __decorate([
  36067. BABYLON.serialize()
  36068. ], Material.prototype, "disableDepthWrite", void 0);
  36069. __decorate([
  36070. BABYLON.serialize()
  36071. ], Material.prototype, "forceDepthWrite", void 0);
  36072. __decorate([
  36073. BABYLON.serialize()
  36074. ], Material.prototype, "separateCullingPass", void 0);
  36075. __decorate([
  36076. BABYLON.serialize("fogEnabled")
  36077. ], Material.prototype, "_fogEnabled", void 0);
  36078. __decorate([
  36079. BABYLON.serialize()
  36080. ], Material.prototype, "pointSize", void 0);
  36081. __decorate([
  36082. BABYLON.serialize()
  36083. ], Material.prototype, "zOffset", void 0);
  36084. __decorate([
  36085. BABYLON.serialize()
  36086. ], Material.prototype, "wireframe", null);
  36087. __decorate([
  36088. BABYLON.serialize()
  36089. ], Material.prototype, "pointsCloud", null);
  36090. __decorate([
  36091. BABYLON.serialize()
  36092. ], Material.prototype, "fillMode", null);
  36093. return Material;
  36094. }());
  36095. BABYLON.Material = Material;
  36096. })(BABYLON || (BABYLON = {}));
  36097. //# sourceMappingURL=babylon.material.js.map
  36098. var BABYLON;
  36099. (function (BABYLON) {
  36100. var UniformBuffer = /** @class */ (function () {
  36101. /**
  36102. * Uniform buffer objects.
  36103. *
  36104. * Handles blocks of uniform on the GPU.
  36105. *
  36106. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36107. *
  36108. * For more information, please refer to :
  36109. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36110. */
  36111. function UniformBuffer(engine, data, dynamic) {
  36112. this._engine = engine;
  36113. this._noUBO = !engine.supportsUniformBuffers;
  36114. this._dynamic = dynamic;
  36115. this._data = data || [];
  36116. this._uniformLocations = {};
  36117. this._uniformSizes = {};
  36118. this._uniformLocationPointer = 0;
  36119. this._needSync = false;
  36120. if (this._noUBO) {
  36121. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36122. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36123. this.updateFloat = this._updateFloatForEffect;
  36124. this.updateFloat2 = this._updateFloat2ForEffect;
  36125. this.updateFloat3 = this._updateFloat3ForEffect;
  36126. this.updateFloat4 = this._updateFloat4ForEffect;
  36127. this.updateMatrix = this._updateMatrixForEffect;
  36128. this.updateVector3 = this._updateVector3ForEffect;
  36129. this.updateVector4 = this._updateVector4ForEffect;
  36130. this.updateColor3 = this._updateColor3ForEffect;
  36131. this.updateColor4 = this._updateColor4ForEffect;
  36132. }
  36133. else {
  36134. this._engine._uniformBuffers.push(this);
  36135. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36136. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36137. this.updateFloat = this._updateFloatForUniform;
  36138. this.updateFloat2 = this._updateFloat2ForUniform;
  36139. this.updateFloat3 = this._updateFloat3ForUniform;
  36140. this.updateFloat4 = this._updateFloat4ForUniform;
  36141. this.updateMatrix = this._updateMatrixForUniform;
  36142. this.updateVector3 = this._updateVector3ForUniform;
  36143. this.updateVector4 = this._updateVector4ForUniform;
  36144. this.updateColor3 = this._updateColor3ForUniform;
  36145. this.updateColor4 = this._updateColor4ForUniform;
  36146. }
  36147. }
  36148. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36149. // Properties
  36150. /**
  36151. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36152. * or just falling back on setUniformXXX calls.
  36153. */
  36154. get: function () {
  36155. return !this._noUBO;
  36156. },
  36157. enumerable: true,
  36158. configurable: true
  36159. });
  36160. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36161. /**
  36162. * Indicates if the WebGL underlying uniform buffer is in sync
  36163. * with the javascript cache data.
  36164. */
  36165. get: function () {
  36166. return !this._needSync;
  36167. },
  36168. enumerable: true,
  36169. configurable: true
  36170. });
  36171. /**
  36172. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36173. * Also, a dynamic UniformBuffer will disable cache verification and always
  36174. * update the underlying WebGL uniform buffer to the GPU.
  36175. */
  36176. UniformBuffer.prototype.isDynamic = function () {
  36177. return this._dynamic !== undefined;
  36178. };
  36179. /**
  36180. * The data cache on JS side.
  36181. */
  36182. UniformBuffer.prototype.getData = function () {
  36183. return this._bufferData;
  36184. };
  36185. /**
  36186. * The underlying WebGL Uniform buffer.
  36187. */
  36188. UniformBuffer.prototype.getBuffer = function () {
  36189. return this._buffer;
  36190. };
  36191. /**
  36192. * std140 layout specifies how to align data within an UBO structure.
  36193. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36194. * for specs.
  36195. */
  36196. UniformBuffer.prototype._fillAlignment = function (size) {
  36197. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36198. // and 4x4 matrices
  36199. // TODO : change if other types are used
  36200. var alignment;
  36201. if (size <= 2) {
  36202. alignment = size;
  36203. }
  36204. else {
  36205. alignment = 4;
  36206. }
  36207. if ((this._uniformLocationPointer % alignment) !== 0) {
  36208. var oldPointer = this._uniformLocationPointer;
  36209. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36210. var diff = this._uniformLocationPointer - oldPointer;
  36211. for (var i = 0; i < diff; i++) {
  36212. this._data.push(0);
  36213. }
  36214. }
  36215. };
  36216. /**
  36217. * Adds an uniform in the buffer.
  36218. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36219. * for the layout to be correct !
  36220. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36221. * @param {number|number[]} size Data size, or data directly.
  36222. */
  36223. UniformBuffer.prototype.addUniform = function (name, size) {
  36224. if (this._noUBO) {
  36225. return;
  36226. }
  36227. if (this._uniformLocations[name] !== undefined) {
  36228. // Already existing uniform
  36229. return;
  36230. }
  36231. // This function must be called in the order of the shader layout !
  36232. // size can be the size of the uniform, or data directly
  36233. var data;
  36234. if (size instanceof Array) {
  36235. data = size;
  36236. size = data.length;
  36237. }
  36238. else {
  36239. size = size;
  36240. data = [];
  36241. // Fill with zeros
  36242. for (var i = 0; i < size; i++) {
  36243. data.push(0);
  36244. }
  36245. }
  36246. this._fillAlignment(size);
  36247. this._uniformSizes[name] = size;
  36248. this._uniformLocations[name] = this._uniformLocationPointer;
  36249. this._uniformLocationPointer += size;
  36250. for (var i = 0; i < size; i++) {
  36251. this._data.push(data[i]);
  36252. }
  36253. this._needSync = true;
  36254. };
  36255. /**
  36256. * Wrapper for addUniform.
  36257. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36258. * @param {Matrix} mat A 4x4 matrix.
  36259. */
  36260. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36261. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36262. };
  36263. /**
  36264. * Wrapper for addUniform.
  36265. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36266. * @param {number} x
  36267. * @param {number} y
  36268. */
  36269. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36270. var temp = [x, y];
  36271. this.addUniform(name, temp);
  36272. };
  36273. /**
  36274. * Wrapper for addUniform.
  36275. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36276. * @param {number} x
  36277. * @param {number} y
  36278. * @param {number} z
  36279. */
  36280. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36281. var temp = [x, y, z];
  36282. this.addUniform(name, temp);
  36283. };
  36284. /**
  36285. * Wrapper for addUniform.
  36286. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36287. * @param {Color3} color
  36288. */
  36289. UniformBuffer.prototype.addColor3 = function (name, color) {
  36290. var temp = new Array();
  36291. color.toArray(temp);
  36292. this.addUniform(name, temp);
  36293. };
  36294. /**
  36295. * Wrapper for addUniform.
  36296. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36297. * @param {Color3} color
  36298. * @param {number} alpha
  36299. */
  36300. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36301. var temp = new Array();
  36302. color.toArray(temp);
  36303. temp.push(alpha);
  36304. this.addUniform(name, temp);
  36305. };
  36306. /**
  36307. * Wrapper for addUniform.
  36308. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36309. * @param {Vector3} vector
  36310. */
  36311. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36312. var temp = new Array();
  36313. vector.toArray(temp);
  36314. this.addUniform(name, temp);
  36315. };
  36316. /**
  36317. * Wrapper for addUniform.
  36318. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36319. */
  36320. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36321. this.addUniform(name, 12);
  36322. };
  36323. /**
  36324. * Wrapper for addUniform.
  36325. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36326. */
  36327. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36328. this.addUniform(name, 8);
  36329. };
  36330. /**
  36331. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36332. */
  36333. UniformBuffer.prototype.create = function () {
  36334. if (this._noUBO) {
  36335. return;
  36336. }
  36337. if (this._buffer) {
  36338. return; // nothing to do
  36339. }
  36340. // See spec, alignment must be filled as a vec4
  36341. this._fillAlignment(4);
  36342. this._bufferData = new Float32Array(this._data);
  36343. this._rebuild();
  36344. this._needSync = true;
  36345. };
  36346. UniformBuffer.prototype._rebuild = function () {
  36347. if (this._noUBO) {
  36348. return;
  36349. }
  36350. if (this._dynamic) {
  36351. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36352. }
  36353. else {
  36354. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36355. }
  36356. };
  36357. /**
  36358. * Updates the WebGL Uniform Buffer on the GPU.
  36359. * If the `dynamic` flag is set to true, no cache comparison is done.
  36360. * Otherwise, the buffer will be updated only if the cache differs.
  36361. */
  36362. UniformBuffer.prototype.update = function () {
  36363. if (!this._buffer) {
  36364. this.create();
  36365. return;
  36366. }
  36367. if (!this._dynamic && !this._needSync) {
  36368. return;
  36369. }
  36370. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36371. this._needSync = false;
  36372. };
  36373. /**
  36374. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36375. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36376. * @param {number[]|Float32Array} data Flattened data
  36377. * @param {number} size Size of the data.
  36378. */
  36379. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36380. var location = this._uniformLocations[uniformName];
  36381. if (location === undefined) {
  36382. if (this._buffer) {
  36383. // Cannot add an uniform if the buffer is already created
  36384. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36385. return;
  36386. }
  36387. this.addUniform(uniformName, size);
  36388. location = this._uniformLocations[uniformName];
  36389. }
  36390. if (!this._buffer) {
  36391. this.create();
  36392. }
  36393. if (!this._dynamic) {
  36394. // Cache for static uniform buffers
  36395. var changed = false;
  36396. for (var i = 0; i < size; i++) {
  36397. if (this._bufferData[location + i] !== data[i]) {
  36398. changed = true;
  36399. this._bufferData[location + i] = data[i];
  36400. }
  36401. }
  36402. this._needSync = this._needSync || changed;
  36403. }
  36404. else {
  36405. // No cache for dynamic
  36406. for (var i = 0; i < size; i++) {
  36407. this._bufferData[location + i] = data[i];
  36408. }
  36409. }
  36410. };
  36411. // Update methods
  36412. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36413. // To match std140, matrix must be realigned
  36414. for (var i = 0; i < 3; i++) {
  36415. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36416. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36417. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36418. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36419. }
  36420. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36421. };
  36422. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36423. this._currentEffect.setMatrix3x3(name, matrix);
  36424. };
  36425. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36426. this._currentEffect.setMatrix2x2(name, matrix);
  36427. };
  36428. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36429. // To match std140, matrix must be realigned
  36430. for (var i = 0; i < 2; i++) {
  36431. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36432. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36433. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36434. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36435. }
  36436. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36437. };
  36438. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36439. this._currentEffect.setFloat(name, x);
  36440. };
  36441. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36442. UniformBuffer._tempBuffer[0] = x;
  36443. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36444. };
  36445. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36446. if (suffix === void 0) { suffix = ""; }
  36447. this._currentEffect.setFloat2(name + suffix, x, y);
  36448. };
  36449. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36450. if (suffix === void 0) { suffix = ""; }
  36451. UniformBuffer._tempBuffer[0] = x;
  36452. UniformBuffer._tempBuffer[1] = y;
  36453. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36454. };
  36455. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36456. if (suffix === void 0) { suffix = ""; }
  36457. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36458. };
  36459. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36460. if (suffix === void 0) { suffix = ""; }
  36461. UniformBuffer._tempBuffer[0] = x;
  36462. UniformBuffer._tempBuffer[1] = y;
  36463. UniformBuffer._tempBuffer[2] = z;
  36464. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36465. };
  36466. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36467. if (suffix === void 0) { suffix = ""; }
  36468. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36469. };
  36470. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36471. if (suffix === void 0) { suffix = ""; }
  36472. UniformBuffer._tempBuffer[0] = x;
  36473. UniformBuffer._tempBuffer[1] = y;
  36474. UniformBuffer._tempBuffer[2] = z;
  36475. UniformBuffer._tempBuffer[3] = w;
  36476. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36477. };
  36478. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36479. this._currentEffect.setMatrix(name, mat);
  36480. };
  36481. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36482. this.updateUniform(name, mat.toArray(), 16);
  36483. };
  36484. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36485. this._currentEffect.setVector3(name, vector);
  36486. };
  36487. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36488. vector.toArray(UniformBuffer._tempBuffer);
  36489. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36490. };
  36491. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36492. this._currentEffect.setVector4(name, vector);
  36493. };
  36494. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36495. vector.toArray(UniformBuffer._tempBuffer);
  36496. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36497. };
  36498. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36499. if (suffix === void 0) { suffix = ""; }
  36500. this._currentEffect.setColor3(name + suffix, color);
  36501. };
  36502. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36503. if (suffix === void 0) { suffix = ""; }
  36504. color.toArray(UniformBuffer._tempBuffer);
  36505. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36506. };
  36507. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36508. if (suffix === void 0) { suffix = ""; }
  36509. this._currentEffect.setColor4(name + suffix, color, alpha);
  36510. };
  36511. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36512. if (suffix === void 0) { suffix = ""; }
  36513. color.toArray(UniformBuffer._tempBuffer);
  36514. UniformBuffer._tempBuffer[3] = alpha;
  36515. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36516. };
  36517. /**
  36518. * Sets a sampler uniform on the effect.
  36519. * @param {string} name Name of the sampler.
  36520. * @param {Texture} texture
  36521. */
  36522. UniformBuffer.prototype.setTexture = function (name, texture) {
  36523. this._currentEffect.setTexture(name, texture);
  36524. };
  36525. /**
  36526. * Directly updates the value of the uniform in the cache AND on the GPU.
  36527. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36528. * @param {number[]|Float32Array} data Flattened data
  36529. */
  36530. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36531. this.updateUniform(uniformName, data, data.length);
  36532. this.update();
  36533. };
  36534. /**
  36535. * Binds this uniform buffer to an effect.
  36536. * @param {Effect} effect
  36537. * @param {string} name Name of the uniform block in the shader.
  36538. */
  36539. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36540. this._currentEffect = effect;
  36541. if (this._noUBO || !this._buffer) {
  36542. return;
  36543. }
  36544. effect.bindUniformBuffer(this._buffer, name);
  36545. };
  36546. /**
  36547. * Disposes the uniform buffer.
  36548. */
  36549. UniformBuffer.prototype.dispose = function () {
  36550. if (this._noUBO) {
  36551. return;
  36552. }
  36553. var index = this._engine._uniformBuffers.indexOf(this);
  36554. if (index !== -1) {
  36555. this._engine._uniformBuffers.splice(index, 1);
  36556. }
  36557. if (!this._buffer) {
  36558. return;
  36559. }
  36560. if (this._engine._releaseBuffer(this._buffer)) {
  36561. this._buffer = null;
  36562. }
  36563. };
  36564. // Pool for avoiding memory leaks
  36565. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36566. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36567. return UniformBuffer;
  36568. }());
  36569. BABYLON.UniformBuffer = UniformBuffer;
  36570. })(BABYLON || (BABYLON = {}));
  36571. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36572. var BABYLON;
  36573. (function (BABYLON) {
  36574. /**
  36575. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36576. */
  36577. var VertexData = /** @class */ (function () {
  36578. function VertexData() {
  36579. }
  36580. /**
  36581. * Uses the passed data array to set the set the values for the specified kind of data
  36582. * @param data a linear array of floating numbers
  36583. * @param kind the type of data that is being set, eg positions, colors etc
  36584. */
  36585. VertexData.prototype.set = function (data, kind) {
  36586. switch (kind) {
  36587. case BABYLON.VertexBuffer.PositionKind:
  36588. this.positions = data;
  36589. break;
  36590. case BABYLON.VertexBuffer.NormalKind:
  36591. this.normals = data;
  36592. break;
  36593. case BABYLON.VertexBuffer.TangentKind:
  36594. this.tangents = data;
  36595. break;
  36596. case BABYLON.VertexBuffer.UVKind:
  36597. this.uvs = data;
  36598. break;
  36599. case BABYLON.VertexBuffer.UV2Kind:
  36600. this.uvs2 = data;
  36601. break;
  36602. case BABYLON.VertexBuffer.UV3Kind:
  36603. this.uvs3 = data;
  36604. break;
  36605. case BABYLON.VertexBuffer.UV4Kind:
  36606. this.uvs4 = data;
  36607. break;
  36608. case BABYLON.VertexBuffer.UV5Kind:
  36609. this.uvs5 = data;
  36610. break;
  36611. case BABYLON.VertexBuffer.UV6Kind:
  36612. this.uvs6 = data;
  36613. break;
  36614. case BABYLON.VertexBuffer.ColorKind:
  36615. this.colors = data;
  36616. break;
  36617. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36618. this.matricesIndices = data;
  36619. break;
  36620. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36621. this.matricesWeights = data;
  36622. break;
  36623. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36624. this.matricesIndicesExtra = data;
  36625. break;
  36626. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36627. this.matricesWeightsExtra = data;
  36628. break;
  36629. }
  36630. };
  36631. /**
  36632. * Associates the vertexData to the passed Mesh.
  36633. * Sets it as updatable or not (default `false`)
  36634. * @param mesh the mesh the vertexData is applied to
  36635. * @param updatable when used and having the value true allows new data to update the vertexData
  36636. * @returns the VertexData
  36637. */
  36638. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36639. this._applyTo(mesh, updatable);
  36640. return this;
  36641. };
  36642. /**
  36643. * Associates the vertexData to the passed Geometry.
  36644. * Sets it as updatable or not (default `false`)
  36645. * @param geometry the geometry the vertexData is applied to
  36646. * @param updatable when used and having the value true allows new data to update the vertexData
  36647. * @returns VertexData
  36648. */
  36649. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36650. this._applyTo(geometry, updatable);
  36651. return this;
  36652. };
  36653. /**
  36654. * Updates the associated mesh
  36655. * @param mesh the mesh to be updated
  36656. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36657. * @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
  36658. * @returns VertexData
  36659. */
  36660. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36661. this._update(mesh);
  36662. return this;
  36663. };
  36664. /**
  36665. * Updates the associated geometry
  36666. * @param geometry the geometry to be updated
  36667. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36668. * @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
  36669. * @returns VertexData.
  36670. */
  36671. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36672. this._update(geometry);
  36673. return this;
  36674. };
  36675. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36676. if (updatable === void 0) { updatable = false; }
  36677. if (this.positions) {
  36678. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36679. }
  36680. if (this.normals) {
  36681. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36682. }
  36683. if (this.tangents) {
  36684. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36685. }
  36686. if (this.uvs) {
  36687. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36688. }
  36689. if (this.uvs2) {
  36690. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36691. }
  36692. if (this.uvs3) {
  36693. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36694. }
  36695. if (this.uvs4) {
  36696. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36697. }
  36698. if (this.uvs5) {
  36699. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36700. }
  36701. if (this.uvs6) {
  36702. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36703. }
  36704. if (this.colors) {
  36705. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36706. }
  36707. if (this.matricesIndices) {
  36708. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36709. }
  36710. if (this.matricesWeights) {
  36711. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36712. }
  36713. if (this.matricesIndicesExtra) {
  36714. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36715. }
  36716. if (this.matricesWeightsExtra) {
  36717. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36718. }
  36719. if (this.indices) {
  36720. meshOrGeometry.setIndices(this.indices, null, updatable);
  36721. }
  36722. else {
  36723. meshOrGeometry.setIndices([], null);
  36724. }
  36725. return this;
  36726. };
  36727. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36728. if (this.positions) {
  36729. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36730. }
  36731. if (this.normals) {
  36732. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36733. }
  36734. if (this.tangents) {
  36735. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36736. }
  36737. if (this.uvs) {
  36738. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36739. }
  36740. if (this.uvs2) {
  36741. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36742. }
  36743. if (this.uvs3) {
  36744. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36745. }
  36746. if (this.uvs4) {
  36747. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36748. }
  36749. if (this.uvs5) {
  36750. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36751. }
  36752. if (this.uvs6) {
  36753. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36754. }
  36755. if (this.colors) {
  36756. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36757. }
  36758. if (this.matricesIndices) {
  36759. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36760. }
  36761. if (this.matricesWeights) {
  36762. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36763. }
  36764. if (this.matricesIndicesExtra) {
  36765. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36766. }
  36767. if (this.matricesWeightsExtra) {
  36768. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36769. }
  36770. if (this.indices) {
  36771. meshOrGeometry.setIndices(this.indices, null);
  36772. }
  36773. return this;
  36774. };
  36775. /**
  36776. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36777. * @param matrix the transforming matrix
  36778. * @returns the VertexData
  36779. */
  36780. VertexData.prototype.transform = function (matrix) {
  36781. var transformed = BABYLON.Vector3.Zero();
  36782. var index;
  36783. if (this.positions) {
  36784. var position = BABYLON.Vector3.Zero();
  36785. for (index = 0; index < this.positions.length; index += 3) {
  36786. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36787. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36788. this.positions[index] = transformed.x;
  36789. this.positions[index + 1] = transformed.y;
  36790. this.positions[index + 2] = transformed.z;
  36791. }
  36792. }
  36793. if (this.normals) {
  36794. var normal = BABYLON.Vector3.Zero();
  36795. for (index = 0; index < this.normals.length; index += 3) {
  36796. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36797. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36798. this.normals[index] = transformed.x;
  36799. this.normals[index + 1] = transformed.y;
  36800. this.normals[index + 2] = transformed.z;
  36801. }
  36802. }
  36803. if (this.tangents) {
  36804. var tangent = BABYLON.Vector4.Zero();
  36805. var tangentTransformed = BABYLON.Vector4.Zero();
  36806. for (index = 0; index < this.tangents.length; index += 4) {
  36807. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36808. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36809. this.tangents[index] = tangentTransformed.x;
  36810. this.tangents[index + 1] = tangentTransformed.y;
  36811. this.tangents[index + 2] = tangentTransformed.z;
  36812. this.tangents[index + 3] = tangentTransformed.w;
  36813. }
  36814. }
  36815. return this;
  36816. };
  36817. /**
  36818. * Merges the passed VertexData into the current one
  36819. * @param other the VertexData to be merged into the current one
  36820. * @returns the modified VertexData
  36821. */
  36822. VertexData.prototype.merge = function (other) {
  36823. this._validate();
  36824. other._validate();
  36825. if (!this.normals !== !other.normals ||
  36826. !this.tangents !== !other.tangents ||
  36827. !this.uvs !== !other.uvs ||
  36828. !this.uvs2 !== !other.uvs2 ||
  36829. !this.uvs3 !== !other.uvs3 ||
  36830. !this.uvs4 !== !other.uvs4 ||
  36831. !this.uvs5 !== !other.uvs5 ||
  36832. !this.uvs6 !== !other.uvs6 ||
  36833. !this.colors !== !other.colors ||
  36834. !this.matricesIndices !== !other.matricesIndices ||
  36835. !this.matricesWeights !== !other.matricesWeights ||
  36836. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36837. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36838. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36839. }
  36840. if (other.indices) {
  36841. if (!this.indices) {
  36842. this.indices = [];
  36843. }
  36844. var offset = this.positions ? this.positions.length / 3 : 0;
  36845. for (var index = 0; index < other.indices.length; index++) {
  36846. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36847. this.indices.push(other.indices[index] + offset);
  36848. }
  36849. }
  36850. this.positions = this._mergeElement(this.positions, other.positions);
  36851. this.normals = this._mergeElement(this.normals, other.normals);
  36852. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36853. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36854. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36855. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36856. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36857. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36858. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36859. this.colors = this._mergeElement(this.colors, other.colors);
  36860. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36861. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36862. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36863. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36864. return this;
  36865. };
  36866. VertexData.prototype._mergeElement = function (source, other) {
  36867. if (!source) {
  36868. return other;
  36869. }
  36870. if (!other) {
  36871. return source;
  36872. }
  36873. var len = other.length + source.length;
  36874. var isSrcTypedArray = source instanceof Float32Array;
  36875. var isOthTypedArray = other instanceof Float32Array;
  36876. // use non-loop method when the source is Float32Array
  36877. if (isSrcTypedArray) {
  36878. var ret32 = new Float32Array(len);
  36879. ret32.set(source);
  36880. ret32.set(other, source.length);
  36881. return ret32;
  36882. // source is number[], when other is also use concat
  36883. }
  36884. else if (!isOthTypedArray) {
  36885. return source.concat(other);
  36886. // source is a number[], but other is a Float32Array, loop required
  36887. }
  36888. else {
  36889. var ret = source.slice(0); // copy source to a separate array
  36890. for (var i = 0, len = other.length; i < len; i++) {
  36891. ret.push(other[i]);
  36892. }
  36893. return ret;
  36894. }
  36895. };
  36896. VertexData.prototype._validate = function () {
  36897. if (!this.positions) {
  36898. throw new Error("Positions are required");
  36899. }
  36900. var getElementCount = function (kind, values) {
  36901. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36902. if ((values.length % stride) !== 0) {
  36903. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36904. }
  36905. return values.length / stride;
  36906. };
  36907. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36908. var validateElementCount = function (kind, values) {
  36909. var elementCount = getElementCount(kind, values);
  36910. if (elementCount !== positionsElementCount) {
  36911. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36912. }
  36913. };
  36914. if (this.normals)
  36915. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36916. if (this.tangents)
  36917. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36918. if (this.uvs)
  36919. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36920. if (this.uvs2)
  36921. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36922. if (this.uvs3)
  36923. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36924. if (this.uvs4)
  36925. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36926. if (this.uvs5)
  36927. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36928. if (this.uvs6)
  36929. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36930. if (this.colors)
  36931. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36932. if (this.matricesIndices)
  36933. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36934. if (this.matricesWeights)
  36935. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36936. if (this.matricesIndicesExtra)
  36937. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36938. if (this.matricesWeightsExtra)
  36939. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36940. };
  36941. /**
  36942. * Serializes the VertexData
  36943. * @returns a serialized object
  36944. */
  36945. VertexData.prototype.serialize = function () {
  36946. var serializationObject = this.serialize();
  36947. if (this.positions) {
  36948. serializationObject.positions = this.positions;
  36949. }
  36950. if (this.normals) {
  36951. serializationObject.normals = this.normals;
  36952. }
  36953. if (this.tangents) {
  36954. serializationObject.tangents = this.tangents;
  36955. }
  36956. if (this.uvs) {
  36957. serializationObject.uvs = this.uvs;
  36958. }
  36959. if (this.uvs2) {
  36960. serializationObject.uvs2 = this.uvs2;
  36961. }
  36962. if (this.uvs3) {
  36963. serializationObject.uvs3 = this.uvs3;
  36964. }
  36965. if (this.uvs4) {
  36966. serializationObject.uvs4 = this.uvs4;
  36967. }
  36968. if (this.uvs5) {
  36969. serializationObject.uvs5 = this.uvs5;
  36970. }
  36971. if (this.uvs6) {
  36972. serializationObject.uvs6 = this.uvs6;
  36973. }
  36974. if (this.colors) {
  36975. serializationObject.colors = this.colors;
  36976. }
  36977. if (this.matricesIndices) {
  36978. serializationObject.matricesIndices = this.matricesIndices;
  36979. serializationObject.matricesIndices._isExpanded = true;
  36980. }
  36981. if (this.matricesWeights) {
  36982. serializationObject.matricesWeights = this.matricesWeights;
  36983. }
  36984. if (this.matricesIndicesExtra) {
  36985. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36986. serializationObject.matricesIndicesExtra._isExpanded = true;
  36987. }
  36988. if (this.matricesWeightsExtra) {
  36989. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36990. }
  36991. serializationObject.indices = this.indices;
  36992. return serializationObject;
  36993. };
  36994. // Statics
  36995. /**
  36996. * Extracts the vertexData from a mesh
  36997. * @param mesh the mesh from which to extract the VertexData
  36998. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36999. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37000. * @returns the object VertexData associated to the passed mesh
  37001. */
  37002. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  37003. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  37004. };
  37005. /**
  37006. * Extracts the vertexData from the geometry
  37007. * @param geometry the geometry from which to extract the VertexData
  37008. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  37009. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37010. * @returns the object VertexData associated to the passed mesh
  37011. */
  37012. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  37013. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  37014. };
  37015. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  37016. var result = new VertexData();
  37017. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37018. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  37019. }
  37020. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37021. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  37022. }
  37023. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37024. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  37025. }
  37026. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37027. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  37028. }
  37029. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37030. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37031. }
  37032. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37033. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  37034. }
  37035. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37036. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37037. }
  37038. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37039. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37040. }
  37041. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37042. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37043. }
  37044. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37045. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37046. }
  37047. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37048. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37049. }
  37050. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37051. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37052. }
  37053. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37054. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37055. }
  37056. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37057. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37058. }
  37059. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37060. return result;
  37061. };
  37062. /**
  37063. * Creates the VertexData for a Ribbon
  37064. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37065. * * pathArray array of paths, each of which an array of successive Vector3
  37066. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37067. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37068. * * 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
  37069. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37070. * * 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)
  37071. * * 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)
  37072. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37073. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37074. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37075. * @returns the VertexData of the ribbon
  37076. */
  37077. VertexData.CreateRibbon = function (options) {
  37078. var pathArray = options.pathArray;
  37079. var closeArray = options.closeArray || false;
  37080. var closePath = options.closePath || false;
  37081. var invertUV = options.invertUV || false;
  37082. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37083. var offset = options.offset || defaultOffset;
  37084. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37085. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37086. var customUV = options.uvs;
  37087. var customColors = options.colors;
  37088. var positions = [];
  37089. var indices = [];
  37090. var normals = [];
  37091. var uvs = [];
  37092. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37093. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37094. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37095. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37096. var minlg; // minimal length among all paths from pathArray
  37097. var lg = []; // array of path lengths : nb of vertex per path
  37098. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37099. var p; // path iterator
  37100. var i; // point iterator
  37101. var j; // point iterator
  37102. // if single path in pathArray
  37103. if (pathArray.length < 2) {
  37104. var ar1 = [];
  37105. var ar2 = [];
  37106. for (i = 0; i < pathArray[0].length - offset; i++) {
  37107. ar1.push(pathArray[0][i]);
  37108. ar2.push(pathArray[0][i + offset]);
  37109. }
  37110. pathArray = [ar1, ar2];
  37111. }
  37112. // positions and horizontal distances (u)
  37113. var idc = 0;
  37114. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37115. var path;
  37116. var l;
  37117. minlg = pathArray[0].length;
  37118. var vectlg;
  37119. var dist;
  37120. for (p = 0; p < pathArray.length; p++) {
  37121. uTotalDistance[p] = 0;
  37122. us[p] = [0];
  37123. path = pathArray[p];
  37124. l = path.length;
  37125. minlg = (minlg < l) ? minlg : l;
  37126. j = 0;
  37127. while (j < l) {
  37128. positions.push(path[j].x, path[j].y, path[j].z);
  37129. if (j > 0) {
  37130. vectlg = path[j].subtract(path[j - 1]).length();
  37131. dist = vectlg + uTotalDistance[p];
  37132. us[p].push(dist);
  37133. uTotalDistance[p] = dist;
  37134. }
  37135. j++;
  37136. }
  37137. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37138. j--;
  37139. positions.push(path[0].x, path[0].y, path[0].z);
  37140. vectlg = path[j].subtract(path[0]).length();
  37141. dist = vectlg + uTotalDistance[p];
  37142. us[p].push(dist);
  37143. uTotalDistance[p] = dist;
  37144. }
  37145. lg[p] = l + closePathCorr;
  37146. idx[p] = idc;
  37147. idc += (l + closePathCorr);
  37148. }
  37149. // vertical distances (v)
  37150. var path1;
  37151. var path2;
  37152. var vertex1 = null;
  37153. var vertex2 = null;
  37154. for (i = 0; i < minlg + closePathCorr; i++) {
  37155. vTotalDistance[i] = 0;
  37156. vs[i] = [0];
  37157. for (p = 0; p < pathArray.length - 1; p++) {
  37158. path1 = pathArray[p];
  37159. path2 = pathArray[p + 1];
  37160. if (i === minlg) { // closePath
  37161. vertex1 = path1[0];
  37162. vertex2 = path2[0];
  37163. }
  37164. else {
  37165. vertex1 = path1[i];
  37166. vertex2 = path2[i];
  37167. }
  37168. vectlg = vertex2.subtract(vertex1).length();
  37169. dist = vectlg + vTotalDistance[i];
  37170. vs[i].push(dist);
  37171. vTotalDistance[i] = dist;
  37172. }
  37173. if (closeArray && vertex2 && vertex1) {
  37174. path1 = pathArray[p];
  37175. path2 = pathArray[0];
  37176. if (i === minlg) { // closePath
  37177. vertex2 = path2[0];
  37178. }
  37179. vectlg = vertex2.subtract(vertex1).length();
  37180. dist = vectlg + vTotalDistance[i];
  37181. vTotalDistance[i] = dist;
  37182. }
  37183. }
  37184. // uvs
  37185. var u;
  37186. var v;
  37187. if (customUV) {
  37188. for (p = 0; p < customUV.length; p++) {
  37189. uvs.push(customUV[p].x, customUV[p].y);
  37190. }
  37191. }
  37192. else {
  37193. for (p = 0; p < pathArray.length; p++) {
  37194. for (i = 0; i < minlg + closePathCorr; i++) {
  37195. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37196. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37197. if (invertUV) {
  37198. uvs.push(v, u);
  37199. }
  37200. else {
  37201. uvs.push(u, v);
  37202. }
  37203. }
  37204. }
  37205. }
  37206. // indices
  37207. p = 0; // path index
  37208. var pi = 0; // positions array index
  37209. var l1 = lg[p] - 1; // path1 length
  37210. var l2 = lg[p + 1] - 1; // path2 length
  37211. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37212. var shft = idx[1] - idx[0]; // shift
  37213. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37214. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37215. // 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
  37216. indices.push(pi, pi + shft, pi + 1);
  37217. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37218. pi += 1;
  37219. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37220. p++;
  37221. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37222. shft = idx[0] - idx[p];
  37223. l1 = lg[p] - 1;
  37224. l2 = lg[0] - 1;
  37225. }
  37226. else {
  37227. shft = idx[p + 1] - idx[p];
  37228. l1 = lg[p] - 1;
  37229. l2 = lg[p + 1] - 1;
  37230. }
  37231. pi = idx[p];
  37232. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37233. }
  37234. }
  37235. // normals
  37236. VertexData.ComputeNormals(positions, indices, normals);
  37237. if (closePath) { // update both the first and last vertex normals to their average value
  37238. var indexFirst = 0;
  37239. var indexLast = 0;
  37240. for (p = 0; p < pathArray.length; p++) {
  37241. indexFirst = idx[p] * 3;
  37242. if (p + 1 < pathArray.length) {
  37243. indexLast = (idx[p + 1] - 1) * 3;
  37244. }
  37245. else {
  37246. indexLast = normals.length - 3;
  37247. }
  37248. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37249. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37250. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37251. normals[indexLast] = normals[indexFirst];
  37252. normals[indexLast + 1] = normals[indexFirst + 1];
  37253. normals[indexLast + 2] = normals[indexFirst + 2];
  37254. }
  37255. }
  37256. // sides
  37257. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37258. // Colors
  37259. var colors = null;
  37260. if (customColors) {
  37261. colors = new Float32Array(customColors.length * 4);
  37262. for (var c = 0; c < customColors.length; c++) {
  37263. colors[c * 4] = customColors[c].r;
  37264. colors[c * 4 + 1] = customColors[c].g;
  37265. colors[c * 4 + 2] = customColors[c].b;
  37266. colors[c * 4 + 3] = customColors[c].a;
  37267. }
  37268. }
  37269. // Result
  37270. var vertexData = new VertexData();
  37271. var positions32 = new Float32Array(positions);
  37272. var normals32 = new Float32Array(normals);
  37273. var uvs32 = new Float32Array(uvs);
  37274. vertexData.indices = indices;
  37275. vertexData.positions = positions32;
  37276. vertexData.normals = normals32;
  37277. vertexData.uvs = uvs32;
  37278. if (colors) {
  37279. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37280. }
  37281. if (closePath) {
  37282. vertexData._idx = idx;
  37283. }
  37284. return vertexData;
  37285. };
  37286. /**
  37287. * Creates the VertexData for a box
  37288. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37289. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37290. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37291. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37292. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37293. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37294. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37295. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37296. * * 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)
  37297. * * 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)
  37298. * @returns the VertexData of the box
  37299. */
  37300. VertexData.CreateBox = function (options) {
  37301. var normalsSource = [
  37302. new BABYLON.Vector3(0, 0, 1),
  37303. new BABYLON.Vector3(0, 0, -1),
  37304. new BABYLON.Vector3(1, 0, 0),
  37305. new BABYLON.Vector3(-1, 0, 0),
  37306. new BABYLON.Vector3(0, 1, 0),
  37307. new BABYLON.Vector3(0, -1, 0)
  37308. ];
  37309. var indices = [];
  37310. var positions = [];
  37311. var normals = [];
  37312. var uvs = [];
  37313. var width = options.width || options.size || 1;
  37314. var height = options.height || options.size || 1;
  37315. var depth = options.depth || options.size || 1;
  37316. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37317. var faceUV = options.faceUV || new Array(6);
  37318. var faceColors = options.faceColors;
  37319. var colors = [];
  37320. // default face colors and UV if undefined
  37321. for (var f = 0; f < 6; f++) {
  37322. if (faceUV[f] === undefined) {
  37323. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37324. }
  37325. if (faceColors && faceColors[f] === undefined) {
  37326. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37327. }
  37328. }
  37329. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37330. // Create each face in turn.
  37331. for (var index = 0; index < normalsSource.length; index++) {
  37332. var normal = normalsSource[index];
  37333. // Get two vectors perpendicular to the face normal and to each other.
  37334. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37335. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37336. // Six indices (two triangles) per face.
  37337. var verticesLength = positions.length / 3;
  37338. indices.push(verticesLength);
  37339. indices.push(verticesLength + 1);
  37340. indices.push(verticesLength + 2);
  37341. indices.push(verticesLength);
  37342. indices.push(verticesLength + 2);
  37343. indices.push(verticesLength + 3);
  37344. // Four vertices per face.
  37345. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37346. positions.push(vertex.x, vertex.y, vertex.z);
  37347. normals.push(normal.x, normal.y, normal.z);
  37348. uvs.push(faceUV[index].z, faceUV[index].w);
  37349. if (faceColors) {
  37350. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37351. }
  37352. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37353. positions.push(vertex.x, vertex.y, vertex.z);
  37354. normals.push(normal.x, normal.y, normal.z);
  37355. uvs.push(faceUV[index].x, faceUV[index].w);
  37356. if (faceColors) {
  37357. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37358. }
  37359. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37360. positions.push(vertex.x, vertex.y, vertex.z);
  37361. normals.push(normal.x, normal.y, normal.z);
  37362. uvs.push(faceUV[index].x, faceUV[index].y);
  37363. if (faceColors) {
  37364. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37365. }
  37366. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37367. positions.push(vertex.x, vertex.y, vertex.z);
  37368. normals.push(normal.x, normal.y, normal.z);
  37369. uvs.push(faceUV[index].z, faceUV[index].y);
  37370. if (faceColors) {
  37371. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37372. }
  37373. }
  37374. // sides
  37375. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37376. // Result
  37377. var vertexData = new VertexData();
  37378. vertexData.indices = indices;
  37379. vertexData.positions = positions;
  37380. vertexData.normals = normals;
  37381. vertexData.uvs = uvs;
  37382. if (faceColors) {
  37383. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37384. vertexData.colors = totalColors;
  37385. }
  37386. return vertexData;
  37387. };
  37388. /**
  37389. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37390. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37391. * * segments sets the number of horizontal strips optional, default 32
  37392. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37393. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37394. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37395. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37396. * * 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
  37397. * * 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
  37398. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37399. * * 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)
  37400. * * 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)
  37401. * @returns the VertexData of the ellipsoid
  37402. */
  37403. VertexData.CreateSphere = function (options) {
  37404. var segments = options.segments || 32;
  37405. var diameterX = options.diameterX || options.diameter || 1;
  37406. var diameterY = options.diameterY || options.diameter || 1;
  37407. var diameterZ = options.diameterZ || options.diameter || 1;
  37408. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37409. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37410. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37411. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37412. var totalZRotationSteps = 2 + segments;
  37413. var totalYRotationSteps = 2 * totalZRotationSteps;
  37414. var indices = [];
  37415. var positions = [];
  37416. var normals = [];
  37417. var uvs = [];
  37418. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37419. var normalizedZ = zRotationStep / totalZRotationSteps;
  37420. var angleZ = normalizedZ * Math.PI * slice;
  37421. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37422. var normalizedY = yRotationStep / totalYRotationSteps;
  37423. var angleY = normalizedY * Math.PI * 2 * arc;
  37424. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37425. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37426. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37427. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37428. var vertex = complete.multiply(radius);
  37429. var normal = complete.divide(radius).normalize();
  37430. positions.push(vertex.x, vertex.y, vertex.z);
  37431. normals.push(normal.x, normal.y, normal.z);
  37432. uvs.push(normalizedY, normalizedZ);
  37433. }
  37434. if (zRotationStep > 0) {
  37435. var verticesCount = positions.length / 3;
  37436. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37437. indices.push((firstIndex));
  37438. indices.push((firstIndex + 1));
  37439. indices.push(firstIndex + totalYRotationSteps + 1);
  37440. indices.push((firstIndex + totalYRotationSteps + 1));
  37441. indices.push((firstIndex + 1));
  37442. indices.push((firstIndex + totalYRotationSteps + 2));
  37443. }
  37444. }
  37445. }
  37446. // Sides
  37447. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37448. // Result
  37449. var vertexData = new VertexData();
  37450. vertexData.indices = indices;
  37451. vertexData.positions = positions;
  37452. vertexData.normals = normals;
  37453. vertexData.uvs = uvs;
  37454. return vertexData;
  37455. };
  37456. /**
  37457. * Creates the VertexData for a cylinder, cone or prism
  37458. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37459. * * height sets the height (y direction) of the cylinder, optional, default 2
  37460. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37461. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37462. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37463. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37464. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37465. * * 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
  37466. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37467. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37468. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37469. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37470. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37471. * * 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)
  37472. * * 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)
  37473. * @returns the VertexData of the cylinder, cone or prism
  37474. */
  37475. VertexData.CreateCylinder = function (options) {
  37476. var height = options.height || 2;
  37477. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37478. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37479. var tessellation = options.tessellation || 24;
  37480. var subdivisions = options.subdivisions || 1;
  37481. var hasRings = options.hasRings ? true : false;
  37482. var enclose = options.enclose ? true : false;
  37483. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37484. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37485. var faceUV = options.faceUV || new Array(3);
  37486. var faceColors = options.faceColors;
  37487. // default face colors and UV if undefined
  37488. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37489. var ringNb = (hasRings) ? subdivisions : 1;
  37490. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37491. var f;
  37492. for (f = 0; f < surfaceNb; f++) {
  37493. if (faceColors && faceColors[f] === undefined) {
  37494. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37495. }
  37496. }
  37497. for (f = 0; f < surfaceNb; f++) {
  37498. if (faceUV && faceUV[f] === undefined) {
  37499. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37500. }
  37501. }
  37502. var indices = new Array();
  37503. var positions = new Array();
  37504. var normals = new Array();
  37505. var uvs = new Array();
  37506. var colors = new Array();
  37507. var angle_step = Math.PI * 2 * arc / tessellation;
  37508. var angle;
  37509. var h;
  37510. var radius;
  37511. var tan = (diameterBottom - diameterTop) / 2 / height;
  37512. var ringVertex = BABYLON.Vector3.Zero();
  37513. var ringNormal = BABYLON.Vector3.Zero();
  37514. var ringFirstVertex = BABYLON.Vector3.Zero();
  37515. var ringFirstNormal = BABYLON.Vector3.Zero();
  37516. var quadNormal = BABYLON.Vector3.Zero();
  37517. var Y = BABYLON.Axis.Y;
  37518. // positions, normals, uvs
  37519. var i;
  37520. var j;
  37521. var r;
  37522. var ringIdx = 1;
  37523. var s = 1; // surface index
  37524. var cs = 0;
  37525. var v = 0;
  37526. for (i = 0; i <= subdivisions; i++) {
  37527. h = i / subdivisions;
  37528. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37529. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37530. for (r = 0; r < ringIdx; r++) {
  37531. if (hasRings) {
  37532. s += r;
  37533. }
  37534. if (enclose) {
  37535. s += 2 * r;
  37536. }
  37537. for (j = 0; j <= tessellation; j++) {
  37538. angle = j * angle_step;
  37539. // position
  37540. ringVertex.x = Math.cos(-angle) * radius;
  37541. ringVertex.y = -height / 2 + h * height;
  37542. ringVertex.z = Math.sin(-angle) * radius;
  37543. // normal
  37544. if (diameterTop === 0 && i === subdivisions) {
  37545. // if no top cap, reuse former normals
  37546. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37547. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37548. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37549. }
  37550. else {
  37551. ringNormal.x = ringVertex.x;
  37552. ringNormal.z = ringVertex.z;
  37553. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37554. ringNormal.normalize();
  37555. }
  37556. // keep first ring vertex values for enclose
  37557. if (j === 0) {
  37558. ringFirstVertex.copyFrom(ringVertex);
  37559. ringFirstNormal.copyFrom(ringNormal);
  37560. }
  37561. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37562. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37563. if (hasRings) {
  37564. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37565. }
  37566. else {
  37567. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37568. }
  37569. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37570. if (faceColors) {
  37571. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37572. }
  37573. }
  37574. // if enclose, add four vertices and their dedicated normals
  37575. if (arc !== 1 && enclose) {
  37576. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37577. positions.push(0, ringVertex.y, 0);
  37578. positions.push(0, ringVertex.y, 0);
  37579. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37580. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37581. quadNormal.normalize();
  37582. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37583. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37584. quadNormal.normalize();
  37585. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37586. if (hasRings) {
  37587. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37588. }
  37589. else {
  37590. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37591. }
  37592. uvs.push(faceUV[s + 1].x, v);
  37593. uvs.push(faceUV[s + 1].z, v);
  37594. if (hasRings) {
  37595. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37596. }
  37597. else {
  37598. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37599. }
  37600. uvs.push(faceUV[s + 2].x, v);
  37601. uvs.push(faceUV[s + 2].z, v);
  37602. if (faceColors) {
  37603. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37604. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37605. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37606. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37607. }
  37608. }
  37609. if (cs !== s) {
  37610. cs = s;
  37611. }
  37612. }
  37613. }
  37614. // indices
  37615. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37616. var s;
  37617. i = 0;
  37618. for (s = 0; s < subdivisions; s++) {
  37619. var i0 = 0;
  37620. var i1 = 0;
  37621. var i2 = 0;
  37622. var i3 = 0;
  37623. for (j = 0; j < tessellation; j++) {
  37624. i0 = i * (e + 1) + j;
  37625. i1 = (i + 1) * (e + 1) + j;
  37626. i2 = i * (e + 1) + (j + 1);
  37627. i3 = (i + 1) * (e + 1) + (j + 1);
  37628. indices.push(i0, i1, i2);
  37629. indices.push(i3, i2, i1);
  37630. }
  37631. if (arc !== 1 && enclose) { // if enclose, add two quads
  37632. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37633. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37634. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37635. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37636. }
  37637. i = (hasRings) ? (i + 2) : (i + 1);
  37638. }
  37639. // Caps
  37640. var createCylinderCap = function (isTop) {
  37641. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37642. if (radius === 0) {
  37643. return;
  37644. }
  37645. // Cap positions, normals & uvs
  37646. var angle;
  37647. var circleVector;
  37648. var i;
  37649. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37650. var c = null;
  37651. if (faceColors) {
  37652. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37653. }
  37654. // cap center
  37655. var vbase = positions.length / 3;
  37656. var offset = isTop ? height / 2 : -height / 2;
  37657. var center = new BABYLON.Vector3(0, offset, 0);
  37658. positions.push(center.x, center.y, center.z);
  37659. normals.push(0, isTop ? 1 : -1, 0);
  37660. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37661. if (c) {
  37662. colors.push(c.r, c.g, c.b, c.a);
  37663. }
  37664. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37665. for (i = 0; i <= tessellation; i++) {
  37666. angle = Math.PI * 2 * i * arc / tessellation;
  37667. var cos = Math.cos(-angle);
  37668. var sin = Math.sin(-angle);
  37669. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37670. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37671. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37672. normals.push(0, isTop ? 1 : -1, 0);
  37673. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37674. if (c) {
  37675. colors.push(c.r, c.g, c.b, c.a);
  37676. }
  37677. }
  37678. // Cap indices
  37679. for (i = 0; i < tessellation; i++) {
  37680. if (!isTop) {
  37681. indices.push(vbase);
  37682. indices.push(vbase + (i + 1));
  37683. indices.push(vbase + (i + 2));
  37684. }
  37685. else {
  37686. indices.push(vbase);
  37687. indices.push(vbase + (i + 2));
  37688. indices.push(vbase + (i + 1));
  37689. }
  37690. }
  37691. };
  37692. // add caps to geometry
  37693. createCylinderCap(false);
  37694. createCylinderCap(true);
  37695. // Sides
  37696. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37697. var vertexData = new VertexData();
  37698. vertexData.indices = indices;
  37699. vertexData.positions = positions;
  37700. vertexData.normals = normals;
  37701. vertexData.uvs = uvs;
  37702. if (faceColors) {
  37703. vertexData.colors = colors;
  37704. }
  37705. return vertexData;
  37706. };
  37707. /**
  37708. * Creates the VertexData for a torus
  37709. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37710. * * diameter the diameter of the torus, optional default 1
  37711. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37712. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37713. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37714. * * 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)
  37715. * * 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)
  37716. * @returns the VertexData of the torus
  37717. */
  37718. VertexData.CreateTorus = function (options) {
  37719. var indices = [];
  37720. var positions = [];
  37721. var normals = [];
  37722. var uvs = [];
  37723. var diameter = options.diameter || 1;
  37724. var thickness = options.thickness || 0.5;
  37725. var tessellation = options.tessellation || 16;
  37726. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37727. var stride = tessellation + 1;
  37728. for (var i = 0; i <= tessellation; i++) {
  37729. var u = i / tessellation;
  37730. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37731. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37732. for (var j = 0; j <= tessellation; j++) {
  37733. var v = 1 - j / tessellation;
  37734. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37735. var dx = Math.cos(innerAngle);
  37736. var dy = Math.sin(innerAngle);
  37737. // Create a vertex.
  37738. var normal = new BABYLON.Vector3(dx, dy, 0);
  37739. var position = normal.scale(thickness / 2);
  37740. var textureCoordinate = new BABYLON.Vector2(u, v);
  37741. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37742. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37743. positions.push(position.x, position.y, position.z);
  37744. normals.push(normal.x, normal.y, normal.z);
  37745. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37746. // And create indices for two triangles.
  37747. var nextI = (i + 1) % stride;
  37748. var nextJ = (j + 1) % stride;
  37749. indices.push(i * stride + j);
  37750. indices.push(i * stride + nextJ);
  37751. indices.push(nextI * stride + j);
  37752. indices.push(i * stride + nextJ);
  37753. indices.push(nextI * stride + nextJ);
  37754. indices.push(nextI * stride + j);
  37755. }
  37756. }
  37757. // Sides
  37758. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37759. // Result
  37760. var vertexData = new VertexData();
  37761. vertexData.indices = indices;
  37762. vertexData.positions = positions;
  37763. vertexData.normals = normals;
  37764. vertexData.uvs = uvs;
  37765. return vertexData;
  37766. };
  37767. /**
  37768. * Creates the VertexData of the LineSystem
  37769. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37770. * - lines an array of lines, each line being an array of successive Vector3
  37771. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37772. * @returns the VertexData of the LineSystem
  37773. */
  37774. VertexData.CreateLineSystem = function (options) {
  37775. var indices = [];
  37776. var positions = [];
  37777. var lines = options.lines;
  37778. var colors = options.colors;
  37779. var vertexColors = [];
  37780. var idx = 0;
  37781. for (var l = 0; l < lines.length; l++) {
  37782. var points = lines[l];
  37783. for (var index = 0; index < points.length; index++) {
  37784. positions.push(points[index].x, points[index].y, points[index].z);
  37785. if (colors) {
  37786. var color = colors[l];
  37787. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37788. }
  37789. if (index > 0) {
  37790. indices.push(idx - 1);
  37791. indices.push(idx);
  37792. }
  37793. idx++;
  37794. }
  37795. }
  37796. var vertexData = new VertexData();
  37797. vertexData.indices = indices;
  37798. vertexData.positions = positions;
  37799. if (colors) {
  37800. vertexData.colors = vertexColors;
  37801. }
  37802. return vertexData;
  37803. };
  37804. /**
  37805. * Create the VertexData for a DashedLines
  37806. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37807. * - points an array successive Vector3
  37808. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37809. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37810. * - dashNb the intended total number of dashes, optional, default 200
  37811. * @returns the VertexData for the DashedLines
  37812. */
  37813. VertexData.CreateDashedLines = function (options) {
  37814. var dashSize = options.dashSize || 3;
  37815. var gapSize = options.gapSize || 1;
  37816. var dashNb = options.dashNb || 200;
  37817. var points = options.points;
  37818. var positions = new Array();
  37819. var indices = new Array();
  37820. var curvect = BABYLON.Vector3.Zero();
  37821. var lg = 0;
  37822. var nb = 0;
  37823. var shft = 0;
  37824. var dashshft = 0;
  37825. var curshft = 0;
  37826. var idx = 0;
  37827. var i = 0;
  37828. for (i = 0; i < points.length - 1; i++) {
  37829. points[i + 1].subtractToRef(points[i], curvect);
  37830. lg += curvect.length();
  37831. }
  37832. shft = lg / dashNb;
  37833. dashshft = dashSize * shft / (dashSize + gapSize);
  37834. for (i = 0; i < points.length - 1; i++) {
  37835. points[i + 1].subtractToRef(points[i], curvect);
  37836. nb = Math.floor(curvect.length() / shft);
  37837. curvect.normalize();
  37838. for (var j = 0; j < nb; j++) {
  37839. curshft = shft * j;
  37840. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37841. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37842. indices.push(idx, idx + 1);
  37843. idx += 2;
  37844. }
  37845. }
  37846. // Result
  37847. var vertexData = new VertexData();
  37848. vertexData.positions = positions;
  37849. vertexData.indices = indices;
  37850. return vertexData;
  37851. };
  37852. /**
  37853. * Creates the VertexData for a Ground
  37854. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37855. * - width the width (x direction) of the ground, optional, default 1
  37856. * - height the height (z direction) of the ground, optional, default 1
  37857. * - subdivisions the number of subdivisions per side, optional, default 1
  37858. * @returns the VertexData of the Ground
  37859. */
  37860. VertexData.CreateGround = function (options) {
  37861. var indices = [];
  37862. var positions = [];
  37863. var normals = [];
  37864. var uvs = [];
  37865. var row, col;
  37866. var width = options.width || 1;
  37867. var height = options.height || 1;
  37868. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37869. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37870. for (row = 0; row <= subdivisionsY; row++) {
  37871. for (col = 0; col <= subdivisionsX; col++) {
  37872. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37873. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37874. positions.push(position.x, position.y, position.z);
  37875. normals.push(normal.x, normal.y, normal.z);
  37876. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37877. }
  37878. }
  37879. for (row = 0; row < subdivisionsY; row++) {
  37880. for (col = 0; col < subdivisionsX; col++) {
  37881. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37882. indices.push(col + 1 + row * (subdivisionsX + 1));
  37883. indices.push(col + row * (subdivisionsX + 1));
  37884. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37885. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37886. indices.push(col + row * (subdivisionsX + 1));
  37887. }
  37888. }
  37889. // Result
  37890. var vertexData = new VertexData();
  37891. vertexData.indices = indices;
  37892. vertexData.positions = positions;
  37893. vertexData.normals = normals;
  37894. vertexData.uvs = uvs;
  37895. return vertexData;
  37896. };
  37897. /**
  37898. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37899. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37900. * * xmin the ground minimum X coordinate, optional, default -1
  37901. * * zmin the ground minimum Z coordinate, optional, default -1
  37902. * * xmax the ground maximum X coordinate, optional, default 1
  37903. * * zmax the ground maximum Z coordinate, optional, default 1
  37904. * * 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}
  37905. * * 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}
  37906. * @returns the VertexData of the TiledGround
  37907. */
  37908. VertexData.CreateTiledGround = function (options) {
  37909. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37910. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37911. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37912. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37913. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37914. var precision = options.precision || { w: 1, h: 1 };
  37915. var indices = new Array();
  37916. var positions = new Array();
  37917. var normals = new Array();
  37918. var uvs = new Array();
  37919. var row, col, tileRow, tileCol;
  37920. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37921. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37922. precision.w = (precision.w < 1) ? 1 : precision.w;
  37923. precision.h = (precision.h < 1) ? 1 : precision.h;
  37924. var tileSize = {
  37925. 'w': (xmax - xmin) / subdivisions.w,
  37926. 'h': (zmax - zmin) / subdivisions.h
  37927. };
  37928. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37929. // Indices
  37930. var base = positions.length / 3;
  37931. var rowLength = precision.w + 1;
  37932. for (row = 0; row < precision.h; row++) {
  37933. for (col = 0; col < precision.w; col++) {
  37934. var square = [
  37935. base + col + row * rowLength,
  37936. base + (col + 1) + row * rowLength,
  37937. base + (col + 1) + (row + 1) * rowLength,
  37938. base + col + (row + 1) * rowLength
  37939. ];
  37940. indices.push(square[1]);
  37941. indices.push(square[2]);
  37942. indices.push(square[3]);
  37943. indices.push(square[0]);
  37944. indices.push(square[1]);
  37945. indices.push(square[3]);
  37946. }
  37947. }
  37948. // Position, normals and uvs
  37949. var position = BABYLON.Vector3.Zero();
  37950. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37951. for (row = 0; row <= precision.h; row++) {
  37952. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37953. for (col = 0; col <= precision.w; col++) {
  37954. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37955. position.y = 0;
  37956. positions.push(position.x, position.y, position.z);
  37957. normals.push(normal.x, normal.y, normal.z);
  37958. uvs.push(col / precision.w, row / precision.h);
  37959. }
  37960. }
  37961. }
  37962. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37963. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37964. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37965. }
  37966. }
  37967. // Result
  37968. var vertexData = new VertexData();
  37969. vertexData.indices = indices;
  37970. vertexData.positions = positions;
  37971. vertexData.normals = normals;
  37972. vertexData.uvs = uvs;
  37973. return vertexData;
  37974. };
  37975. /**
  37976. * Creates the VertexData of the Ground designed from a heightmap
  37977. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37978. * * width the width (x direction) of the ground
  37979. * * height the height (z direction) of the ground
  37980. * * subdivisions the number of subdivisions per side
  37981. * * minHeight the minimum altitude on the ground, optional, default 0
  37982. * * maxHeight the maximum altitude on the ground, optional default 1
  37983. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37984. * * buffer the array holding the image color data
  37985. * * bufferWidth the width of image
  37986. * * bufferHeight the height of image
  37987. * @returns the VertexData of the Ground designed from a heightmap
  37988. */
  37989. VertexData.CreateGroundFromHeightMap = function (options) {
  37990. var indices = [];
  37991. var positions = [];
  37992. var normals = [];
  37993. var uvs = [];
  37994. var row, col;
  37995. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37996. // Vertices
  37997. for (row = 0; row <= options.subdivisions; row++) {
  37998. for (col = 0; col <= options.subdivisions; col++) {
  37999. 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));
  38000. // Compute height
  38001. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38002. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38003. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  38004. var r = options.buffer[pos] / 255.0;
  38005. var g = options.buffer[pos + 1] / 255.0;
  38006. var b = options.buffer[pos + 2] / 255.0;
  38007. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38008. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38009. // Add vertex
  38010. positions.push(position.x, position.y, position.z);
  38011. normals.push(0, 0, 0);
  38012. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38013. }
  38014. }
  38015. // Indices
  38016. for (row = 0; row < options.subdivisions; row++) {
  38017. for (col = 0; col < options.subdivisions; col++) {
  38018. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38019. indices.push(col + 1 + row * (options.subdivisions + 1));
  38020. indices.push(col + row * (options.subdivisions + 1));
  38021. indices.push(col + (row + 1) * (options.subdivisions + 1));
  38022. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38023. indices.push(col + row * (options.subdivisions + 1));
  38024. }
  38025. }
  38026. // Normals
  38027. VertexData.ComputeNormals(positions, indices, normals);
  38028. // Result
  38029. var vertexData = new VertexData();
  38030. vertexData.indices = indices;
  38031. vertexData.positions = positions;
  38032. vertexData.normals = normals;
  38033. vertexData.uvs = uvs;
  38034. return vertexData;
  38035. };
  38036. /**
  38037. * Creates the VertexData for a Plane
  38038. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  38039. * * size sets the width and height of the plane to the value of size, optional default 1
  38040. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38041. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  38042. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38043. * * 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)
  38044. * * 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)
  38045. * @returns the VertexData of the box
  38046. */
  38047. VertexData.CreatePlane = function (options) {
  38048. var indices = [];
  38049. var positions = [];
  38050. var normals = [];
  38051. var uvs = [];
  38052. var width = options.width || options.size || 1;
  38053. var height = options.height || options.size || 1;
  38054. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38055. // Vertices
  38056. var halfWidth = width / 2.0;
  38057. var halfHeight = height / 2.0;
  38058. positions.push(-halfWidth, -halfHeight, 0);
  38059. normals.push(0, 0, -1.0);
  38060. uvs.push(0.0, 0.0);
  38061. positions.push(halfWidth, -halfHeight, 0);
  38062. normals.push(0, 0, -1.0);
  38063. uvs.push(1.0, 0.0);
  38064. positions.push(halfWidth, halfHeight, 0);
  38065. normals.push(0, 0, -1.0);
  38066. uvs.push(1.0, 1.0);
  38067. positions.push(-halfWidth, halfHeight, 0);
  38068. normals.push(0, 0, -1.0);
  38069. uvs.push(0.0, 1.0);
  38070. // Indices
  38071. indices.push(0);
  38072. indices.push(1);
  38073. indices.push(2);
  38074. indices.push(0);
  38075. indices.push(2);
  38076. indices.push(3);
  38077. // Sides
  38078. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38079. // Result
  38080. var vertexData = new VertexData();
  38081. vertexData.indices = indices;
  38082. vertexData.positions = positions;
  38083. vertexData.normals = normals;
  38084. vertexData.uvs = uvs;
  38085. return vertexData;
  38086. };
  38087. /**
  38088. * Creates the VertexData of the Disc or regular Polygon
  38089. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38090. * * radius the radius of the disc, optional default 0.5
  38091. * * tessellation the number of polygon sides, optional, default 64
  38092. * * 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
  38093. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38094. * * 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)
  38095. * * 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)
  38096. * @returns the VertexData of the box
  38097. */
  38098. VertexData.CreateDisc = function (options) {
  38099. var positions = new Array();
  38100. var indices = new Array();
  38101. var normals = new Array();
  38102. var uvs = new Array();
  38103. var radius = options.radius || 0.5;
  38104. var tessellation = options.tessellation || 64;
  38105. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38106. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38107. // positions and uvs
  38108. positions.push(0, 0, 0); // disc center first
  38109. uvs.push(0.5, 0.5);
  38110. var theta = Math.PI * 2 * arc;
  38111. var step = theta / tessellation;
  38112. for (var a = 0; a < theta; a += step) {
  38113. var x = Math.cos(a);
  38114. var y = Math.sin(a);
  38115. var u = (x + 1) / 2;
  38116. var v = (1 - y) / 2;
  38117. positions.push(radius * x, radius * y, 0);
  38118. uvs.push(u, v);
  38119. }
  38120. if (arc === 1) {
  38121. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38122. uvs.push(uvs[2], uvs[3]);
  38123. }
  38124. //indices
  38125. var vertexNb = positions.length / 3;
  38126. for (var i = 1; i < vertexNb - 1; i++) {
  38127. indices.push(i + 1, 0, i);
  38128. }
  38129. // result
  38130. VertexData.ComputeNormals(positions, indices, normals);
  38131. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38132. var vertexData = new VertexData();
  38133. vertexData.indices = indices;
  38134. vertexData.positions = positions;
  38135. vertexData.normals = normals;
  38136. vertexData.uvs = uvs;
  38137. return vertexData;
  38138. };
  38139. /**
  38140. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38141. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38142. * @param polygon a mesh built from polygonTriangulation.build()
  38143. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38144. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38145. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38146. * @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)
  38147. * @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)
  38148. * @returns the VertexData of the Polygon
  38149. */
  38150. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38151. var faceUV = fUV || new Array(3);
  38152. var faceColors = fColors;
  38153. var colors = [];
  38154. // default face colors and UV if undefined
  38155. for (var f = 0; f < 3; f++) {
  38156. if (faceUV[f] === undefined) {
  38157. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38158. }
  38159. if (faceColors && faceColors[f] === undefined) {
  38160. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38161. }
  38162. }
  38163. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38164. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38165. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38166. var indices = polygon.getIndices();
  38167. // set face colours and textures
  38168. var idx = 0;
  38169. var face = 0;
  38170. for (var index = 0; index < normals.length; index += 3) {
  38171. //Edge Face no. 1
  38172. if (Math.abs(normals[index + 1]) < 0.001) {
  38173. face = 1;
  38174. }
  38175. //Top Face no. 0
  38176. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38177. face = 0;
  38178. }
  38179. //Bottom Face no. 2
  38180. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38181. face = 2;
  38182. }
  38183. idx = index / 3;
  38184. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38185. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38186. if (faceColors) {
  38187. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38188. }
  38189. }
  38190. // sides
  38191. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38192. // Result
  38193. var vertexData = new VertexData();
  38194. vertexData.indices = indices;
  38195. vertexData.positions = positions;
  38196. vertexData.normals = normals;
  38197. vertexData.uvs = uvs;
  38198. if (faceColors) {
  38199. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38200. vertexData.colors = totalColors;
  38201. }
  38202. return vertexData;
  38203. };
  38204. /**
  38205. * Creates the VertexData of the IcoSphere
  38206. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38207. * * radius the radius of the IcoSphere, optional default 1
  38208. * * radiusX allows stretching in the x direction, optional, default radius
  38209. * * radiusY allows stretching in the y direction, optional, default radius
  38210. * * radiusZ allows stretching in the z direction, optional, default radius
  38211. * * flat when true creates a flat shaded mesh, optional, default true
  38212. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38213. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38214. * * 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)
  38215. * * 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)
  38216. * @returns the VertexData of the IcoSphere
  38217. */
  38218. VertexData.CreateIcoSphere = function (options) {
  38219. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38220. var radius = options.radius || 1;
  38221. var flat = (options.flat === undefined) ? true : options.flat;
  38222. var subdivisions = options.subdivisions || 4;
  38223. var radiusX = options.radiusX || radius;
  38224. var radiusY = options.radiusY || radius;
  38225. var radiusZ = options.radiusZ || radius;
  38226. var t = (1 + Math.sqrt(5)) / 2;
  38227. // 12 vertex x,y,z
  38228. var ico_vertices = [
  38229. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38230. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38231. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38232. ];
  38233. // index of 3 vertex makes a face of icopshere
  38234. var ico_indices = [
  38235. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38236. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38237. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38238. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38239. ];
  38240. // vertex for uv have aliased position, not for UV
  38241. var vertices_unalias_id = [
  38242. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38243. // vertex alias
  38244. 0,
  38245. 2,
  38246. 3,
  38247. 3,
  38248. 3,
  38249. 4,
  38250. 7,
  38251. 8,
  38252. 9,
  38253. 9,
  38254. 10,
  38255. 11 // 23: B + 12
  38256. ];
  38257. // uv as integer step (not pixels !)
  38258. var ico_vertexuv = [
  38259. 5, 1, 3, 1, 6, 4, 0, 0,
  38260. 5, 3, 4, 2, 2, 2, 4, 0,
  38261. 2, 0, 1, 1, 6, 0, 6, 2,
  38262. // vertex alias (for same vertex on different faces)
  38263. 0, 4,
  38264. 3, 3,
  38265. 4, 4,
  38266. 3, 1,
  38267. 4, 2,
  38268. 4, 4,
  38269. 0, 2,
  38270. 1, 1,
  38271. 2, 2,
  38272. 3, 3,
  38273. 1, 3,
  38274. 2, 4 // 23: B + 12
  38275. ];
  38276. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38277. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38278. // First island of uv mapping
  38279. // v = 4h 3+ 2
  38280. // v = 3h 9+ 4
  38281. // v = 2h 9+ 5 B
  38282. // v = 1h 9 1 0
  38283. // v = 0h 3 8 7 A
  38284. // u = 0 1 2 3 4 5 6 *a
  38285. // Second island of uv mapping
  38286. // v = 4h 0+ B+ 4+
  38287. // v = 3h A+ 2+
  38288. // v = 2h 7+ 6 3+
  38289. // v = 1h 8+ 3+
  38290. // v = 0h
  38291. // u = 0 1 2 3 4 5 6 *a
  38292. // Face layout on texture UV mapping
  38293. // ============
  38294. // \ 4 /\ 16 / ======
  38295. // \ / \ / /\ 11 /
  38296. // \/ 7 \/ / \ /
  38297. // ======= / 10 \/
  38298. // /\ 17 /\ =======
  38299. // / \ / \ \ 15 /\
  38300. // / 8 \/ 12 \ \ / \
  38301. // ============ \/ 6 \
  38302. // \ 18 /\ ============
  38303. // \ / \ \ 5 /\ 0 /
  38304. // \/ 13 \ \ / \ /
  38305. // ======= \/ 1 \/
  38306. // =============
  38307. // /\ 19 /\ 2 /\
  38308. // / \ / \ / \
  38309. // / 14 \/ 9 \/ 3 \
  38310. // ===================
  38311. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38312. var ustep = 138 / 1024;
  38313. var vstep = 239 / 1024;
  38314. var uoffset = 60 / 1024;
  38315. var voffset = 26 / 1024;
  38316. // Second island should have margin, not to touch the first island
  38317. // avoid any borderline artefact in pixel rounding
  38318. var island_u_offset = -40 / 1024;
  38319. var island_v_offset = +20 / 1024;
  38320. // face is either island 0 or 1 :
  38321. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38322. var island = [
  38323. 0, 0, 0, 0, 1,
  38324. 0, 0, 1, 1, 0,
  38325. 0, 0, 1, 1, 0,
  38326. 0, 1, 1, 1, 0 // 15 - 19
  38327. ];
  38328. var indices = new Array();
  38329. var positions = new Array();
  38330. var normals = new Array();
  38331. var uvs = new Array();
  38332. var current_indice = 0;
  38333. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38334. var face_vertex_pos = new Array(3);
  38335. var face_vertex_uv = new Array(3);
  38336. var v012;
  38337. for (v012 = 0; v012 < 3; v012++) {
  38338. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38339. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38340. }
  38341. // create all with normals
  38342. for (var face = 0; face < 20; face++) {
  38343. // 3 vertex per face
  38344. for (v012 = 0; v012 < 3; v012++) {
  38345. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38346. var v_id = ico_indices[3 * face + v012];
  38347. // vertex have 3D position (x,y,z)
  38348. 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]);
  38349. // Normalize to get normal, then scale to radius
  38350. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38351. // uv Coordinates from vertex ID
  38352. 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);
  38353. }
  38354. // Subdivide the face (interpolate pos, norm, uv)
  38355. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38356. // - norm is linear interpolation of vertex corner normal
  38357. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38358. // - uv is linear interpolation
  38359. //
  38360. // Topology is as below for sub-divide by 2
  38361. // vertex shown as v0,v1,v2
  38362. // interp index is i1 to progress in range [v0,v1[
  38363. // interp index is i2 to progress in range [v0,v2[
  38364. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38365. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38366. //
  38367. //
  38368. // i2 v2
  38369. // ^ ^
  38370. // / / \
  38371. // / / \
  38372. // / / \
  38373. // / / (0,1) \
  38374. // / #---------\
  38375. // / / \ (0,0)'/ \
  38376. // / / \ / \
  38377. // / / \ / \
  38378. // / / (0,0) \ / (1,0) \
  38379. // / #---------#---------\
  38380. // v0 v1
  38381. //
  38382. // --------------------> i1
  38383. //
  38384. // interp of (i1,i2):
  38385. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38386. // along i1 : lerp(x0,x1, i1/(S-i2))
  38387. //
  38388. // centroid of triangle is needed to get help normal computation
  38389. // (c1,c2) are used for centroid location
  38390. var interp_vertex = function (i1, i2, c1, c2) {
  38391. // vertex is interpolated from
  38392. // - face_vertex_pos[0..2]
  38393. // - face_vertex_uv[0..2]
  38394. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38395. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38396. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38397. pos_interp.normalize();
  38398. var vertex_normal;
  38399. if (flat) {
  38400. // in flat mode, recalculate normal as face centroid normal
  38401. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38402. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38403. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38404. }
  38405. else {
  38406. // in smooth mode, recalculate normal from each single vertex position
  38407. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38408. }
  38409. // Vertex normal need correction due to X,Y,Z radius scaling
  38410. vertex_normal.x /= radiusX;
  38411. vertex_normal.y /= radiusY;
  38412. vertex_normal.z /= radiusZ;
  38413. vertex_normal.normalize();
  38414. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38415. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38416. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38417. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38418. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38419. uvs.push(uv_interp.x, uv_interp.y);
  38420. // push each vertex has member of a face
  38421. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38422. indices.push(current_indice);
  38423. current_indice++;
  38424. };
  38425. for (var i2 = 0; i2 < subdivisions; i2++) {
  38426. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38427. // face : (i1,i2) for /\ :
  38428. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38429. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38430. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38431. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38432. if (i1 + i2 + 1 < subdivisions) {
  38433. // face : (i1,i2)' for \/ :
  38434. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38435. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38436. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38437. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38438. }
  38439. }
  38440. }
  38441. }
  38442. // Sides
  38443. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38444. // Result
  38445. var vertexData = new VertexData();
  38446. vertexData.indices = indices;
  38447. vertexData.positions = positions;
  38448. vertexData.normals = normals;
  38449. vertexData.uvs = uvs;
  38450. return vertexData;
  38451. };
  38452. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38453. /**
  38454. * Creates the VertexData for a Polyhedron
  38455. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38456. * * type provided types are:
  38457. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38458. * * 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)
  38459. * * size the size of the IcoSphere, optional default 1
  38460. * * sizeX allows stretching in the x direction, optional, default size
  38461. * * sizeY allows stretching in the y direction, optional, default size
  38462. * * sizeZ allows stretching in the z direction, optional, default size
  38463. * * 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
  38464. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38465. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38466. * * flat when true creates a flat shaded mesh, optional, default true
  38467. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38468. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38469. * * 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)
  38470. * * 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)
  38471. * @returns the VertexData of the Polyhedron
  38472. */
  38473. VertexData.CreatePolyhedron = function (options) {
  38474. // provided polyhedron types :
  38475. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38476. // 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)
  38477. var polyhedra = [];
  38478. 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]] };
  38479. 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]] };
  38480. polyhedra[2] = {
  38481. 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]],
  38482. 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]]
  38483. };
  38484. polyhedra[3] = {
  38485. 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]],
  38486. 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]]
  38487. };
  38488. polyhedra[4] = {
  38489. 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]],
  38490. 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]]
  38491. };
  38492. 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]] };
  38493. 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]] };
  38494. 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]] };
  38495. 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]] };
  38496. 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]] };
  38497. 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]] };
  38498. 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]] };
  38499. 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]] };
  38500. 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]] };
  38501. polyhedra[14] = {
  38502. 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]],
  38503. 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]]
  38504. };
  38505. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38506. var size = options.size;
  38507. var sizeX = options.sizeX || size || 1;
  38508. var sizeY = options.sizeY || size || 1;
  38509. var sizeZ = options.sizeZ || size || 1;
  38510. var data = options.custom || polyhedra[type];
  38511. var nbfaces = data.face.length;
  38512. var faceUV = options.faceUV || new Array(nbfaces);
  38513. var faceColors = options.faceColors;
  38514. var flat = (options.flat === undefined) ? true : options.flat;
  38515. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38516. var positions = new Array();
  38517. var indices = new Array();
  38518. var normals = new Array();
  38519. var uvs = new Array();
  38520. var colors = new Array();
  38521. var index = 0;
  38522. var faceIdx = 0; // face cursor in the array "indexes"
  38523. var indexes = new Array();
  38524. var i = 0;
  38525. var f = 0;
  38526. var u, v, ang, x, y, tmp;
  38527. // default face colors and UV if undefined
  38528. if (flat) {
  38529. for (f = 0; f < nbfaces; f++) {
  38530. if (faceColors && faceColors[f] === undefined) {
  38531. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38532. }
  38533. if (faceUV && faceUV[f] === undefined) {
  38534. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38535. }
  38536. }
  38537. }
  38538. if (!flat) {
  38539. for (i = 0; i < data.vertex.length; i++) {
  38540. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38541. uvs.push(0, 0);
  38542. }
  38543. for (f = 0; f < nbfaces; f++) {
  38544. for (i = 0; i < data.face[f].length - 2; i++) {
  38545. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38546. }
  38547. }
  38548. }
  38549. else {
  38550. for (f = 0; f < nbfaces; f++) {
  38551. var fl = data.face[f].length; // number of vertices of the current face
  38552. ang = 2 * Math.PI / fl;
  38553. x = 0.5 * Math.tan(ang / 2);
  38554. y = 0.5;
  38555. // positions, uvs, colors
  38556. for (i = 0; i < fl; i++) {
  38557. // positions
  38558. 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);
  38559. indexes.push(index);
  38560. index++;
  38561. // uvs
  38562. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38563. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38564. uvs.push(u, v);
  38565. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38566. y = x * Math.sin(ang) + y * Math.cos(ang);
  38567. x = tmp;
  38568. // colors
  38569. if (faceColors) {
  38570. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38571. }
  38572. }
  38573. // indices from indexes
  38574. for (i = 0; i < fl - 2; i++) {
  38575. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38576. }
  38577. faceIdx += fl;
  38578. }
  38579. }
  38580. VertexData.ComputeNormals(positions, indices, normals);
  38581. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38582. var vertexData = new VertexData();
  38583. vertexData.positions = positions;
  38584. vertexData.indices = indices;
  38585. vertexData.normals = normals;
  38586. vertexData.uvs = uvs;
  38587. if (faceColors && flat) {
  38588. vertexData.colors = colors;
  38589. }
  38590. return vertexData;
  38591. };
  38592. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38593. /**
  38594. * Creates the VertexData for a TorusKnot
  38595. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38596. * * radius the radius of the torus knot, optional, default 2
  38597. * * tube the thickness of the tube, optional, default 0.5
  38598. * * radialSegments the number of sides on each tube segments, optional, default 32
  38599. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38600. * * p the number of windings around the z axis, optional, default 2
  38601. * * q the number of windings around the x axis, optional, default 3
  38602. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38603. * * 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)
  38604. * * 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)
  38605. * @returns the VertexData of the Torus Knot
  38606. */
  38607. VertexData.CreateTorusKnot = function (options) {
  38608. var indices = new Array();
  38609. var positions = new Array();
  38610. var normals = new Array();
  38611. var uvs = new Array();
  38612. var radius = options.radius || 2;
  38613. var tube = options.tube || 0.5;
  38614. var radialSegments = options.radialSegments || 32;
  38615. var tubularSegments = options.tubularSegments || 32;
  38616. var p = options.p || 2;
  38617. var q = options.q || 3;
  38618. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38619. // Helper
  38620. var getPos = function (angle) {
  38621. var cu = Math.cos(angle);
  38622. var su = Math.sin(angle);
  38623. var quOverP = q / p * angle;
  38624. var cs = Math.cos(quOverP);
  38625. var tx = radius * (2 + cs) * 0.5 * cu;
  38626. var ty = radius * (2 + cs) * su * 0.5;
  38627. var tz = radius * Math.sin(quOverP) * 0.5;
  38628. return new BABYLON.Vector3(tx, ty, tz);
  38629. };
  38630. // Vertices
  38631. var i;
  38632. var j;
  38633. for (i = 0; i <= radialSegments; i++) {
  38634. var modI = i % radialSegments;
  38635. var u = modI / radialSegments * 2 * p * Math.PI;
  38636. var p1 = getPos(u);
  38637. var p2 = getPos(u + 0.01);
  38638. var tang = p2.subtract(p1);
  38639. var n = p2.add(p1);
  38640. var bitan = BABYLON.Vector3.Cross(tang, n);
  38641. n = BABYLON.Vector3.Cross(bitan, tang);
  38642. bitan.normalize();
  38643. n.normalize();
  38644. for (j = 0; j < tubularSegments; j++) {
  38645. var modJ = j % tubularSegments;
  38646. var v = modJ / tubularSegments * 2 * Math.PI;
  38647. var cx = -tube * Math.cos(v);
  38648. var cy = tube * Math.sin(v);
  38649. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38650. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38651. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38652. uvs.push(i / radialSegments);
  38653. uvs.push(j / tubularSegments);
  38654. }
  38655. }
  38656. for (i = 0; i < radialSegments; i++) {
  38657. for (j = 0; j < tubularSegments; j++) {
  38658. var jNext = (j + 1) % tubularSegments;
  38659. var a = i * tubularSegments + j;
  38660. var b = (i + 1) * tubularSegments + j;
  38661. var c = (i + 1) * tubularSegments + jNext;
  38662. var d = i * tubularSegments + jNext;
  38663. indices.push(d);
  38664. indices.push(b);
  38665. indices.push(a);
  38666. indices.push(d);
  38667. indices.push(c);
  38668. indices.push(b);
  38669. }
  38670. }
  38671. // Normals
  38672. VertexData.ComputeNormals(positions, indices, normals);
  38673. // Sides
  38674. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38675. // Result
  38676. var vertexData = new VertexData();
  38677. vertexData.indices = indices;
  38678. vertexData.positions = positions;
  38679. vertexData.normals = normals;
  38680. vertexData.uvs = uvs;
  38681. return vertexData;
  38682. };
  38683. // Tools
  38684. /**
  38685. * Compute normals for given positions and indices
  38686. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38687. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38688. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38689. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38690. * * facetNormals : optional array of facet normals (vector3)
  38691. * * facetPositions : optional array of facet positions (vector3)
  38692. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38693. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38694. * * bInfo : optional bounding info, required for facetPartitioning computation
  38695. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38696. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38697. * * useRightHandedSystem: optional boolean to for right handed system computation
  38698. * * depthSort : optional boolean to enable the facet depth sort computation
  38699. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38700. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38701. */
  38702. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38703. // temporary scalar variables
  38704. var index = 0; // facet index
  38705. var p1p2x = 0.0; // p1p2 vector x coordinate
  38706. var p1p2y = 0.0; // p1p2 vector y coordinate
  38707. var p1p2z = 0.0; // p1p2 vector z coordinate
  38708. var p3p2x = 0.0; // p3p2 vector x coordinate
  38709. var p3p2y = 0.0; // p3p2 vector y coordinate
  38710. var p3p2z = 0.0; // p3p2 vector z coordinate
  38711. var faceNormalx = 0.0; // facet normal x coordinate
  38712. var faceNormaly = 0.0; // facet normal y coordinate
  38713. var faceNormalz = 0.0; // facet normal z coordinate
  38714. var length = 0.0; // facet normal length before normalization
  38715. var v1x = 0; // vector1 x index in the positions array
  38716. var v1y = 0; // vector1 y index in the positions array
  38717. var v1z = 0; // vector1 z index in the positions array
  38718. var v2x = 0; // vector2 x index in the positions array
  38719. var v2y = 0; // vector2 y index in the positions array
  38720. var v2z = 0; // vector2 z index in the positions array
  38721. var v3x = 0; // vector3 x index in the positions array
  38722. var v3y = 0; // vector3 y index in the positions array
  38723. var v3z = 0; // vector3 z index in the positions array
  38724. var computeFacetNormals = false;
  38725. var computeFacetPositions = false;
  38726. var computeFacetPartitioning = false;
  38727. var computeDepthSort = false;
  38728. var faceNormalSign = 1;
  38729. var ratio = 0;
  38730. var distanceTo = null;
  38731. if (options) {
  38732. computeFacetNormals = (options.facetNormals) ? true : false;
  38733. computeFacetPositions = (options.facetPositions) ? true : false;
  38734. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38735. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38736. ratio = options.ratio || 0;
  38737. computeDepthSort = (options.depthSort) ? true : false;
  38738. distanceTo = (options.distanceTo);
  38739. if (computeDepthSort) {
  38740. if (distanceTo === undefined) {
  38741. distanceTo = BABYLON.Vector3.Zero();
  38742. }
  38743. var depthSortedFacets = options.depthSortedFacets;
  38744. }
  38745. }
  38746. // facetPartitioning reinit if needed
  38747. var xSubRatio = 0;
  38748. var ySubRatio = 0;
  38749. var zSubRatio = 0;
  38750. var subSq = 0;
  38751. if (computeFacetPartitioning && options && options.bbSize) {
  38752. var ox = 0; // X partitioning index for facet position
  38753. var oy = 0; // Y partinioning index for facet position
  38754. var oz = 0; // Z partinioning index for facet position
  38755. var b1x = 0; // X partitioning index for facet v1 vertex
  38756. var b1y = 0; // Y partitioning index for facet v1 vertex
  38757. var b1z = 0; // z partitioning index for facet v1 vertex
  38758. var b2x = 0; // X partitioning index for facet v2 vertex
  38759. var b2y = 0; // Y partitioning index for facet v2 vertex
  38760. var b2z = 0; // Z partitioning index for facet v2 vertex
  38761. var b3x = 0; // X partitioning index for facet v3 vertex
  38762. var b3y = 0; // Y partitioning index for facet v3 vertex
  38763. var b3z = 0; // Z partitioning index for facet v3 vertex
  38764. var block_idx_o = 0; // facet barycenter block index
  38765. var block_idx_v1 = 0; // v1 vertex block index
  38766. var block_idx_v2 = 0; // v2 vertex block index
  38767. var block_idx_v3 = 0; // v3 vertex block index
  38768. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38769. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38770. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38771. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38772. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38773. subSq = options.subDiv.max * options.subDiv.max;
  38774. options.facetPartitioning.length = 0;
  38775. }
  38776. // reset the normals
  38777. for (index = 0; index < positions.length; index++) {
  38778. normals[index] = 0.0;
  38779. }
  38780. // Loop : 1 indice triplet = 1 facet
  38781. var nbFaces = (indices.length / 3) | 0;
  38782. for (index = 0; index < nbFaces; index++) {
  38783. // get the indexes of the coordinates of each vertex of the facet
  38784. v1x = indices[index * 3] * 3;
  38785. v1y = v1x + 1;
  38786. v1z = v1x + 2;
  38787. v2x = indices[index * 3 + 1] * 3;
  38788. v2y = v2x + 1;
  38789. v2z = v2x + 2;
  38790. v3x = indices[index * 3 + 2] * 3;
  38791. v3y = v3x + 1;
  38792. v3z = v3x + 2;
  38793. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38794. p1p2y = positions[v1y] - positions[v2y];
  38795. p1p2z = positions[v1z] - positions[v2z];
  38796. p3p2x = positions[v3x] - positions[v2x];
  38797. p3p2y = positions[v3y] - positions[v2y];
  38798. p3p2z = positions[v3z] - positions[v2z];
  38799. // compute the face normal with the cross product
  38800. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38801. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38802. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38803. // normalize this normal and store it in the array facetData
  38804. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38805. length = (length === 0) ? 1.0 : length;
  38806. faceNormalx /= length;
  38807. faceNormaly /= length;
  38808. faceNormalz /= length;
  38809. if (computeFacetNormals && options) {
  38810. options.facetNormals[index].x = faceNormalx;
  38811. options.facetNormals[index].y = faceNormaly;
  38812. options.facetNormals[index].z = faceNormalz;
  38813. }
  38814. if (computeFacetPositions && options) {
  38815. // compute and the facet barycenter coordinates in the array facetPositions
  38816. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38817. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38818. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38819. }
  38820. if (computeFacetPartitioning && options) {
  38821. // store the facet indexes in arrays in the main facetPartitioning array :
  38822. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38823. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38824. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38825. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38826. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38827. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38828. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38829. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38830. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38831. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38832. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38833. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38834. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38835. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38836. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38837. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38838. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38839. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38840. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38841. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38842. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38843. // push each facet index in each block containing the vertex
  38844. options.facetPartitioning[block_idx_v1].push(index);
  38845. if (block_idx_v2 != block_idx_v1) {
  38846. options.facetPartitioning[block_idx_v2].push(index);
  38847. }
  38848. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38849. options.facetPartitioning[block_idx_v3].push(index);
  38850. }
  38851. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38852. options.facetPartitioning[block_idx_o].push(index);
  38853. }
  38854. }
  38855. if (computeDepthSort && options && options.facetPositions) {
  38856. var dsf = depthSortedFacets[index];
  38857. dsf.ind = index * 3;
  38858. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38859. }
  38860. // compute the normals anyway
  38861. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38862. normals[v1y] += faceNormaly;
  38863. normals[v1z] += faceNormalz;
  38864. normals[v2x] += faceNormalx;
  38865. normals[v2y] += faceNormaly;
  38866. normals[v2z] += faceNormalz;
  38867. normals[v3x] += faceNormalx;
  38868. normals[v3y] += faceNormaly;
  38869. normals[v3z] += faceNormalz;
  38870. }
  38871. // last normalization of each normal
  38872. for (index = 0; index < normals.length / 3; index++) {
  38873. faceNormalx = normals[index * 3];
  38874. faceNormaly = normals[index * 3 + 1];
  38875. faceNormalz = normals[index * 3 + 2];
  38876. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38877. length = (length === 0) ? 1.0 : length;
  38878. faceNormalx /= length;
  38879. faceNormaly /= length;
  38880. faceNormalz /= length;
  38881. normals[index * 3] = faceNormalx;
  38882. normals[index * 3 + 1] = faceNormaly;
  38883. normals[index * 3 + 2] = faceNormalz;
  38884. }
  38885. };
  38886. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38887. var li = indices.length;
  38888. var ln = normals.length;
  38889. var i;
  38890. var n;
  38891. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38892. switch (sideOrientation) {
  38893. case BABYLON.Mesh.FRONTSIDE:
  38894. // nothing changed
  38895. break;
  38896. case BABYLON.Mesh.BACKSIDE:
  38897. var tmp;
  38898. // indices
  38899. for (i = 0; i < li; i += 3) {
  38900. tmp = indices[i];
  38901. indices[i] = indices[i + 2];
  38902. indices[i + 2] = tmp;
  38903. }
  38904. // normals
  38905. for (n = 0; n < ln; n++) {
  38906. normals[n] = -normals[n];
  38907. }
  38908. break;
  38909. case BABYLON.Mesh.DOUBLESIDE:
  38910. // positions
  38911. var lp = positions.length;
  38912. var l = lp / 3;
  38913. for (var p = 0; p < lp; p++) {
  38914. positions[lp + p] = positions[p];
  38915. }
  38916. // indices
  38917. for (i = 0; i < li; i += 3) {
  38918. indices[i + li] = indices[i + 2] + l;
  38919. indices[i + 1 + li] = indices[i + 1] + l;
  38920. indices[i + 2 + li] = indices[i] + l;
  38921. }
  38922. // normals
  38923. for (n = 0; n < ln; n++) {
  38924. normals[ln + n] = -normals[n];
  38925. }
  38926. // uvs
  38927. var lu = uvs.length;
  38928. var u = 0;
  38929. for (u = 0; u < lu; u++) {
  38930. uvs[u + lu] = uvs[u];
  38931. }
  38932. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38933. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38934. u = 0;
  38935. for (i = 0; i < lu / 2; i++) {
  38936. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38937. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38938. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38939. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38940. u += 2;
  38941. }
  38942. break;
  38943. }
  38944. };
  38945. /**
  38946. * Applies VertexData created from the imported parameters to the geometry
  38947. * @param parsedVertexData the parsed data from an imported file
  38948. * @param geometry the geometry to apply the VertexData to
  38949. */
  38950. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38951. var vertexData = new VertexData();
  38952. // positions
  38953. var positions = parsedVertexData.positions;
  38954. if (positions) {
  38955. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38956. }
  38957. // normals
  38958. var normals = parsedVertexData.normals;
  38959. if (normals) {
  38960. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38961. }
  38962. // tangents
  38963. var tangents = parsedVertexData.tangents;
  38964. if (tangents) {
  38965. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38966. }
  38967. // uvs
  38968. var uvs = parsedVertexData.uvs;
  38969. if (uvs) {
  38970. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38971. }
  38972. // uv2s
  38973. var uv2s = parsedVertexData.uv2s;
  38974. if (uv2s) {
  38975. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38976. }
  38977. // uv3s
  38978. var uv3s = parsedVertexData.uv3s;
  38979. if (uv3s) {
  38980. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38981. }
  38982. // uv4s
  38983. var uv4s = parsedVertexData.uv4s;
  38984. if (uv4s) {
  38985. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38986. }
  38987. // uv5s
  38988. var uv5s = parsedVertexData.uv5s;
  38989. if (uv5s) {
  38990. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38991. }
  38992. // uv6s
  38993. var uv6s = parsedVertexData.uv6s;
  38994. if (uv6s) {
  38995. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38996. }
  38997. // colors
  38998. var colors = parsedVertexData.colors;
  38999. if (colors) {
  39000. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  39001. }
  39002. // matricesIndices
  39003. var matricesIndices = parsedVertexData.matricesIndices;
  39004. if (matricesIndices) {
  39005. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39006. }
  39007. // matricesWeights
  39008. var matricesWeights = parsedVertexData.matricesWeights;
  39009. if (matricesWeights) {
  39010. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  39011. }
  39012. // indices
  39013. var indices = parsedVertexData.indices;
  39014. if (indices) {
  39015. vertexData.indices = indices;
  39016. }
  39017. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39018. };
  39019. return VertexData;
  39020. }());
  39021. BABYLON.VertexData = VertexData;
  39022. })(BABYLON || (BABYLON = {}));
  39023. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39024. var BABYLON;
  39025. (function (BABYLON) {
  39026. /**
  39027. * Class used to store geometry data (vertex buffers + index buffer)
  39028. */
  39029. var Geometry = /** @class */ (function () {
  39030. /**
  39031. * Creates a new geometry
  39032. * @param id defines the unique ID
  39033. * @param scene defines the hosting scene
  39034. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  39035. * @param updatable defines if geometry must be updatable (false by default)
  39036. * @param mesh defines the mesh that will be associated with the geometry
  39037. */
  39038. function Geometry(id, scene, vertexData, updatable, mesh) {
  39039. if (updatable === void 0) { updatable = false; }
  39040. if (mesh === void 0) { mesh = null; }
  39041. /**
  39042. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39043. */
  39044. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39045. this._totalVertices = 0;
  39046. this._isDisposed = false;
  39047. this._indexBufferIsUpdatable = false;
  39048. this.id = id;
  39049. this._engine = scene.getEngine();
  39050. this._meshes = [];
  39051. this._scene = scene;
  39052. //Init vertex buffer cache
  39053. this._vertexBuffers = {};
  39054. this._indices = [];
  39055. this._updatable = updatable;
  39056. // vertexData
  39057. if (vertexData) {
  39058. this.setAllVerticesData(vertexData, updatable);
  39059. }
  39060. else {
  39061. this._totalVertices = 0;
  39062. this._indices = [];
  39063. }
  39064. if (this._engine.getCaps().vertexArrayObject) {
  39065. this._vertexArrayObjects = {};
  39066. }
  39067. // applyToMesh
  39068. if (mesh) {
  39069. if (mesh.getClassName() === "LinesMesh") {
  39070. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39071. this._updateExtend();
  39072. }
  39073. this.applyToMesh(mesh);
  39074. mesh.computeWorldMatrix(true);
  39075. }
  39076. }
  39077. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39078. /**
  39079. * 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
  39080. */
  39081. get: function () {
  39082. return this._boundingBias;
  39083. },
  39084. /**
  39085. * 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
  39086. */
  39087. set: function (value) {
  39088. if (this._boundingBias && this._boundingBias.equals(value)) {
  39089. return;
  39090. }
  39091. this._boundingBias = value.clone();
  39092. this._updateBoundingInfo(true, null);
  39093. },
  39094. enumerable: true,
  39095. configurable: true
  39096. });
  39097. /**
  39098. * Static function used to attach a new empty geometry to a mesh
  39099. * @param mesh defines the mesh to attach the geometry to
  39100. * @returns the new {BABYLON.Geometry}
  39101. */
  39102. Geometry.CreateGeometryForMesh = function (mesh) {
  39103. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39104. geometry.applyToMesh(mesh);
  39105. return geometry;
  39106. };
  39107. Object.defineProperty(Geometry.prototype, "extend", {
  39108. /**
  39109. * Gets the current extend of the geometry
  39110. */
  39111. get: function () {
  39112. return this._extend;
  39113. },
  39114. enumerable: true,
  39115. configurable: true
  39116. });
  39117. /**
  39118. * Gets the hosting scene
  39119. * @returns the hosting {BABYLON.Scene}
  39120. */
  39121. Geometry.prototype.getScene = function () {
  39122. return this._scene;
  39123. };
  39124. /**
  39125. * Gets the hosting engine
  39126. * @returns the hosting {BABYLON.Engine}
  39127. */
  39128. Geometry.prototype.getEngine = function () {
  39129. return this._engine;
  39130. };
  39131. /**
  39132. * Defines if the geometry is ready to use
  39133. * @returns true if the geometry is ready to be used
  39134. */
  39135. Geometry.prototype.isReady = function () {
  39136. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39137. };
  39138. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39139. /**
  39140. * Gets a value indicating that the geometry should not be serialized
  39141. */
  39142. get: function () {
  39143. for (var index = 0; index < this._meshes.length; index++) {
  39144. if (!this._meshes[index].doNotSerialize) {
  39145. return false;
  39146. }
  39147. }
  39148. return true;
  39149. },
  39150. enumerable: true,
  39151. configurable: true
  39152. });
  39153. /** @hidden */
  39154. Geometry.prototype._rebuild = function () {
  39155. if (this._vertexArrayObjects) {
  39156. this._vertexArrayObjects = {};
  39157. }
  39158. // Index buffer
  39159. if (this._meshes.length !== 0 && this._indices) {
  39160. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39161. }
  39162. // Vertex buffers
  39163. for (var key in this._vertexBuffers) {
  39164. var vertexBuffer = this._vertexBuffers[key];
  39165. vertexBuffer._rebuild();
  39166. }
  39167. };
  39168. /**
  39169. * Affects all gemetry data in one call
  39170. * @param vertexData defines the geometry data
  39171. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39172. */
  39173. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39174. vertexData.applyToGeometry(this, updatable);
  39175. this.notifyUpdate();
  39176. };
  39177. /**
  39178. * Set specific vertex data
  39179. * @param kind defines the data kind (Position, normal, etc...)
  39180. * @param data defines the vertex data to use
  39181. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39182. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39183. */
  39184. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39185. if (updatable === void 0) { updatable = false; }
  39186. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39187. this.setVerticesBuffer(buffer);
  39188. };
  39189. /**
  39190. * Removes a specific vertex data
  39191. * @param kind defines the data kind (Position, normal, etc...)
  39192. */
  39193. Geometry.prototype.removeVerticesData = function (kind) {
  39194. if (this._vertexBuffers[kind]) {
  39195. this._vertexBuffers[kind].dispose();
  39196. delete this._vertexBuffers[kind];
  39197. }
  39198. };
  39199. /**
  39200. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39201. * @param buffer defines the vertex buffer to use
  39202. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39203. */
  39204. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39205. if (totalVertices === void 0) { totalVertices = null; }
  39206. var kind = buffer.getKind();
  39207. if (this._vertexBuffers[kind]) {
  39208. this._vertexBuffers[kind].dispose();
  39209. }
  39210. this._vertexBuffers[kind] = buffer;
  39211. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39212. var data = buffer.getData();
  39213. if (totalVertices != null) {
  39214. this._totalVertices = totalVertices;
  39215. }
  39216. else {
  39217. if (data != null) {
  39218. this._totalVertices = data.length / (buffer.byteStride / 4);
  39219. }
  39220. }
  39221. this._updateExtend(data);
  39222. this._resetPointsArrayCache();
  39223. var meshes = this._meshes;
  39224. var numOfMeshes = meshes.length;
  39225. for (var index = 0; index < numOfMeshes; index++) {
  39226. var mesh = meshes[index];
  39227. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39228. mesh._createGlobalSubMesh(false);
  39229. mesh.computeWorldMatrix(true);
  39230. }
  39231. }
  39232. this.notifyUpdate(kind);
  39233. if (this._vertexArrayObjects) {
  39234. this._disposeVertexArrayObjects();
  39235. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39236. }
  39237. };
  39238. /**
  39239. * Update a specific vertex buffer
  39240. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39241. * It will do nothing if the buffer is not updatable
  39242. * @param kind defines the data kind (Position, normal, etc...)
  39243. * @param data defines the data to use
  39244. * @param offset defines the offset in the target buffer where to store the data
  39245. * @param useBytes set to true if the offset is in bytes
  39246. */
  39247. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39248. if (useBytes === void 0) { useBytes = false; }
  39249. var vertexBuffer = this.getVertexBuffer(kind);
  39250. if (!vertexBuffer) {
  39251. return;
  39252. }
  39253. vertexBuffer.updateDirectly(data, offset, useBytes);
  39254. this.notifyUpdate(kind);
  39255. };
  39256. /**
  39257. * Update a specific vertex buffer
  39258. * This function will create a new buffer if the current one is not updatable
  39259. * @param kind defines the data kind (Position, normal, etc...)
  39260. * @param data defines the data to use
  39261. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39262. */
  39263. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39264. if (updateExtends === void 0) { updateExtends = false; }
  39265. var vertexBuffer = this.getVertexBuffer(kind);
  39266. if (!vertexBuffer) {
  39267. return;
  39268. }
  39269. vertexBuffer.update(data);
  39270. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39271. this._updateBoundingInfo(updateExtends, data);
  39272. }
  39273. this.notifyUpdate(kind);
  39274. };
  39275. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39276. if (updateExtends) {
  39277. this._updateExtend(data);
  39278. }
  39279. var meshes = this._meshes;
  39280. var numOfMeshes = meshes.length;
  39281. this._resetPointsArrayCache();
  39282. for (var index = 0; index < numOfMeshes; index++) {
  39283. var mesh = meshes[index];
  39284. if (updateExtends) {
  39285. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39286. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39287. var subMesh = mesh.subMeshes[subIndex];
  39288. subMesh.refreshBoundingInfo();
  39289. }
  39290. }
  39291. }
  39292. };
  39293. /** @hidden */
  39294. Geometry.prototype._bind = function (effect, indexToBind) {
  39295. if (!effect) {
  39296. return;
  39297. }
  39298. if (indexToBind === undefined) {
  39299. indexToBind = this._indexBuffer;
  39300. }
  39301. var vbs = this.getVertexBuffers();
  39302. if (!vbs) {
  39303. return;
  39304. }
  39305. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39306. this._engine.bindBuffers(vbs, indexToBind, effect);
  39307. return;
  39308. }
  39309. // Using VAO
  39310. if (!this._vertexArrayObjects[effect.key]) {
  39311. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39312. }
  39313. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39314. };
  39315. /**
  39316. * Gets total number of vertices
  39317. * @returns the total number of vertices
  39318. */
  39319. Geometry.prototype.getTotalVertices = function () {
  39320. if (!this.isReady()) {
  39321. return 0;
  39322. }
  39323. return this._totalVertices;
  39324. };
  39325. /**
  39326. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39327. * @param kind defines the data kind (Position, normal, etc...)
  39328. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39329. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39330. * @returns a float array containing vertex data
  39331. */
  39332. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39333. var vertexBuffer = this.getVertexBuffer(kind);
  39334. if (!vertexBuffer) {
  39335. return null;
  39336. }
  39337. var data = vertexBuffer.getData();
  39338. if (!data) {
  39339. return null;
  39340. }
  39341. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39342. var count = this._totalVertices * vertexBuffer.getSize();
  39343. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39344. var copy_1 = new Array(count);
  39345. vertexBuffer.forEach(count, function (value, index) {
  39346. copy_1[index] = value;
  39347. });
  39348. return copy_1;
  39349. }
  39350. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39351. if (data instanceof Array) {
  39352. var offset = vertexBuffer.byteOffset / 4;
  39353. return BABYLON.Tools.Slice(data, offset, offset + count);
  39354. }
  39355. else if (data instanceof ArrayBuffer) {
  39356. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39357. }
  39358. else {
  39359. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39360. }
  39361. }
  39362. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39363. return BABYLON.Tools.Slice(data);
  39364. }
  39365. return data;
  39366. };
  39367. /**
  39368. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39369. * @param kind defines the data kind (Position, normal, etc...)
  39370. * @returns true if the vertex buffer with the specified kind is updatable
  39371. */
  39372. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39373. var vb = this._vertexBuffers[kind];
  39374. if (!vb) {
  39375. return false;
  39376. }
  39377. return vb.isUpdatable();
  39378. };
  39379. /**
  39380. * Gets a specific vertex buffer
  39381. * @param kind defines the data kind (Position, normal, etc...)
  39382. * @returns a {BABYLON.VertexBuffer}
  39383. */
  39384. Geometry.prototype.getVertexBuffer = function (kind) {
  39385. if (!this.isReady()) {
  39386. return null;
  39387. }
  39388. return this._vertexBuffers[kind];
  39389. };
  39390. /**
  39391. * Returns all vertex buffers
  39392. * @return an object holding all vertex buffers indexed by kind
  39393. */
  39394. Geometry.prototype.getVertexBuffers = function () {
  39395. if (!this.isReady()) {
  39396. return null;
  39397. }
  39398. return this._vertexBuffers;
  39399. };
  39400. /**
  39401. * Gets a boolean indicating if specific vertex buffer is present
  39402. * @param kind defines the data kind (Position, normal, etc...)
  39403. * @returns true if data is present
  39404. */
  39405. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39406. if (!this._vertexBuffers) {
  39407. if (this._delayInfo) {
  39408. return this._delayInfo.indexOf(kind) !== -1;
  39409. }
  39410. return false;
  39411. }
  39412. return this._vertexBuffers[kind] !== undefined;
  39413. };
  39414. /**
  39415. * Gets a list of all attached data kinds (Position, normal, etc...)
  39416. * @returns a list of string containing all kinds
  39417. */
  39418. Geometry.prototype.getVerticesDataKinds = function () {
  39419. var result = [];
  39420. var kind;
  39421. if (!this._vertexBuffers && this._delayInfo) {
  39422. for (kind in this._delayInfo) {
  39423. result.push(kind);
  39424. }
  39425. }
  39426. else {
  39427. for (kind in this._vertexBuffers) {
  39428. result.push(kind);
  39429. }
  39430. }
  39431. return result;
  39432. };
  39433. /**
  39434. * Update index buffer
  39435. * @param indices defines the indices to store in the index buffer
  39436. * @param offset defines the offset in the target buffer where to store the data
  39437. */
  39438. Geometry.prototype.updateIndices = function (indices, offset) {
  39439. if (!this._indexBuffer) {
  39440. return;
  39441. }
  39442. if (!this._indexBufferIsUpdatable) {
  39443. this.setIndices(indices, null, true);
  39444. }
  39445. else {
  39446. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39447. }
  39448. };
  39449. /**
  39450. * Creates a new index buffer
  39451. * @param indices defines the indices to store in the index buffer
  39452. * @param totalVertices defines the total number of vertices (could be null)
  39453. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39454. */
  39455. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39456. if (totalVertices === void 0) { totalVertices = null; }
  39457. if (updatable === void 0) { updatable = false; }
  39458. if (this._indexBuffer) {
  39459. this._engine._releaseBuffer(this._indexBuffer);
  39460. }
  39461. this._disposeVertexArrayObjects();
  39462. this._indices = indices;
  39463. this._indexBufferIsUpdatable = updatable;
  39464. if (this._meshes.length !== 0 && this._indices) {
  39465. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39466. }
  39467. if (totalVertices != undefined) { // including null and undefined
  39468. this._totalVertices = totalVertices;
  39469. }
  39470. var meshes = this._meshes;
  39471. var numOfMeshes = meshes.length;
  39472. for (var index = 0; index < numOfMeshes; index++) {
  39473. meshes[index]._createGlobalSubMesh(true);
  39474. }
  39475. this.notifyUpdate();
  39476. };
  39477. /**
  39478. * Return the total number of indices
  39479. * @returns the total number of indices
  39480. */
  39481. Geometry.prototype.getTotalIndices = function () {
  39482. if (!this.isReady()) {
  39483. return 0;
  39484. }
  39485. return this._indices.length;
  39486. };
  39487. /**
  39488. * Gets the index buffer array
  39489. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39490. * @returns the index buffer array
  39491. */
  39492. Geometry.prototype.getIndices = function (copyWhenShared) {
  39493. if (!this.isReady()) {
  39494. return null;
  39495. }
  39496. var orig = this._indices;
  39497. if (!copyWhenShared || this._meshes.length === 1) {
  39498. return orig;
  39499. }
  39500. else {
  39501. var len = orig.length;
  39502. var copy = [];
  39503. for (var i = 0; i < len; i++) {
  39504. copy.push(orig[i]);
  39505. }
  39506. return copy;
  39507. }
  39508. };
  39509. /**
  39510. * Gets the index buffer
  39511. * @return the index buffer
  39512. */
  39513. Geometry.prototype.getIndexBuffer = function () {
  39514. if (!this.isReady()) {
  39515. return null;
  39516. }
  39517. return this._indexBuffer;
  39518. };
  39519. /** @hidden */
  39520. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39521. if (effect === void 0) { effect = null; }
  39522. if (!effect || !this._vertexArrayObjects) {
  39523. return;
  39524. }
  39525. if (this._vertexArrayObjects[effect.key]) {
  39526. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39527. delete this._vertexArrayObjects[effect.key];
  39528. }
  39529. };
  39530. /**
  39531. * Release the associated resources for a specific mesh
  39532. * @param mesh defines the source mesh
  39533. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39534. */
  39535. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39536. var meshes = this._meshes;
  39537. var index = meshes.indexOf(mesh);
  39538. if (index === -1) {
  39539. return;
  39540. }
  39541. meshes.splice(index, 1);
  39542. mesh._geometry = null;
  39543. if (meshes.length === 0 && shouldDispose) {
  39544. this.dispose();
  39545. }
  39546. };
  39547. /**
  39548. * Apply current geometry to a given mesh
  39549. * @param mesh defines the mesh to apply geometry to
  39550. */
  39551. Geometry.prototype.applyToMesh = function (mesh) {
  39552. if (mesh._geometry === this) {
  39553. return;
  39554. }
  39555. var previousGeometry = mesh._geometry;
  39556. if (previousGeometry) {
  39557. previousGeometry.releaseForMesh(mesh);
  39558. }
  39559. var meshes = this._meshes;
  39560. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39561. mesh._geometry = this;
  39562. this._scene.pushGeometry(this);
  39563. meshes.push(mesh);
  39564. if (this.isReady()) {
  39565. this._applyToMesh(mesh);
  39566. }
  39567. else {
  39568. mesh._boundingInfo = this._boundingInfo;
  39569. }
  39570. };
  39571. Geometry.prototype._updateExtend = function (data) {
  39572. if (data === void 0) { data = null; }
  39573. if (!data) {
  39574. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39575. }
  39576. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39577. };
  39578. Geometry.prototype._applyToMesh = function (mesh) {
  39579. var numOfMeshes = this._meshes.length;
  39580. // vertexBuffers
  39581. for (var kind in this._vertexBuffers) {
  39582. if (numOfMeshes === 1) {
  39583. this._vertexBuffers[kind].create();
  39584. }
  39585. var buffer = this._vertexBuffers[kind].getBuffer();
  39586. if (buffer)
  39587. buffer.references = numOfMeshes;
  39588. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39589. if (!this._extend) {
  39590. this._updateExtend();
  39591. }
  39592. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39593. mesh._createGlobalSubMesh(false);
  39594. //bounding info was just created again, world matrix should be applied again.
  39595. mesh._updateBoundingInfo();
  39596. }
  39597. }
  39598. // indexBuffer
  39599. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39600. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39601. }
  39602. if (this._indexBuffer) {
  39603. this._indexBuffer.references = numOfMeshes;
  39604. }
  39605. };
  39606. Geometry.prototype.notifyUpdate = function (kind) {
  39607. if (this.onGeometryUpdated) {
  39608. this.onGeometryUpdated(this, kind);
  39609. }
  39610. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39611. var mesh = _a[_i];
  39612. mesh._markSubMeshesAsAttributesDirty();
  39613. }
  39614. };
  39615. /**
  39616. * Load the geometry if it was flagged as delay loaded
  39617. * @param scene defines the hosting scene
  39618. * @param onLoaded defines a callback called when the geometry is loaded
  39619. */
  39620. Geometry.prototype.load = function (scene, onLoaded) {
  39621. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39622. return;
  39623. }
  39624. if (this.isReady()) {
  39625. if (onLoaded) {
  39626. onLoaded();
  39627. }
  39628. return;
  39629. }
  39630. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39631. this._queueLoad(scene, onLoaded);
  39632. };
  39633. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39634. var _this = this;
  39635. if (!this.delayLoadingFile) {
  39636. return;
  39637. }
  39638. scene._addPendingData(this);
  39639. scene._loadFile(this.delayLoadingFile, function (data) {
  39640. if (!_this._delayLoadingFunction) {
  39641. return;
  39642. }
  39643. _this._delayLoadingFunction(JSON.parse(data), _this);
  39644. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39645. _this._delayInfo = [];
  39646. scene._removePendingData(_this);
  39647. var meshes = _this._meshes;
  39648. var numOfMeshes = meshes.length;
  39649. for (var index = 0; index < numOfMeshes; index++) {
  39650. _this._applyToMesh(meshes[index]);
  39651. }
  39652. if (onLoaded) {
  39653. onLoaded();
  39654. }
  39655. }, undefined, true);
  39656. };
  39657. /**
  39658. * Invert the geometry to move from a right handed system to a left handed one.
  39659. */
  39660. Geometry.prototype.toLeftHanded = function () {
  39661. // Flip faces
  39662. var tIndices = this.getIndices(false);
  39663. if (tIndices != null && tIndices.length > 0) {
  39664. for (var i = 0; i < tIndices.length; i += 3) {
  39665. var tTemp = tIndices[i + 0];
  39666. tIndices[i + 0] = tIndices[i + 2];
  39667. tIndices[i + 2] = tTemp;
  39668. }
  39669. this.setIndices(tIndices);
  39670. }
  39671. // Negate position.z
  39672. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39673. if (tPositions != null && tPositions.length > 0) {
  39674. for (var i = 0; i < tPositions.length; i += 3) {
  39675. tPositions[i + 2] = -tPositions[i + 2];
  39676. }
  39677. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39678. }
  39679. // Negate normal.z
  39680. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39681. if (tNormals != null && tNormals.length > 0) {
  39682. for (var i = 0; i < tNormals.length; i += 3) {
  39683. tNormals[i + 2] = -tNormals[i + 2];
  39684. }
  39685. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39686. }
  39687. };
  39688. // Cache
  39689. /** @hidden */
  39690. Geometry.prototype._resetPointsArrayCache = function () {
  39691. this._positions = null;
  39692. };
  39693. /** @hidden */
  39694. Geometry.prototype._generatePointsArray = function () {
  39695. if (this._positions)
  39696. return true;
  39697. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39698. if (!data || data.length === 0) {
  39699. return false;
  39700. }
  39701. this._positions = [];
  39702. for (var index = 0; index < data.length; index += 3) {
  39703. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39704. }
  39705. return true;
  39706. };
  39707. /**
  39708. * Gets a value indicating if the geometry is disposed
  39709. * @returns true if the geometry was disposed
  39710. */
  39711. Geometry.prototype.isDisposed = function () {
  39712. return this._isDisposed;
  39713. };
  39714. Geometry.prototype._disposeVertexArrayObjects = function () {
  39715. if (this._vertexArrayObjects) {
  39716. for (var kind in this._vertexArrayObjects) {
  39717. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39718. }
  39719. this._vertexArrayObjects = {};
  39720. }
  39721. };
  39722. /**
  39723. * Free all associated resources
  39724. */
  39725. Geometry.prototype.dispose = function () {
  39726. var meshes = this._meshes;
  39727. var numOfMeshes = meshes.length;
  39728. var index;
  39729. for (index = 0; index < numOfMeshes; index++) {
  39730. this.releaseForMesh(meshes[index]);
  39731. }
  39732. this._meshes = [];
  39733. this._disposeVertexArrayObjects();
  39734. for (var kind in this._vertexBuffers) {
  39735. this._vertexBuffers[kind].dispose();
  39736. }
  39737. this._vertexBuffers = {};
  39738. this._totalVertices = 0;
  39739. if (this._indexBuffer) {
  39740. this._engine._releaseBuffer(this._indexBuffer);
  39741. }
  39742. this._indexBuffer = null;
  39743. this._indices = [];
  39744. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39745. this.delayLoadingFile = null;
  39746. this._delayLoadingFunction = null;
  39747. this._delayInfo = [];
  39748. this._boundingInfo = null;
  39749. this._scene.removeGeometry(this);
  39750. this._isDisposed = true;
  39751. };
  39752. /**
  39753. * Clone the current geometry into a new geometry
  39754. * @param id defines the unique ID of the new geometry
  39755. * @returns a new geometry object
  39756. */
  39757. Geometry.prototype.copy = function (id) {
  39758. var vertexData = new BABYLON.VertexData();
  39759. vertexData.indices = [];
  39760. var indices = this.getIndices();
  39761. if (indices) {
  39762. for (var index = 0; index < indices.length; index++) {
  39763. vertexData.indices.push(indices[index]);
  39764. }
  39765. }
  39766. var updatable = false;
  39767. var stopChecking = false;
  39768. var kind;
  39769. for (kind in this._vertexBuffers) {
  39770. // using slice() to make a copy of the array and not just reference it
  39771. var data = this.getVerticesData(kind);
  39772. if (data instanceof Float32Array) {
  39773. vertexData.set(new Float32Array(data), kind);
  39774. }
  39775. else {
  39776. vertexData.set(data.slice(0), kind);
  39777. }
  39778. if (!stopChecking) {
  39779. var vb = this.getVertexBuffer(kind);
  39780. if (vb) {
  39781. updatable = vb.isUpdatable();
  39782. stopChecking = !updatable;
  39783. }
  39784. }
  39785. }
  39786. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39787. geometry.delayLoadState = this.delayLoadState;
  39788. geometry.delayLoadingFile = this.delayLoadingFile;
  39789. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39790. for (kind in this._delayInfo) {
  39791. geometry._delayInfo = geometry._delayInfo || [];
  39792. geometry._delayInfo.push(kind);
  39793. }
  39794. // Bounding info
  39795. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39796. return geometry;
  39797. };
  39798. /**
  39799. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39800. * @return a JSON representation of the current geometry data (without the vertices data)
  39801. */
  39802. Geometry.prototype.serialize = function () {
  39803. var serializationObject = {};
  39804. serializationObject.id = this.id;
  39805. serializationObject.updatable = this._updatable;
  39806. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39807. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39808. }
  39809. return serializationObject;
  39810. };
  39811. Geometry.prototype.toNumberArray = function (origin) {
  39812. if (Array.isArray(origin)) {
  39813. return origin;
  39814. }
  39815. else {
  39816. return Array.prototype.slice.call(origin);
  39817. }
  39818. };
  39819. /**
  39820. * Serialize all vertices data into a JSON oject
  39821. * @returns a JSON representation of the current geometry data
  39822. */
  39823. Geometry.prototype.serializeVerticeData = function () {
  39824. var serializationObject = this.serialize();
  39825. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39826. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39827. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39828. serializationObject.positions._updatable = true;
  39829. }
  39830. }
  39831. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39832. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39833. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39834. serializationObject.normals._updatable = true;
  39835. }
  39836. }
  39837. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39838. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39839. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39840. serializationObject.tangets._updatable = true;
  39841. }
  39842. }
  39843. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39844. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39845. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39846. serializationObject.uvs._updatable = true;
  39847. }
  39848. }
  39849. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39850. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39851. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39852. serializationObject.uv2s._updatable = true;
  39853. }
  39854. }
  39855. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39856. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39857. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39858. serializationObject.uv3s._updatable = true;
  39859. }
  39860. }
  39861. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39862. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39863. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39864. serializationObject.uv4s._updatable = true;
  39865. }
  39866. }
  39867. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39868. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39869. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39870. serializationObject.uv5s._updatable = true;
  39871. }
  39872. }
  39873. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39874. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39875. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39876. serializationObject.uv6s._updatable = true;
  39877. }
  39878. }
  39879. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39880. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39881. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39882. serializationObject.colors._updatable = true;
  39883. }
  39884. }
  39885. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39886. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39887. serializationObject.matricesIndices._isExpanded = true;
  39888. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39889. serializationObject.matricesIndices._updatable = true;
  39890. }
  39891. }
  39892. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39893. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39894. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39895. serializationObject.matricesWeights._updatable = true;
  39896. }
  39897. }
  39898. serializationObject.indices = this.toNumberArray(this.getIndices());
  39899. return serializationObject;
  39900. };
  39901. // Statics
  39902. /**
  39903. * Extracts a clone of a mesh geometry
  39904. * @param mesh defines the source mesh
  39905. * @param id defines the unique ID of the new geometry object
  39906. * @returns the new geometry object
  39907. */
  39908. Geometry.ExtractFromMesh = function (mesh, id) {
  39909. var geometry = mesh._geometry;
  39910. if (!geometry) {
  39911. return null;
  39912. }
  39913. return geometry.copy(id);
  39914. };
  39915. /**
  39916. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39917. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39918. * Be aware Math.random() could cause collisions, but:
  39919. * "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"
  39920. * @returns a string containing a new GUID
  39921. */
  39922. Geometry.RandomId = function () {
  39923. return BABYLON.Tools.RandomId();
  39924. };
  39925. /** @hidden */
  39926. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39927. var scene = mesh.getScene();
  39928. // Geometry
  39929. var geometryId = parsedGeometry.geometryId;
  39930. if (geometryId) {
  39931. var geometry = scene.getGeometryByID(geometryId);
  39932. if (geometry) {
  39933. geometry.applyToMesh(mesh);
  39934. }
  39935. }
  39936. else if (parsedGeometry instanceof ArrayBuffer) {
  39937. var binaryInfo = mesh._binaryInfo;
  39938. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39939. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39940. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39941. }
  39942. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39943. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39944. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39945. }
  39946. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39947. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39948. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39949. }
  39950. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39951. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39952. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39953. }
  39954. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39955. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39956. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39957. }
  39958. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39959. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39960. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39961. }
  39962. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39963. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39964. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39965. }
  39966. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39967. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39968. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39969. }
  39970. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39971. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39972. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39973. }
  39974. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39975. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39976. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39977. }
  39978. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39979. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39980. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39981. }
  39982. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39983. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39984. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39985. }
  39986. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39987. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39988. mesh.setIndices(indicesData, null);
  39989. }
  39990. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39991. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39992. mesh.subMeshes = [];
  39993. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39994. var materialIndex = subMeshesData[(i * 5) + 0];
  39995. var verticesStart = subMeshesData[(i * 5) + 1];
  39996. var verticesCount = subMeshesData[(i * 5) + 2];
  39997. var indexStart = subMeshesData[(i * 5) + 3];
  39998. var indexCount = subMeshesData[(i * 5) + 4];
  39999. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40000. }
  40001. }
  40002. }
  40003. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40004. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40005. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40006. if (parsedGeometry.tangents) {
  40007. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  40008. }
  40009. if (parsedGeometry.uvs) {
  40010. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40011. }
  40012. if (parsedGeometry.uvs2) {
  40013. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40014. }
  40015. if (parsedGeometry.uvs3) {
  40016. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40017. }
  40018. if (parsedGeometry.uvs4) {
  40019. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40020. }
  40021. if (parsedGeometry.uvs5) {
  40022. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40023. }
  40024. if (parsedGeometry.uvs6) {
  40025. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40026. }
  40027. if (parsedGeometry.colors) {
  40028. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40029. }
  40030. if (parsedGeometry.matricesIndices) {
  40031. if (!parsedGeometry.matricesIndices._isExpanded) {
  40032. var floatIndices = [];
  40033. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40034. var matricesIndex = parsedGeometry.matricesIndices[i];
  40035. floatIndices.push(matricesIndex & 0x000000FF);
  40036. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40037. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40038. floatIndices.push(matricesIndex >> 24);
  40039. }
  40040. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40041. }
  40042. else {
  40043. delete parsedGeometry.matricesIndices._isExpanded;
  40044. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40045. }
  40046. }
  40047. if (parsedGeometry.matricesIndicesExtra) {
  40048. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40049. var floatIndices = [];
  40050. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40051. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40052. floatIndices.push(matricesIndex & 0x000000FF);
  40053. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40054. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40055. floatIndices.push(matricesIndex >> 24);
  40056. }
  40057. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40058. }
  40059. else {
  40060. delete parsedGeometry.matricesIndices._isExpanded;
  40061. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40062. }
  40063. }
  40064. if (parsedGeometry.matricesWeights) {
  40065. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40066. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40067. }
  40068. if (parsedGeometry.matricesWeightsExtra) {
  40069. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40070. }
  40071. mesh.setIndices(parsedGeometry.indices, null);
  40072. }
  40073. // SubMeshes
  40074. if (parsedGeometry.subMeshes) {
  40075. mesh.subMeshes = [];
  40076. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40077. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40078. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40079. }
  40080. }
  40081. // Flat shading
  40082. if (mesh._shouldGenerateFlatShading) {
  40083. mesh.convertToFlatShadedMesh();
  40084. delete mesh._shouldGenerateFlatShading;
  40085. }
  40086. // Update
  40087. mesh.computeWorldMatrix(true);
  40088. // Octree
  40089. var sceneOctree = scene.selectionOctree;
  40090. if (sceneOctree !== undefined && sceneOctree !== null) {
  40091. sceneOctree.addMesh(mesh);
  40092. }
  40093. };
  40094. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40095. var epsilon = 1e-3;
  40096. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40097. return;
  40098. }
  40099. var noInfluenceBoneIndex = 0.0;
  40100. if (parsedGeometry.skeletonId > -1) {
  40101. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40102. if (!skeleton) {
  40103. return;
  40104. }
  40105. noInfluenceBoneIndex = skeleton.bones.length;
  40106. }
  40107. else {
  40108. return;
  40109. }
  40110. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40111. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40112. var matricesWeights = parsedGeometry.matricesWeights;
  40113. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40114. var influencers = parsedGeometry.numBoneInfluencer;
  40115. var size = matricesWeights.length;
  40116. for (var i = 0; i < size; i += 4) {
  40117. var weight = 0.0;
  40118. var firstZeroWeight = -1;
  40119. for (var j = 0; j < 4; j++) {
  40120. var w = matricesWeights[i + j];
  40121. weight += w;
  40122. if (w < epsilon && firstZeroWeight < 0) {
  40123. firstZeroWeight = j;
  40124. }
  40125. }
  40126. if (matricesWeightsExtra) {
  40127. for (var j = 0; j < 4; j++) {
  40128. var w = matricesWeightsExtra[i + j];
  40129. weight += w;
  40130. if (w < epsilon && firstZeroWeight < 0) {
  40131. firstZeroWeight = j + 4;
  40132. }
  40133. }
  40134. }
  40135. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40136. firstZeroWeight = influencers - 1;
  40137. }
  40138. if (weight > epsilon) {
  40139. var mweight = 1.0 / weight;
  40140. for (var j = 0; j < 4; j++) {
  40141. matricesWeights[i + j] *= mweight;
  40142. }
  40143. if (matricesWeightsExtra) {
  40144. for (var j = 0; j < 4; j++) {
  40145. matricesWeightsExtra[i + j] *= mweight;
  40146. }
  40147. }
  40148. }
  40149. else {
  40150. if (firstZeroWeight >= 4) {
  40151. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40152. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40153. }
  40154. else {
  40155. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40156. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40157. }
  40158. }
  40159. }
  40160. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40161. if (parsedGeometry.matricesWeightsExtra) {
  40162. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40163. }
  40164. };
  40165. /**
  40166. * Create a new geometry from persisted data (Using .babylon file format)
  40167. * @param parsedVertexData defines the persisted data
  40168. * @param scene defines the hosting scene
  40169. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40170. * @returns the new geometry object
  40171. */
  40172. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40173. if (scene.getGeometryByID(parsedVertexData.id)) {
  40174. return null; // null since geometry could be something else than a box...
  40175. }
  40176. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40177. if (BABYLON.Tags) {
  40178. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40179. }
  40180. if (parsedVertexData.delayLoadingFile) {
  40181. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40182. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40183. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40184. geometry._delayInfo = [];
  40185. if (parsedVertexData.hasUVs) {
  40186. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40187. }
  40188. if (parsedVertexData.hasUVs2) {
  40189. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40190. }
  40191. if (parsedVertexData.hasUVs3) {
  40192. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40193. }
  40194. if (parsedVertexData.hasUVs4) {
  40195. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40196. }
  40197. if (parsedVertexData.hasUVs5) {
  40198. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40199. }
  40200. if (parsedVertexData.hasUVs6) {
  40201. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40202. }
  40203. if (parsedVertexData.hasColors) {
  40204. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40205. }
  40206. if (parsedVertexData.hasMatricesIndices) {
  40207. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40208. }
  40209. if (parsedVertexData.hasMatricesWeights) {
  40210. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40211. }
  40212. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40213. }
  40214. else {
  40215. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40216. }
  40217. scene.pushGeometry(geometry, true);
  40218. return geometry;
  40219. };
  40220. return Geometry;
  40221. }());
  40222. BABYLON.Geometry = Geometry;
  40223. // Primitives
  40224. /// Abstract class
  40225. /**
  40226. * Abstract class used to provide common services for all typed geometries
  40227. * @hidden
  40228. */
  40229. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40230. __extends(_PrimitiveGeometry, _super);
  40231. /**
  40232. * Creates a new typed geometry
  40233. * @param id defines the unique ID of the geometry
  40234. * @param scene defines the hosting scene
  40235. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40236. * @param mesh defines the hosting mesh (can be null)
  40237. */
  40238. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40239. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40240. if (mesh === void 0) { mesh = null; }
  40241. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40242. _this._canBeRegenerated = _canBeRegenerated;
  40243. _this._beingRegenerated = true;
  40244. _this.regenerate();
  40245. _this._beingRegenerated = false;
  40246. return _this;
  40247. }
  40248. /**
  40249. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40250. * @returns true if the geometry can be regenerated
  40251. */
  40252. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40253. return this._canBeRegenerated;
  40254. };
  40255. /**
  40256. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40257. */
  40258. _PrimitiveGeometry.prototype.regenerate = function () {
  40259. if (!this._canBeRegenerated) {
  40260. return;
  40261. }
  40262. this._beingRegenerated = true;
  40263. this.setAllVerticesData(this._regenerateVertexData(), false);
  40264. this._beingRegenerated = false;
  40265. };
  40266. /**
  40267. * Clone the geometry
  40268. * @param id defines the unique ID of the new geometry
  40269. * @returns the new geometry
  40270. */
  40271. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40272. return _super.prototype.copy.call(this, id);
  40273. };
  40274. // overrides
  40275. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40276. if (!this._beingRegenerated) {
  40277. return;
  40278. }
  40279. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40280. };
  40281. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40282. if (!this._beingRegenerated) {
  40283. return;
  40284. }
  40285. _super.prototype.setVerticesData.call(this, kind, data, false);
  40286. };
  40287. // to override
  40288. /** @hidden */
  40289. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40290. throw new Error("Abstract method");
  40291. };
  40292. _PrimitiveGeometry.prototype.copy = function (id) {
  40293. throw new Error("Must be overriden in sub-classes.");
  40294. };
  40295. _PrimitiveGeometry.prototype.serialize = function () {
  40296. var serializationObject = _super.prototype.serialize.call(this);
  40297. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40298. return serializationObject;
  40299. };
  40300. return _PrimitiveGeometry;
  40301. }(Geometry));
  40302. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40303. /**
  40304. * Creates a ribbon geometry
  40305. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40306. */
  40307. var RibbonGeometry = /** @class */ (function (_super) {
  40308. __extends(RibbonGeometry, _super);
  40309. /**
  40310. * Creates a ribbon geometry
  40311. * @param id defines the unique ID of the geometry
  40312. * @param scene defines the hosting scene
  40313. * @param pathArray defines the array of paths to use
  40314. * @param closeArray defines if the last path and the first path must be joined
  40315. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40316. * @param offset defines the offset between points
  40317. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40318. * @param mesh defines the hosting mesh (can be null)
  40319. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40320. */
  40321. function RibbonGeometry(id, scene,
  40322. /**
  40323. * Defines the array of paths to use
  40324. */
  40325. pathArray,
  40326. /**
  40327. * Defines if the last and first points of each path in your pathArray must be joined
  40328. */
  40329. closeArray,
  40330. /**
  40331. * Defines if the last and first points of each path in your pathArray must be joined
  40332. */
  40333. closePath,
  40334. /**
  40335. * Defines the offset between points
  40336. */
  40337. offset, canBeRegenerated, mesh,
  40338. /**
  40339. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40340. */
  40341. side) {
  40342. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40343. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40344. _this.pathArray = pathArray;
  40345. _this.closeArray = closeArray;
  40346. _this.closePath = closePath;
  40347. _this.offset = offset;
  40348. _this.side = side;
  40349. return _this;
  40350. }
  40351. /** @hidden */
  40352. RibbonGeometry.prototype._regenerateVertexData = function () {
  40353. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40354. };
  40355. RibbonGeometry.prototype.copy = function (id) {
  40356. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40357. };
  40358. return RibbonGeometry;
  40359. }(_PrimitiveGeometry));
  40360. BABYLON.RibbonGeometry = RibbonGeometry;
  40361. /**
  40362. * Creates a box geometry
  40363. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40364. */
  40365. var BoxGeometry = /** @class */ (function (_super) {
  40366. __extends(BoxGeometry, _super);
  40367. /**
  40368. * Creates a box geometry
  40369. * @param id defines the unique ID of the geometry
  40370. * @param scene defines the hosting scene
  40371. * @param size defines the zise of the box (width, height and depth are the same)
  40372. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40373. * @param mesh defines the hosting mesh (can be null)
  40374. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40375. */
  40376. function BoxGeometry(id, scene,
  40377. /**
  40378. * Defines the zise of the box (width, height and depth are the same)
  40379. */
  40380. size, canBeRegenerated, mesh,
  40381. /**
  40382. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40383. */
  40384. side) {
  40385. if (mesh === void 0) { mesh = null; }
  40386. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40387. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40388. _this.size = size;
  40389. _this.side = side;
  40390. return _this;
  40391. }
  40392. BoxGeometry.prototype._regenerateVertexData = function () {
  40393. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40394. };
  40395. BoxGeometry.prototype.copy = function (id) {
  40396. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40397. };
  40398. BoxGeometry.prototype.serialize = function () {
  40399. var serializationObject = _super.prototype.serialize.call(this);
  40400. serializationObject.size = this.size;
  40401. return serializationObject;
  40402. };
  40403. BoxGeometry.Parse = function (parsedBox, scene) {
  40404. if (scene.getGeometryByID(parsedBox.id)) {
  40405. return null; // null since geometry could be something else than a box...
  40406. }
  40407. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40408. if (BABYLON.Tags) {
  40409. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40410. }
  40411. scene.pushGeometry(box, true);
  40412. return box;
  40413. };
  40414. return BoxGeometry;
  40415. }(_PrimitiveGeometry));
  40416. BABYLON.BoxGeometry = BoxGeometry;
  40417. /**
  40418. * Creates a sphere geometry
  40419. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40420. */
  40421. var SphereGeometry = /** @class */ (function (_super) {
  40422. __extends(SphereGeometry, _super);
  40423. /**
  40424. * Create a new sphere geometry
  40425. * @param id defines the unique ID of the geometry
  40426. * @param scene defines the hosting scene
  40427. * @param segments defines the number of segments to use to create the sphere
  40428. * @param diameter defines the diameter of the sphere
  40429. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40430. * @param mesh defines the hosting mesh (can be null)
  40431. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40432. */
  40433. function SphereGeometry(id, scene,
  40434. /**
  40435. * Defines the number of segments to use to create the sphere
  40436. */
  40437. segments,
  40438. /**
  40439. * Defines the diameter of the sphere
  40440. */
  40441. diameter, canBeRegenerated, mesh,
  40442. /**
  40443. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40444. */
  40445. side) {
  40446. if (mesh === void 0) { mesh = null; }
  40447. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40448. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40449. _this.segments = segments;
  40450. _this.diameter = diameter;
  40451. _this.side = side;
  40452. return _this;
  40453. }
  40454. SphereGeometry.prototype._regenerateVertexData = function () {
  40455. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40456. };
  40457. SphereGeometry.prototype.copy = function (id) {
  40458. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40459. };
  40460. SphereGeometry.prototype.serialize = function () {
  40461. var serializationObject = _super.prototype.serialize.call(this);
  40462. serializationObject.segments = this.segments;
  40463. serializationObject.diameter = this.diameter;
  40464. return serializationObject;
  40465. };
  40466. SphereGeometry.Parse = function (parsedSphere, scene) {
  40467. if (scene.getGeometryByID(parsedSphere.id)) {
  40468. return null; // null since geometry could be something else than a sphere...
  40469. }
  40470. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40471. if (BABYLON.Tags) {
  40472. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40473. }
  40474. scene.pushGeometry(sphere, true);
  40475. return sphere;
  40476. };
  40477. return SphereGeometry;
  40478. }(_PrimitiveGeometry));
  40479. BABYLON.SphereGeometry = SphereGeometry;
  40480. /**
  40481. * Creates a disc geometry
  40482. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40483. */
  40484. var DiscGeometry = /** @class */ (function (_super) {
  40485. __extends(DiscGeometry, _super);
  40486. /**
  40487. * Creates a new disc geometry
  40488. * @param id defines the unique ID of the geometry
  40489. * @param scene defines the hosting scene
  40490. * @param radius defines the radius of the disc
  40491. * @param tessellation defines the tesselation factor to apply to the disc
  40492. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40493. * @param mesh defines the hosting mesh (can be null)
  40494. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40495. */
  40496. function DiscGeometry(id, scene,
  40497. /**
  40498. * Defines the radius of the disc
  40499. */
  40500. radius,
  40501. /**
  40502. * Defines the tesselation factor to apply to the disc
  40503. */
  40504. tessellation, canBeRegenerated, mesh,
  40505. /**
  40506. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40507. */
  40508. side) {
  40509. if (mesh === void 0) { mesh = null; }
  40510. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40511. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40512. _this.radius = radius;
  40513. _this.tessellation = tessellation;
  40514. _this.side = side;
  40515. return _this;
  40516. }
  40517. DiscGeometry.prototype._regenerateVertexData = function () {
  40518. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40519. };
  40520. DiscGeometry.prototype.copy = function (id) {
  40521. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40522. };
  40523. return DiscGeometry;
  40524. }(_PrimitiveGeometry));
  40525. BABYLON.DiscGeometry = DiscGeometry;
  40526. /**
  40527. * Creates a new cylinder geometry
  40528. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40529. */
  40530. var CylinderGeometry = /** @class */ (function (_super) {
  40531. __extends(CylinderGeometry, _super);
  40532. /**
  40533. * Creates a new cylinder geometry
  40534. * @param id defines the unique ID of the geometry
  40535. * @param scene defines the hosting scene
  40536. * @param height defines the height of the cylinder
  40537. * @param diameterTop defines the diameter of the cylinder's top cap
  40538. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40539. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40540. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40541. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40542. * @param mesh defines the hosting mesh (can be null)
  40543. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40544. */
  40545. function CylinderGeometry(id, scene,
  40546. /**
  40547. * Defines the height of the cylinder
  40548. */
  40549. height,
  40550. /**
  40551. * Defines the diameter of the cylinder's top cap
  40552. */
  40553. diameterTop,
  40554. /**
  40555. * Defines the diameter of the cylinder's bottom cap
  40556. */
  40557. diameterBottom,
  40558. /**
  40559. * Defines the tessellation factor to apply to the cylinder
  40560. */
  40561. tessellation,
  40562. /**
  40563. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40564. */
  40565. subdivisions, canBeRegenerated, mesh,
  40566. /**
  40567. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40568. */
  40569. side) {
  40570. if (subdivisions === void 0) { subdivisions = 1; }
  40571. if (mesh === void 0) { mesh = null; }
  40572. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40573. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40574. _this.height = height;
  40575. _this.diameterTop = diameterTop;
  40576. _this.diameterBottom = diameterBottom;
  40577. _this.tessellation = tessellation;
  40578. _this.subdivisions = subdivisions;
  40579. _this.side = side;
  40580. return _this;
  40581. }
  40582. CylinderGeometry.prototype._regenerateVertexData = function () {
  40583. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40584. };
  40585. CylinderGeometry.prototype.copy = function (id) {
  40586. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40587. };
  40588. CylinderGeometry.prototype.serialize = function () {
  40589. var serializationObject = _super.prototype.serialize.call(this);
  40590. serializationObject.height = this.height;
  40591. serializationObject.diameterTop = this.diameterTop;
  40592. serializationObject.diameterBottom = this.diameterBottom;
  40593. serializationObject.tessellation = this.tessellation;
  40594. return serializationObject;
  40595. };
  40596. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40597. if (scene.getGeometryByID(parsedCylinder.id)) {
  40598. return null; // null since geometry could be something else than a cylinder...
  40599. }
  40600. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40601. if (BABYLON.Tags) {
  40602. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40603. }
  40604. scene.pushGeometry(cylinder, true);
  40605. return cylinder;
  40606. };
  40607. return CylinderGeometry;
  40608. }(_PrimitiveGeometry));
  40609. BABYLON.CylinderGeometry = CylinderGeometry;
  40610. /**
  40611. * Creates a new torus geometry
  40612. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40613. */
  40614. var TorusGeometry = /** @class */ (function (_super) {
  40615. __extends(TorusGeometry, _super);
  40616. /**
  40617. * Creates a new torus geometry
  40618. * @param id defines the unique ID of the geometry
  40619. * @param scene defines the hosting scene
  40620. * @param diameter defines the diameter of the torus
  40621. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40622. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40623. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40624. * @param mesh defines the hosting mesh (can be null)
  40625. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40626. */
  40627. function TorusGeometry(id, scene,
  40628. /**
  40629. * Defines the diameter of the torus
  40630. */
  40631. diameter,
  40632. /**
  40633. * Defines the thickness of the torus (ie. internal diameter)
  40634. */
  40635. thickness,
  40636. /**
  40637. * Defines the tesselation factor to apply to the torus
  40638. */
  40639. tessellation, canBeRegenerated, mesh,
  40640. /**
  40641. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40642. */
  40643. side) {
  40644. if (mesh === void 0) { mesh = null; }
  40645. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40646. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40647. _this.diameter = diameter;
  40648. _this.thickness = thickness;
  40649. _this.tessellation = tessellation;
  40650. _this.side = side;
  40651. return _this;
  40652. }
  40653. TorusGeometry.prototype._regenerateVertexData = function () {
  40654. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40655. };
  40656. TorusGeometry.prototype.copy = function (id) {
  40657. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40658. };
  40659. TorusGeometry.prototype.serialize = function () {
  40660. var serializationObject = _super.prototype.serialize.call(this);
  40661. serializationObject.diameter = this.diameter;
  40662. serializationObject.thickness = this.thickness;
  40663. serializationObject.tessellation = this.tessellation;
  40664. return serializationObject;
  40665. };
  40666. TorusGeometry.Parse = function (parsedTorus, scene) {
  40667. if (scene.getGeometryByID(parsedTorus.id)) {
  40668. return null; // null since geometry could be something else than a torus...
  40669. }
  40670. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40671. if (BABYLON.Tags) {
  40672. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40673. }
  40674. scene.pushGeometry(torus, true);
  40675. return torus;
  40676. };
  40677. return TorusGeometry;
  40678. }(_PrimitiveGeometry));
  40679. BABYLON.TorusGeometry = TorusGeometry;
  40680. /**
  40681. * Creates a new ground geometry
  40682. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40683. */
  40684. var GroundGeometry = /** @class */ (function (_super) {
  40685. __extends(GroundGeometry, _super);
  40686. /**
  40687. * Creates a new ground geometry
  40688. * @param id defines the unique ID of the geometry
  40689. * @param scene defines the hosting scene
  40690. * @param width defines the width of the ground
  40691. * @param height defines the height of the ground
  40692. * @param subdivisions defines the subdivisions to apply to the ground
  40693. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40694. * @param mesh defines the hosting mesh (can be null)
  40695. */
  40696. function GroundGeometry(id, scene,
  40697. /**
  40698. * Defines the width of the ground
  40699. */
  40700. width,
  40701. /**
  40702. * Defines the height of the ground
  40703. */
  40704. height,
  40705. /**
  40706. * Defines the subdivisions to apply to the ground
  40707. */
  40708. subdivisions, canBeRegenerated, mesh) {
  40709. if (mesh === void 0) { mesh = null; }
  40710. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40711. _this.width = width;
  40712. _this.height = height;
  40713. _this.subdivisions = subdivisions;
  40714. return _this;
  40715. }
  40716. GroundGeometry.prototype._regenerateVertexData = function () {
  40717. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40718. };
  40719. GroundGeometry.prototype.copy = function (id) {
  40720. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40721. };
  40722. GroundGeometry.prototype.serialize = function () {
  40723. var serializationObject = _super.prototype.serialize.call(this);
  40724. serializationObject.width = this.width;
  40725. serializationObject.height = this.height;
  40726. serializationObject.subdivisions = this.subdivisions;
  40727. return serializationObject;
  40728. };
  40729. GroundGeometry.Parse = function (parsedGround, scene) {
  40730. if (scene.getGeometryByID(parsedGround.id)) {
  40731. return null; // null since geometry could be something else than a ground...
  40732. }
  40733. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40734. if (BABYLON.Tags) {
  40735. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40736. }
  40737. scene.pushGeometry(ground, true);
  40738. return ground;
  40739. };
  40740. return GroundGeometry;
  40741. }(_PrimitiveGeometry));
  40742. BABYLON.GroundGeometry = GroundGeometry;
  40743. /**
  40744. * Creates a tiled ground geometry
  40745. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40746. */
  40747. var TiledGroundGeometry = /** @class */ (function (_super) {
  40748. __extends(TiledGroundGeometry, _super);
  40749. /**
  40750. * Creates a tiled ground geometry
  40751. * @param id defines the unique ID of the geometry
  40752. * @param scene defines the hosting scene
  40753. * @param xmin defines the minimum value on X axis
  40754. * @param zmin defines the minimum value on Z axis
  40755. * @param xmax defines the maximum value on X axis
  40756. * @param zmax defines the maximum value on Z axis
  40757. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40758. * @param precision defines the precision to use when computing the tiles
  40759. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40760. * @param mesh defines the hosting mesh (can be null)
  40761. */
  40762. function TiledGroundGeometry(id, scene,
  40763. /**
  40764. * Defines the minimum value on X axis
  40765. */
  40766. xmin,
  40767. /**
  40768. * Defines the minimum value on Z axis
  40769. */
  40770. zmin,
  40771. /**
  40772. * Defines the maximum value on X axis
  40773. */
  40774. xmax,
  40775. /**
  40776. * Defines the maximum value on Z axis
  40777. */
  40778. zmax,
  40779. /**
  40780. * Defines the subdivisions to apply to the ground
  40781. */
  40782. subdivisions,
  40783. /**
  40784. * Defines the precision to use when computing the tiles
  40785. */
  40786. precision, canBeRegenerated, mesh) {
  40787. if (mesh === void 0) { mesh = null; }
  40788. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40789. _this.xmin = xmin;
  40790. _this.zmin = zmin;
  40791. _this.xmax = xmax;
  40792. _this.zmax = zmax;
  40793. _this.subdivisions = subdivisions;
  40794. _this.precision = precision;
  40795. return _this;
  40796. }
  40797. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40798. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40799. };
  40800. TiledGroundGeometry.prototype.copy = function (id) {
  40801. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40802. };
  40803. return TiledGroundGeometry;
  40804. }(_PrimitiveGeometry));
  40805. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40806. /**
  40807. * Creates a plane geometry
  40808. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40809. */
  40810. var PlaneGeometry = /** @class */ (function (_super) {
  40811. __extends(PlaneGeometry, _super);
  40812. /**
  40813. * Creates a plane geometry
  40814. * @param id defines the unique ID of the geometry
  40815. * @param scene defines the hosting scene
  40816. * @param size defines the size of the plane (width === height)
  40817. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40818. * @param mesh defines the hosting mesh (can be null)
  40819. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40820. */
  40821. function PlaneGeometry(id, scene,
  40822. /**
  40823. * Defines the size of the plane (width === height)
  40824. */
  40825. size, canBeRegenerated, mesh,
  40826. /**
  40827. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40828. */
  40829. side) {
  40830. if (mesh === void 0) { mesh = null; }
  40831. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40832. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40833. _this.size = size;
  40834. _this.side = side;
  40835. return _this;
  40836. }
  40837. PlaneGeometry.prototype._regenerateVertexData = function () {
  40838. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40839. };
  40840. PlaneGeometry.prototype.copy = function (id) {
  40841. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40842. };
  40843. PlaneGeometry.prototype.serialize = function () {
  40844. var serializationObject = _super.prototype.serialize.call(this);
  40845. serializationObject.size = this.size;
  40846. return serializationObject;
  40847. };
  40848. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40849. if (scene.getGeometryByID(parsedPlane.id)) {
  40850. return null; // null since geometry could be something else than a ground...
  40851. }
  40852. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40853. if (BABYLON.Tags) {
  40854. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40855. }
  40856. scene.pushGeometry(plane, true);
  40857. return plane;
  40858. };
  40859. return PlaneGeometry;
  40860. }(_PrimitiveGeometry));
  40861. BABYLON.PlaneGeometry = PlaneGeometry;
  40862. /**
  40863. * Creates a torus knot geometry
  40864. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40865. */
  40866. var TorusKnotGeometry = /** @class */ (function (_super) {
  40867. __extends(TorusKnotGeometry, _super);
  40868. /**
  40869. * Creates a torus knot geometry
  40870. * @param id defines the unique ID of the geometry
  40871. * @param scene defines the hosting scene
  40872. * @param radius defines the radius of the torus knot
  40873. * @param tube defines the thickness of the torus knot tube
  40874. * @param radialSegments defines the number of radial segments
  40875. * @param tubularSegments defines the number of tubular segments
  40876. * @param p defines the first number of windings
  40877. * @param q defines the second number of windings
  40878. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40879. * @param mesh defines the hosting mesh (can be null)
  40880. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40881. */
  40882. function TorusKnotGeometry(id, scene,
  40883. /**
  40884. * Defines the radius of the torus knot
  40885. */
  40886. radius,
  40887. /**
  40888. * Defines the thickness of the torus knot tube
  40889. */
  40890. tube,
  40891. /**
  40892. * Defines the number of radial segments
  40893. */
  40894. radialSegments,
  40895. /**
  40896. * Defines the number of tubular segments
  40897. */
  40898. tubularSegments,
  40899. /**
  40900. * Defines the first number of windings
  40901. */
  40902. p,
  40903. /**
  40904. * Defines the second number of windings
  40905. */
  40906. q, canBeRegenerated, mesh,
  40907. /**
  40908. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40909. */
  40910. side) {
  40911. if (mesh === void 0) { mesh = null; }
  40912. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40913. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40914. _this.radius = radius;
  40915. _this.tube = tube;
  40916. _this.radialSegments = radialSegments;
  40917. _this.tubularSegments = tubularSegments;
  40918. _this.p = p;
  40919. _this.q = q;
  40920. _this.side = side;
  40921. return _this;
  40922. }
  40923. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40924. 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 });
  40925. };
  40926. TorusKnotGeometry.prototype.copy = function (id) {
  40927. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40928. };
  40929. TorusKnotGeometry.prototype.serialize = function () {
  40930. var serializationObject = _super.prototype.serialize.call(this);
  40931. serializationObject.radius = this.radius;
  40932. serializationObject.tube = this.tube;
  40933. serializationObject.radialSegments = this.radialSegments;
  40934. serializationObject.tubularSegments = this.tubularSegments;
  40935. serializationObject.p = this.p;
  40936. serializationObject.q = this.q;
  40937. return serializationObject;
  40938. };
  40939. ;
  40940. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40941. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40942. return null; // null since geometry could be something else than a ground...
  40943. }
  40944. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40945. if (BABYLON.Tags) {
  40946. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40947. }
  40948. scene.pushGeometry(torusKnot, true);
  40949. return torusKnot;
  40950. };
  40951. return TorusKnotGeometry;
  40952. }(_PrimitiveGeometry));
  40953. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40954. //}
  40955. })(BABYLON || (BABYLON = {}));
  40956. //# sourceMappingURL=babylon.geometry.js.map
  40957. var BABYLON;
  40958. (function (BABYLON) {
  40959. /**
  40960. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40961. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40962. */
  40963. var PostProcessManager = /** @class */ (function () {
  40964. /**
  40965. * Creates a new instance PostProcess
  40966. * @param scene The scene that the post process is associated with.
  40967. */
  40968. function PostProcessManager(scene) {
  40969. this._vertexBuffers = {};
  40970. this._scene = scene;
  40971. }
  40972. PostProcessManager.prototype._prepareBuffers = function () {
  40973. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40974. return;
  40975. }
  40976. // VBO
  40977. var vertices = [];
  40978. vertices.push(1, 1);
  40979. vertices.push(-1, 1);
  40980. vertices.push(-1, -1);
  40981. vertices.push(1, -1);
  40982. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40983. this._buildIndexBuffer();
  40984. };
  40985. PostProcessManager.prototype._buildIndexBuffer = function () {
  40986. // Indices
  40987. var indices = [];
  40988. indices.push(0);
  40989. indices.push(1);
  40990. indices.push(2);
  40991. indices.push(0);
  40992. indices.push(2);
  40993. indices.push(3);
  40994. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40995. };
  40996. /**
  40997. * Rebuilds the vertex buffers of the manager.
  40998. */
  40999. PostProcessManager.prototype._rebuild = function () {
  41000. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  41001. if (!vb) {
  41002. return;
  41003. }
  41004. vb._rebuild();
  41005. this._buildIndexBuffer();
  41006. };
  41007. // Methods
  41008. /**
  41009. * Prepares a frame to be run through a post process.
  41010. * @param sourceTexture The input texture to the post procesess. (default: null)
  41011. * @param postProcesses An array of post processes to be run. (default: null)
  41012. * @returns True if the post processes were able to be run.
  41013. */
  41014. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  41015. if (sourceTexture === void 0) { sourceTexture = null; }
  41016. if (postProcesses === void 0) { postProcesses = null; }
  41017. var camera = this._scene.activeCamera;
  41018. if (!camera) {
  41019. return false;
  41020. }
  41021. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  41022. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  41023. return false;
  41024. }
  41025. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  41026. return true;
  41027. };
  41028. /**
  41029. * Manually render a set of post processes to a texture.
  41030. * @param postProcesses An array of post processes to be run.
  41031. * @param targetTexture The target texture to render to.
  41032. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  41033. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  41034. * @param lodLevel defines which lod of the texture to render to
  41035. */
  41036. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  41037. if (targetTexture === void 0) { targetTexture = null; }
  41038. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  41039. if (faceIndex === void 0) { faceIndex = 0; }
  41040. if (lodLevel === void 0) { lodLevel = 0; }
  41041. var engine = this._scene.getEngine();
  41042. for (var index = 0; index < postProcesses.length; index++) {
  41043. if (index < postProcesses.length - 1) {
  41044. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  41045. }
  41046. else {
  41047. if (targetTexture) {
  41048. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  41049. }
  41050. else {
  41051. engine.restoreDefaultFramebuffer();
  41052. }
  41053. }
  41054. var pp = postProcesses[index];
  41055. var effect = pp.apply();
  41056. if (effect) {
  41057. pp.onBeforeRenderObservable.notifyObservers(effect);
  41058. // VBOs
  41059. this._prepareBuffers();
  41060. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  41061. // Draw order
  41062. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  41063. pp.onAfterRenderObservable.notifyObservers(effect);
  41064. }
  41065. }
  41066. // Restore depth buffer
  41067. engine.setDepthBuffer(true);
  41068. engine.setDepthWrite(true);
  41069. };
  41070. /**
  41071. * Finalize the result of the output of the postprocesses.
  41072. * @param doNotPresent If true the result will not be displayed to the screen.
  41073. * @param targetTexture The target texture to render to.
  41074. * @param faceIndex The index of the face to bind the target texture to.
  41075. * @param postProcesses The array of post processes to render.
  41076. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  41077. */
  41078. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  41079. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  41080. var camera = this._scene.activeCamera;
  41081. if (!camera) {
  41082. return;
  41083. }
  41084. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  41085. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  41086. return;
  41087. }
  41088. var engine = this._scene.getEngine();
  41089. for (var index = 0, len = postProcesses.length; index < len; index++) {
  41090. var pp = postProcesses[index];
  41091. if (index < len - 1) {
  41092. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  41093. }
  41094. else {
  41095. if (targetTexture) {
  41096. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  41097. pp._outputTexture = targetTexture;
  41098. }
  41099. else {
  41100. engine.restoreDefaultFramebuffer();
  41101. pp._outputTexture = null;
  41102. }
  41103. }
  41104. if (doNotPresent) {
  41105. break;
  41106. }
  41107. var effect = pp.apply();
  41108. if (effect) {
  41109. pp.onBeforeRenderObservable.notifyObservers(effect);
  41110. // VBOs
  41111. this._prepareBuffers();
  41112. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  41113. // Draw order
  41114. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  41115. pp.onAfterRenderObservable.notifyObservers(effect);
  41116. }
  41117. }
  41118. // Restore states
  41119. engine.setDepthBuffer(true);
  41120. engine.setDepthWrite(true);
  41121. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  41122. };
  41123. /**
  41124. * Disposes of the post process manager.
  41125. */
  41126. PostProcessManager.prototype.dispose = function () {
  41127. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  41128. if (buffer) {
  41129. buffer.dispose();
  41130. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  41131. }
  41132. if (this._indexBuffer) {
  41133. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  41134. this._indexBuffer = null;
  41135. }
  41136. };
  41137. return PostProcessManager;
  41138. }());
  41139. BABYLON.PostProcessManager = PostProcessManager;
  41140. })(BABYLON || (BABYLON = {}));
  41141. //# sourceMappingURL=babylon.postProcessManager.js.map
  41142. var BABYLON;
  41143. (function (BABYLON) {
  41144. /**
  41145. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  41146. */
  41147. var PerformanceMonitor = /** @class */ (function () {
  41148. /**
  41149. * constructor
  41150. * @param frameSampleSize The number of samples required to saturate the sliding window
  41151. */
  41152. function PerformanceMonitor(frameSampleSize) {
  41153. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  41154. this._enabled = true;
  41155. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  41156. }
  41157. /**
  41158. * Samples current frame
  41159. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  41160. */
  41161. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41162. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41163. if (!this._enabled)
  41164. return;
  41165. if (this._lastFrameTimeMs != null) {
  41166. var dt = timeMs - this._lastFrameTimeMs;
  41167. this._rollingFrameTime.add(dt);
  41168. }
  41169. this._lastFrameTimeMs = timeMs;
  41170. };
  41171. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41172. /**
  41173. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41174. * @return Average frame time in milliseconds
  41175. */
  41176. get: function () {
  41177. return this._rollingFrameTime.average;
  41178. },
  41179. enumerable: true,
  41180. configurable: true
  41181. });
  41182. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41183. /**
  41184. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41185. * @return Frame time variance in milliseconds squared
  41186. */
  41187. get: function () {
  41188. return this._rollingFrameTime.variance;
  41189. },
  41190. enumerable: true,
  41191. configurable: true
  41192. });
  41193. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41194. /**
  41195. * Returns the frame time of the most recent frame
  41196. * @return Frame time in milliseconds
  41197. */
  41198. get: function () {
  41199. return this._rollingFrameTime.history(0);
  41200. },
  41201. enumerable: true,
  41202. configurable: true
  41203. });
  41204. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41205. /**
  41206. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41207. * @return Framerate in frames per second
  41208. */
  41209. get: function () {
  41210. return 1000.0 / this._rollingFrameTime.average;
  41211. },
  41212. enumerable: true,
  41213. configurable: true
  41214. });
  41215. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41216. /**
  41217. * Returns the average framerate in frames per second using the most recent frame time
  41218. * @return Framerate in frames per second
  41219. */
  41220. get: function () {
  41221. var history = this._rollingFrameTime.history(0);
  41222. if (history === 0) {
  41223. return 0;
  41224. }
  41225. return 1000.0 / history;
  41226. },
  41227. enumerable: true,
  41228. configurable: true
  41229. });
  41230. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41231. /**
  41232. * Returns true if enough samples have been taken to completely fill the sliding window
  41233. * @return true if saturated
  41234. */
  41235. get: function () {
  41236. return this._rollingFrameTime.isSaturated();
  41237. },
  41238. enumerable: true,
  41239. configurable: true
  41240. });
  41241. /**
  41242. * Enables contributions to the sliding window sample set
  41243. */
  41244. PerformanceMonitor.prototype.enable = function () {
  41245. this._enabled = true;
  41246. };
  41247. /**
  41248. * Disables contributions to the sliding window sample set
  41249. * Samples will not be interpolated over the disabled period
  41250. */
  41251. PerformanceMonitor.prototype.disable = function () {
  41252. this._enabled = false;
  41253. //clear last sample to avoid interpolating over the disabled period when next enabled
  41254. this._lastFrameTimeMs = null;
  41255. };
  41256. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41257. /**
  41258. * Returns true if sampling is enabled
  41259. * @return true if enabled
  41260. */
  41261. get: function () {
  41262. return this._enabled;
  41263. },
  41264. enumerable: true,
  41265. configurable: true
  41266. });
  41267. /**
  41268. * Resets performance monitor
  41269. */
  41270. PerformanceMonitor.prototype.reset = function () {
  41271. //clear last sample to avoid interpolating over the disabled period when next enabled
  41272. this._lastFrameTimeMs = null;
  41273. //wipe record
  41274. this._rollingFrameTime.reset();
  41275. };
  41276. return PerformanceMonitor;
  41277. }());
  41278. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41279. /**
  41280. * RollingAverage
  41281. *
  41282. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41283. */
  41284. var RollingAverage = /** @class */ (function () {
  41285. /**
  41286. * constructor
  41287. * @param length The number of samples required to saturate the sliding window
  41288. */
  41289. function RollingAverage(length) {
  41290. this._samples = new Array(length);
  41291. this.reset();
  41292. }
  41293. /**
  41294. * Adds a sample to the sample set
  41295. * @param v The sample value
  41296. */
  41297. RollingAverage.prototype.add = function (v) {
  41298. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41299. var delta;
  41300. //we need to check if we've already wrapped round
  41301. if (this.isSaturated()) {
  41302. //remove bottom of stack from mean
  41303. var bottomValue = this._samples[this._pos];
  41304. delta = bottomValue - this.average;
  41305. this.average -= delta / (this._sampleCount - 1);
  41306. this._m2 -= delta * (bottomValue - this.average);
  41307. }
  41308. else {
  41309. this._sampleCount++;
  41310. }
  41311. //add new value to mean
  41312. delta = v - this.average;
  41313. this.average += delta / (this._sampleCount);
  41314. this._m2 += delta * (v - this.average);
  41315. //set the new variance
  41316. this.variance = this._m2 / (this._sampleCount - 1);
  41317. this._samples[this._pos] = v;
  41318. this._pos++;
  41319. this._pos %= this._samples.length; //positive wrap around
  41320. };
  41321. /**
  41322. * Returns previously added values or null if outside of history or outside the sliding window domain
  41323. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41324. * @return Value previously recorded with add() or null if outside of range
  41325. */
  41326. RollingAverage.prototype.history = function (i) {
  41327. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41328. return 0;
  41329. }
  41330. var i0 = this._wrapPosition(this._pos - 1.0);
  41331. return this._samples[this._wrapPosition(i0 - i)];
  41332. };
  41333. /**
  41334. * Returns true if enough samples have been taken to completely fill the sliding window
  41335. * @return true if sample-set saturated
  41336. */
  41337. RollingAverage.prototype.isSaturated = function () {
  41338. return this._sampleCount >= this._samples.length;
  41339. };
  41340. /**
  41341. * Resets the rolling average (equivalent to 0 samples taken so far)
  41342. */
  41343. RollingAverage.prototype.reset = function () {
  41344. this.average = 0;
  41345. this.variance = 0;
  41346. this._sampleCount = 0;
  41347. this._pos = 0;
  41348. this._m2 = 0;
  41349. };
  41350. /**
  41351. * Wraps a value around the sample range boundaries
  41352. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41353. * @return Wrapped position in sample range
  41354. */
  41355. RollingAverage.prototype._wrapPosition = function (i) {
  41356. var max = this._samples.length;
  41357. return ((i % max) + max) % max;
  41358. };
  41359. return RollingAverage;
  41360. }());
  41361. BABYLON.RollingAverage = RollingAverage;
  41362. })(BABYLON || (BABYLON = {}));
  41363. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41364. var BABYLON;
  41365. (function (BABYLON) {
  41366. /**
  41367. * This groups together the common properties used for image processing either in direct forward pass
  41368. * or through post processing effect depending on the use of the image processing pipeline in your scene
  41369. * or not.
  41370. */
  41371. var ImageProcessingConfiguration = /** @class */ (function () {
  41372. function ImageProcessingConfiguration() {
  41373. /**
  41374. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  41375. */
  41376. this.colorCurves = new BABYLON.ColorCurves();
  41377. this._colorCurvesEnabled = false;
  41378. this._colorGradingEnabled = false;
  41379. this._colorGradingWithGreenDepth = true;
  41380. this._colorGradingBGR = true;
  41381. this._exposure = 1.0;
  41382. this._toneMappingEnabled = false;
  41383. this._contrast = 1.0;
  41384. /**
  41385. * Vignette stretch size.
  41386. */
  41387. this.vignetteStretch = 0;
  41388. /**
  41389. * Vignette centre X Offset.
  41390. */
  41391. this.vignetteCentreX = 0;
  41392. /**
  41393. * Vignette centre Y Offset.
  41394. */
  41395. this.vignetteCentreY = 0;
  41396. /**
  41397. * Vignette weight or intensity of the vignette effect.
  41398. */
  41399. this.vignetteWeight = 1.5;
  41400. /**
  41401. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41402. * if vignetteEnabled is set to true.
  41403. */
  41404. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  41405. /**
  41406. * Camera field of view used by the Vignette effect.
  41407. */
  41408. this.vignetteCameraFov = 0.5;
  41409. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  41410. this._vignetteEnabled = false;
  41411. this._applyByPostProcess = false;
  41412. this._isEnabled = true;
  41413. /**
  41414. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  41415. */
  41416. this.onUpdateParameters = new BABYLON.Observable();
  41417. }
  41418. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  41419. /**
  41420. * Gets wether the color curves effect is enabled.
  41421. */
  41422. get: function () {
  41423. return this._colorCurvesEnabled;
  41424. },
  41425. /**
  41426. * Sets wether the color curves effect is enabled.
  41427. */
  41428. set: function (value) {
  41429. if (this._colorCurvesEnabled === value) {
  41430. return;
  41431. }
  41432. this._colorCurvesEnabled = value;
  41433. this._updateParameters();
  41434. },
  41435. enumerable: true,
  41436. configurable: true
  41437. });
  41438. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  41439. /**
  41440. * Gets wether the color grading effect is enabled.
  41441. */
  41442. get: function () {
  41443. return this._colorGradingEnabled;
  41444. },
  41445. /**
  41446. * Sets wether the color grading effect is enabled.
  41447. */
  41448. set: function (value) {
  41449. if (this._colorGradingEnabled === value) {
  41450. return;
  41451. }
  41452. this._colorGradingEnabled = value;
  41453. this._updateParameters();
  41454. },
  41455. enumerable: true,
  41456. configurable: true
  41457. });
  41458. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  41459. /**
  41460. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  41461. */
  41462. get: function () {
  41463. return this._colorGradingWithGreenDepth;
  41464. },
  41465. /**
  41466. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  41467. */
  41468. set: function (value) {
  41469. if (this._colorGradingWithGreenDepth === value) {
  41470. return;
  41471. }
  41472. this._colorGradingWithGreenDepth = value;
  41473. this._updateParameters();
  41474. },
  41475. enumerable: true,
  41476. configurable: true
  41477. });
  41478. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  41479. /**
  41480. * Gets wether the color grading texture contains BGR values.
  41481. */
  41482. get: function () {
  41483. return this._colorGradingBGR;
  41484. },
  41485. /**
  41486. * Sets wether the color grading texture contains BGR values.
  41487. */
  41488. set: function (value) {
  41489. if (this._colorGradingBGR === value) {
  41490. return;
  41491. }
  41492. this._colorGradingBGR = value;
  41493. this._updateParameters();
  41494. },
  41495. enumerable: true,
  41496. configurable: true
  41497. });
  41498. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  41499. /**
  41500. * Gets the Exposure used in the effect.
  41501. */
  41502. get: function () {
  41503. return this._exposure;
  41504. },
  41505. /**
  41506. * Sets the Exposure used in the effect.
  41507. */
  41508. set: function (value) {
  41509. if (this._exposure === value) {
  41510. return;
  41511. }
  41512. this._exposure = value;
  41513. this._updateParameters();
  41514. },
  41515. enumerable: true,
  41516. configurable: true
  41517. });
  41518. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  41519. /**
  41520. * Gets wether the tone mapping effect is enabled.
  41521. */
  41522. get: function () {
  41523. return this._toneMappingEnabled;
  41524. },
  41525. /**
  41526. * Sets wether the tone mapping effect is enabled.
  41527. */
  41528. set: function (value) {
  41529. if (this._toneMappingEnabled === value) {
  41530. return;
  41531. }
  41532. this._toneMappingEnabled = value;
  41533. this._updateParameters();
  41534. },
  41535. enumerable: true,
  41536. configurable: true
  41537. });
  41538. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  41539. /**
  41540. * Gets the contrast used in the effect.
  41541. */
  41542. get: function () {
  41543. return this._contrast;
  41544. },
  41545. /**
  41546. * Sets the contrast used in the effect.
  41547. */
  41548. set: function (value) {
  41549. if (this._contrast === value) {
  41550. return;
  41551. }
  41552. this._contrast = value;
  41553. this._updateParameters();
  41554. },
  41555. enumerable: true,
  41556. configurable: true
  41557. });
  41558. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41559. /**
  41560. * Gets the vignette blend mode allowing different kind of effect.
  41561. */
  41562. get: function () {
  41563. return this._vignetteBlendMode;
  41564. },
  41565. /**
  41566. * Sets the vignette blend mode allowing different kind of effect.
  41567. */
  41568. set: function (value) {
  41569. if (this._vignetteBlendMode === value) {
  41570. return;
  41571. }
  41572. this._vignetteBlendMode = value;
  41573. this._updateParameters();
  41574. },
  41575. enumerable: true,
  41576. configurable: true
  41577. });
  41578. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41579. /**
  41580. * Gets wether the vignette effect is enabled.
  41581. */
  41582. get: function () {
  41583. return this._vignetteEnabled;
  41584. },
  41585. /**
  41586. * Sets wether the vignette effect is enabled.
  41587. */
  41588. set: function (value) {
  41589. if (this._vignetteEnabled === value) {
  41590. return;
  41591. }
  41592. this._vignetteEnabled = value;
  41593. this._updateParameters();
  41594. },
  41595. enumerable: true,
  41596. configurable: true
  41597. });
  41598. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41599. /**
  41600. * Gets wether the image processing is applied through a post process or not.
  41601. */
  41602. get: function () {
  41603. return this._applyByPostProcess;
  41604. },
  41605. /**
  41606. * Sets wether the image processing is applied through a post process or not.
  41607. */
  41608. set: function (value) {
  41609. if (this._applyByPostProcess === value) {
  41610. return;
  41611. }
  41612. this._applyByPostProcess = value;
  41613. this._updateParameters();
  41614. },
  41615. enumerable: true,
  41616. configurable: true
  41617. });
  41618. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41619. /**
  41620. * Gets wether the image processing is enabled or not.
  41621. */
  41622. get: function () {
  41623. return this._isEnabled;
  41624. },
  41625. /**
  41626. * Sets wether the image processing is enabled or not.
  41627. */
  41628. set: function (value) {
  41629. if (this._isEnabled === value) {
  41630. return;
  41631. }
  41632. this._isEnabled = value;
  41633. this._updateParameters();
  41634. },
  41635. enumerable: true,
  41636. configurable: true
  41637. });
  41638. /**
  41639. * Method called each time the image processing information changes requires to recompile the effect.
  41640. */
  41641. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41642. this.onUpdateParameters.notifyObservers(this);
  41643. };
  41644. ImageProcessingConfiguration.prototype.getClassName = function () {
  41645. return "ImageProcessingConfiguration";
  41646. };
  41647. /**
  41648. * Prepare the list of uniforms associated with the Image Processing effects.
  41649. * @param uniformsList The list of uniforms used in the effect
  41650. * @param defines the list of defines currently in use
  41651. */
  41652. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41653. if (defines.EXPOSURE) {
  41654. uniforms.push("exposureLinear");
  41655. }
  41656. if (defines.CONTRAST) {
  41657. uniforms.push("contrast");
  41658. }
  41659. if (defines.COLORGRADING) {
  41660. uniforms.push("colorTransformSettings");
  41661. }
  41662. if (defines.VIGNETTE) {
  41663. uniforms.push("vInverseScreenSize");
  41664. uniforms.push("vignetteSettings1");
  41665. uniforms.push("vignetteSettings2");
  41666. }
  41667. if (defines.COLORCURVES) {
  41668. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41669. }
  41670. };
  41671. /**
  41672. * Prepare the list of samplers associated with the Image Processing effects.
  41673. * @param uniformsList The list of uniforms used in the effect
  41674. * @param defines the list of defines currently in use
  41675. */
  41676. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41677. if (defines.COLORGRADING) {
  41678. samplersList.push("txColorTransform");
  41679. }
  41680. };
  41681. /**
  41682. * Prepare the list of defines associated to the shader.
  41683. * @param defines the list of defines to complete
  41684. */
  41685. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41686. if (forPostProcess === void 0) { forPostProcess = false; }
  41687. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41688. defines.VIGNETTE = false;
  41689. defines.TONEMAPPING = false;
  41690. defines.CONTRAST = false;
  41691. defines.EXPOSURE = false;
  41692. defines.COLORCURVES = false;
  41693. defines.COLORGRADING = false;
  41694. defines.COLORGRADING3D = false;
  41695. defines.IMAGEPROCESSING = false;
  41696. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41697. return;
  41698. }
  41699. defines.VIGNETTE = this.vignetteEnabled;
  41700. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41701. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41702. defines.TONEMAPPING = this.toneMappingEnabled;
  41703. defines.CONTRAST = (this.contrast !== 1.0);
  41704. defines.EXPOSURE = (this.exposure !== 1.0);
  41705. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41706. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41707. if (defines.COLORGRADING) {
  41708. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41709. }
  41710. else {
  41711. defines.COLORGRADING3D = false;
  41712. }
  41713. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41714. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41715. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41716. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41717. };
  41718. /**
  41719. * Returns true if all the image processing information are ready.
  41720. */
  41721. ImageProcessingConfiguration.prototype.isReady = function () {
  41722. // Color Grading texure can not be none blocking.
  41723. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41724. };
  41725. /**
  41726. * Binds the image processing to the shader.
  41727. * @param effect The effect to bind to
  41728. */
  41729. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41730. if (aspectRatio === void 0) { aspectRatio = 1; }
  41731. // Color Curves
  41732. if (this._colorCurvesEnabled && this.colorCurves) {
  41733. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41734. }
  41735. // Vignette
  41736. if (this._vignetteEnabled) {
  41737. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41738. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41739. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41740. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41741. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41742. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41743. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41744. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41745. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41746. var vignettePower = -2.0 * this.vignetteWeight;
  41747. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41748. }
  41749. // Exposure
  41750. effect.setFloat("exposureLinear", this.exposure);
  41751. // Contrast
  41752. effect.setFloat("contrast", this.contrast);
  41753. // Color transform settings
  41754. if (this.colorGradingTexture) {
  41755. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41756. var textureSize = this.colorGradingTexture.getSize().height;
  41757. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41758. 0.5 / textureSize, // textureOffset
  41759. textureSize, // textureSize
  41760. this.colorGradingTexture.level // weight
  41761. );
  41762. }
  41763. };
  41764. /**
  41765. * Clones the current image processing instance.
  41766. * @return The cloned image processing
  41767. */
  41768. ImageProcessingConfiguration.prototype.clone = function () {
  41769. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41770. };
  41771. /**
  41772. * Serializes the current image processing instance to a json representation.
  41773. * @return a JSON representation
  41774. */
  41775. ImageProcessingConfiguration.prototype.serialize = function () {
  41776. return BABYLON.SerializationHelper.Serialize(this);
  41777. };
  41778. /**
  41779. * Parses the image processing from a json representation.
  41780. * @param source the JSON source to parse
  41781. * @return The parsed image processing
  41782. */
  41783. ImageProcessingConfiguration.Parse = function (source) {
  41784. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41785. };
  41786. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41787. /**
  41788. * Used to apply the vignette as a mix with the pixel color.
  41789. */
  41790. get: function () {
  41791. return this._VIGNETTEMODE_MULTIPLY;
  41792. },
  41793. enumerable: true,
  41794. configurable: true
  41795. });
  41796. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41797. /**
  41798. * Used to apply the vignette as a replacement of the pixel color.
  41799. */
  41800. get: function () {
  41801. return this._VIGNETTEMODE_OPAQUE;
  41802. },
  41803. enumerable: true,
  41804. configurable: true
  41805. });
  41806. // Static constants associated to the image processing.
  41807. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41808. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41809. __decorate([
  41810. BABYLON.serializeAsColorCurves()
  41811. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41812. __decorate([
  41813. BABYLON.serialize()
  41814. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41815. __decorate([
  41816. BABYLON.serializeAsTexture()
  41817. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41818. __decorate([
  41819. BABYLON.serialize()
  41820. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41821. __decorate([
  41822. BABYLON.serialize()
  41823. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41824. __decorate([
  41825. BABYLON.serialize()
  41826. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41827. __decorate([
  41828. BABYLON.serialize()
  41829. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41830. __decorate([
  41831. BABYLON.serialize()
  41832. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41833. __decorate([
  41834. BABYLON.serialize()
  41835. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41836. __decorate([
  41837. BABYLON.serialize()
  41838. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41839. __decorate([
  41840. BABYLON.serialize()
  41841. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41842. __decorate([
  41843. BABYLON.serialize()
  41844. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41845. __decorate([
  41846. BABYLON.serialize()
  41847. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41848. __decorate([
  41849. BABYLON.serializeAsColor4()
  41850. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41851. __decorate([
  41852. BABYLON.serialize()
  41853. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41854. __decorate([
  41855. BABYLON.serialize()
  41856. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41857. __decorate([
  41858. BABYLON.serialize()
  41859. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41860. __decorate([
  41861. BABYLON.serialize()
  41862. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41863. __decorate([
  41864. BABYLON.serialize()
  41865. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41866. return ImageProcessingConfiguration;
  41867. }());
  41868. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41869. })(BABYLON || (BABYLON = {}));
  41870. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41871. var BABYLON;
  41872. (function (BABYLON) {
  41873. /**
  41874. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41875. * It can help converting any input color in a desired output one. This can then be used to create effects
  41876. * from sepia, black and white to sixties or futuristic rendering...
  41877. *
  41878. * The only supported format is currently 3dl.
  41879. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41880. */
  41881. var ColorGradingTexture = /** @class */ (function (_super) {
  41882. __extends(ColorGradingTexture, _super);
  41883. /**
  41884. * Instantiates a ColorGradingTexture from the following parameters.
  41885. *
  41886. * @param url The location of the color gradind data (currently only supporting 3dl)
  41887. * @param scene The scene the texture will be used in
  41888. */
  41889. function ColorGradingTexture(url, scene) {
  41890. var _this = _super.call(this, scene) || this;
  41891. if (!url) {
  41892. return _this;
  41893. }
  41894. _this._engine = scene.getEngine();
  41895. _this._textureMatrix = BABYLON.Matrix.Identity();
  41896. _this.name = url;
  41897. _this.url = url;
  41898. _this.hasAlpha = false;
  41899. _this.isCube = false;
  41900. _this.is3D = _this._engine.webGLVersion > 1;
  41901. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41902. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41903. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41904. _this.anisotropicFilteringLevel = 1;
  41905. _this._texture = _this._getFromCache(url, true);
  41906. if (!_this._texture) {
  41907. if (!scene.useDelayedTextureLoading) {
  41908. _this.loadTexture();
  41909. }
  41910. else {
  41911. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41912. }
  41913. }
  41914. return _this;
  41915. }
  41916. /**
  41917. * Returns the texture matrix used in most of the material.
  41918. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41919. */
  41920. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41921. return this._textureMatrix;
  41922. };
  41923. /**
  41924. * Occurs when the file being loaded is a .3dl LUT file.
  41925. */
  41926. ColorGradingTexture.prototype.load3dlTexture = function () {
  41927. var engine = this._engine;
  41928. var texture;
  41929. if (engine.webGLVersion === 1) {
  41930. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41931. }
  41932. else {
  41933. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41934. }
  41935. this._texture = texture;
  41936. var callback = function (text) {
  41937. if (typeof text !== "string") {
  41938. return;
  41939. }
  41940. var data = null;
  41941. var tempData = null;
  41942. var line;
  41943. var lines = text.split('\n');
  41944. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41945. var maxColor = 0;
  41946. for (var i = 0; i < lines.length; i++) {
  41947. line = lines[i];
  41948. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41949. continue;
  41950. if (line.indexOf('#') === 0)
  41951. continue;
  41952. var words = line.split(" ");
  41953. if (size === 0) {
  41954. // Number of space + one
  41955. size = words.length;
  41956. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41957. tempData = new Float32Array(size * size * size * 4);
  41958. continue;
  41959. }
  41960. if (size != 0) {
  41961. var r = Math.max(parseInt(words[0]), 0);
  41962. var g = Math.max(parseInt(words[1]), 0);
  41963. var b = Math.max(parseInt(words[2]), 0);
  41964. maxColor = Math.max(r, maxColor);
  41965. maxColor = Math.max(g, maxColor);
  41966. maxColor = Math.max(b, maxColor);
  41967. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41968. if (tempData) {
  41969. tempData[pixelStorageIndex + 0] = r;
  41970. tempData[pixelStorageIndex + 1] = g;
  41971. tempData[pixelStorageIndex + 2] = b;
  41972. }
  41973. pixelIndexSlice++;
  41974. if (pixelIndexSlice % size == 0) {
  41975. pixelIndexH++;
  41976. pixelIndexSlice = 0;
  41977. if (pixelIndexH % size == 0) {
  41978. pixelIndexW++;
  41979. pixelIndexH = 0;
  41980. }
  41981. }
  41982. }
  41983. }
  41984. if (tempData && data) {
  41985. for (var i = 0; i < tempData.length; i++) {
  41986. if (i > 0 && (i + 1) % 4 === 0) {
  41987. data[i] = 255;
  41988. }
  41989. else {
  41990. var value = tempData[i];
  41991. data[i] = (value / maxColor * 255);
  41992. }
  41993. }
  41994. }
  41995. if (texture.is3D) {
  41996. texture.updateSize(size, size, size);
  41997. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41998. }
  41999. else {
  42000. texture.updateSize(size * size, size);
  42001. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  42002. }
  42003. };
  42004. var scene = this.getScene();
  42005. if (scene) {
  42006. scene._loadFile(this.url, callback);
  42007. }
  42008. else {
  42009. this._engine._loadFile(this.url, callback);
  42010. }
  42011. return this._texture;
  42012. };
  42013. /**
  42014. * Starts the loading process of the texture.
  42015. */
  42016. ColorGradingTexture.prototype.loadTexture = function () {
  42017. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  42018. this.load3dlTexture();
  42019. }
  42020. };
  42021. /**
  42022. * Clones the color gradind texture.
  42023. */
  42024. ColorGradingTexture.prototype.clone = function () {
  42025. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  42026. // Base texture
  42027. newTexture.level = this.level;
  42028. return newTexture;
  42029. };
  42030. /**
  42031. * Called during delayed load for textures.
  42032. */
  42033. ColorGradingTexture.prototype.delayLoad = function () {
  42034. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  42035. return;
  42036. }
  42037. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  42038. this._texture = this._getFromCache(this.url, true);
  42039. if (!this._texture) {
  42040. this.loadTexture();
  42041. }
  42042. };
  42043. /**
  42044. * Parses a color grading texture serialized by Babylon.
  42045. * @param parsedTexture The texture information being parsedTexture
  42046. * @param scene The scene to load the texture in
  42047. * @param rootUrl The root url of the data assets to load
  42048. * @return A color gradind texture
  42049. */
  42050. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  42051. var texture = null;
  42052. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  42053. texture = new ColorGradingTexture(parsedTexture.name, scene);
  42054. texture.name = parsedTexture.name;
  42055. texture.level = parsedTexture.level;
  42056. }
  42057. return texture;
  42058. };
  42059. /**
  42060. * Serializes the LUT texture to json format.
  42061. */
  42062. ColorGradingTexture.prototype.serialize = function () {
  42063. if (!this.name) {
  42064. return null;
  42065. }
  42066. var serializationObject = {};
  42067. serializationObject.name = this.name;
  42068. serializationObject.level = this.level;
  42069. serializationObject.customType = "BABYLON.ColorGradingTexture";
  42070. return serializationObject;
  42071. };
  42072. /**
  42073. * Empty line regex stored for GC.
  42074. */
  42075. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  42076. return ColorGradingTexture;
  42077. }(BABYLON.BaseTexture));
  42078. BABYLON.ColorGradingTexture = ColorGradingTexture;
  42079. })(BABYLON || (BABYLON = {}));
  42080. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  42081. var BABYLON;
  42082. (function (BABYLON) {
  42083. /**
  42084. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42085. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42086. * 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;
  42087. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42088. */
  42089. var ColorCurves = /** @class */ (function () {
  42090. function ColorCurves() {
  42091. this._dirty = true;
  42092. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  42093. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  42094. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  42095. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  42096. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  42097. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  42098. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  42099. this._globalHue = 30;
  42100. this._globalDensity = 0;
  42101. this._globalSaturation = 0;
  42102. this._globalExposure = 0;
  42103. this._highlightsHue = 30;
  42104. this._highlightsDensity = 0;
  42105. this._highlightsSaturation = 0;
  42106. this._highlightsExposure = 0;
  42107. this._midtonesHue = 30;
  42108. this._midtonesDensity = 0;
  42109. this._midtonesSaturation = 0;
  42110. this._midtonesExposure = 0;
  42111. this._shadowsHue = 30;
  42112. this._shadowsDensity = 0;
  42113. this._shadowsSaturation = 0;
  42114. this._shadowsExposure = 0;
  42115. }
  42116. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  42117. /**
  42118. * Gets the global Hue value.
  42119. * 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).
  42120. */
  42121. get: function () {
  42122. return this._globalHue;
  42123. },
  42124. /**
  42125. * Sets the global Hue value.
  42126. * 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).
  42127. */
  42128. set: function (value) {
  42129. this._globalHue = value;
  42130. this._dirty = true;
  42131. },
  42132. enumerable: true,
  42133. configurable: true
  42134. });
  42135. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  42136. /**
  42137. * Gets the global Density value.
  42138. * 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.
  42139. * Values less than zero provide a filter of opposite hue.
  42140. */
  42141. get: function () {
  42142. return this._globalDensity;
  42143. },
  42144. /**
  42145. * Sets the global Density value.
  42146. * 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.
  42147. * Values less than zero provide a filter of opposite hue.
  42148. */
  42149. set: function (value) {
  42150. this._globalDensity = value;
  42151. this._dirty = true;
  42152. },
  42153. enumerable: true,
  42154. configurable: true
  42155. });
  42156. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  42157. /**
  42158. * Gets the global Saturation value.
  42159. * 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.
  42160. */
  42161. get: function () {
  42162. return this._globalSaturation;
  42163. },
  42164. /**
  42165. * Sets the global Saturation value.
  42166. * 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.
  42167. */
  42168. set: function (value) {
  42169. this._globalSaturation = value;
  42170. this._dirty = true;
  42171. },
  42172. enumerable: true,
  42173. configurable: true
  42174. });
  42175. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  42176. /**
  42177. * Gets the global Exposure value.
  42178. * 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.
  42179. */
  42180. get: function () {
  42181. return this._globalExposure;
  42182. },
  42183. /**
  42184. * Sets the global Exposure value.
  42185. * 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.
  42186. */
  42187. set: function (value) {
  42188. this._globalExposure = value;
  42189. this._dirty = true;
  42190. },
  42191. enumerable: true,
  42192. configurable: true
  42193. });
  42194. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  42195. /**
  42196. * Gets the highlights Hue value.
  42197. * 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).
  42198. */
  42199. get: function () {
  42200. return this._highlightsHue;
  42201. },
  42202. /**
  42203. * Sets the highlights Hue value.
  42204. * 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).
  42205. */
  42206. set: function (value) {
  42207. this._highlightsHue = value;
  42208. this._dirty = true;
  42209. },
  42210. enumerable: true,
  42211. configurable: true
  42212. });
  42213. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  42214. /**
  42215. * Gets the highlights Density value.
  42216. * 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.
  42217. * Values less than zero provide a filter of opposite hue.
  42218. */
  42219. get: function () {
  42220. return this._highlightsDensity;
  42221. },
  42222. /**
  42223. * Sets the highlights Density value.
  42224. * 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.
  42225. * Values less than zero provide a filter of opposite hue.
  42226. */
  42227. set: function (value) {
  42228. this._highlightsDensity = value;
  42229. this._dirty = true;
  42230. },
  42231. enumerable: true,
  42232. configurable: true
  42233. });
  42234. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  42235. /**
  42236. * Gets the highlights Saturation value.
  42237. * 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.
  42238. */
  42239. get: function () {
  42240. return this._highlightsSaturation;
  42241. },
  42242. /**
  42243. * Sets the highlights Saturation value.
  42244. * 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.
  42245. */
  42246. set: function (value) {
  42247. this._highlightsSaturation = value;
  42248. this._dirty = true;
  42249. },
  42250. enumerable: true,
  42251. configurable: true
  42252. });
  42253. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  42254. /**
  42255. * Gets the highlights Exposure value.
  42256. * 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.
  42257. */
  42258. get: function () {
  42259. return this._highlightsExposure;
  42260. },
  42261. /**
  42262. * Sets the highlights Exposure value.
  42263. * 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.
  42264. */
  42265. set: function (value) {
  42266. this._highlightsExposure = value;
  42267. this._dirty = true;
  42268. },
  42269. enumerable: true,
  42270. configurable: true
  42271. });
  42272. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  42273. /**
  42274. * Gets the midtones Hue value.
  42275. * 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).
  42276. */
  42277. get: function () {
  42278. return this._midtonesHue;
  42279. },
  42280. /**
  42281. * Sets the midtones Hue value.
  42282. * 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).
  42283. */
  42284. set: function (value) {
  42285. this._midtonesHue = value;
  42286. this._dirty = true;
  42287. },
  42288. enumerable: true,
  42289. configurable: true
  42290. });
  42291. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  42292. /**
  42293. * Gets the midtones Density value.
  42294. * 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.
  42295. * Values less than zero provide a filter of opposite hue.
  42296. */
  42297. get: function () {
  42298. return this._midtonesDensity;
  42299. },
  42300. /**
  42301. * Sets the midtones Density value.
  42302. * 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.
  42303. * Values less than zero provide a filter of opposite hue.
  42304. */
  42305. set: function (value) {
  42306. this._midtonesDensity = value;
  42307. this._dirty = true;
  42308. },
  42309. enumerable: true,
  42310. configurable: true
  42311. });
  42312. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  42313. /**
  42314. * Gets the midtones Saturation value.
  42315. * 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.
  42316. */
  42317. get: function () {
  42318. return this._midtonesSaturation;
  42319. },
  42320. /**
  42321. * Sets the midtones Saturation value.
  42322. * 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.
  42323. */
  42324. set: function (value) {
  42325. this._midtonesSaturation = value;
  42326. this._dirty = true;
  42327. },
  42328. enumerable: true,
  42329. configurable: true
  42330. });
  42331. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  42332. /**
  42333. * Gets the midtones Exposure value.
  42334. * 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.
  42335. */
  42336. get: function () {
  42337. return this._midtonesExposure;
  42338. },
  42339. /**
  42340. * Sets the midtones Exposure value.
  42341. * 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.
  42342. */
  42343. set: function (value) {
  42344. this._midtonesExposure = value;
  42345. this._dirty = true;
  42346. },
  42347. enumerable: true,
  42348. configurable: true
  42349. });
  42350. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  42351. /**
  42352. * Gets the shadows Hue value.
  42353. * 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).
  42354. */
  42355. get: function () {
  42356. return this._shadowsHue;
  42357. },
  42358. /**
  42359. * Sets the shadows Hue value.
  42360. * 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).
  42361. */
  42362. set: function (value) {
  42363. this._shadowsHue = value;
  42364. this._dirty = true;
  42365. },
  42366. enumerable: true,
  42367. configurable: true
  42368. });
  42369. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  42370. /**
  42371. * Gets the shadows Density value.
  42372. * 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.
  42373. * Values less than zero provide a filter of opposite hue.
  42374. */
  42375. get: function () {
  42376. return this._shadowsDensity;
  42377. },
  42378. /**
  42379. * Sets the shadows Density value.
  42380. * 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.
  42381. * Values less than zero provide a filter of opposite hue.
  42382. */
  42383. set: function (value) {
  42384. this._shadowsDensity = value;
  42385. this._dirty = true;
  42386. },
  42387. enumerable: true,
  42388. configurable: true
  42389. });
  42390. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  42391. /**
  42392. * Gets the shadows Saturation value.
  42393. * 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.
  42394. */
  42395. get: function () {
  42396. return this._shadowsSaturation;
  42397. },
  42398. /**
  42399. * Sets the shadows Saturation value.
  42400. * 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.
  42401. */
  42402. set: function (value) {
  42403. this._shadowsSaturation = value;
  42404. this._dirty = true;
  42405. },
  42406. enumerable: true,
  42407. configurable: true
  42408. });
  42409. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  42410. /**
  42411. * Gets the shadows Exposure value.
  42412. * 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.
  42413. */
  42414. get: function () {
  42415. return this._shadowsExposure;
  42416. },
  42417. /**
  42418. * Sets the shadows Exposure value.
  42419. * 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.
  42420. */
  42421. set: function (value) {
  42422. this._shadowsExposure = value;
  42423. this._dirty = true;
  42424. },
  42425. enumerable: true,
  42426. configurable: true
  42427. });
  42428. ColorCurves.prototype.getClassName = function () {
  42429. return "ColorCurves";
  42430. };
  42431. /**
  42432. * Binds the color curves to the shader.
  42433. * @param colorCurves The color curve to bind
  42434. * @param effect The effect to bind to
  42435. */
  42436. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  42437. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  42438. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  42439. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  42440. if (colorCurves._dirty) {
  42441. colorCurves._dirty = false;
  42442. // Fill in global info.
  42443. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42444. // Compute highlights info.
  42445. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42446. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42447. // Compute midtones info.
  42448. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42449. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42450. // Compute shadows info.
  42451. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42452. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42453. // Compute deltas (neutral is midtones).
  42454. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42455. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42456. }
  42457. if (effect) {
  42458. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42459. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42460. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42461. }
  42462. };
  42463. /**
  42464. * Prepare the list of uniforms associated with the ColorCurves effects.
  42465. * @param uniformsList The list of uniforms used in the effect
  42466. */
  42467. ColorCurves.PrepareUniforms = function (uniformsList) {
  42468. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42469. };
  42470. /**
  42471. * Returns color grading data based on a hue, density, saturation and exposure value.
  42472. * @param filterHue The hue of the color filter.
  42473. * @param filterDensity The density of the color filter.
  42474. * @param saturation The saturation.
  42475. * @param exposure The exposure.
  42476. * @param result The result data container.
  42477. */
  42478. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42479. if (hue == null) {
  42480. return;
  42481. }
  42482. hue = ColorCurves.clamp(hue, 0, 360);
  42483. density = ColorCurves.clamp(density, -100, 100);
  42484. saturation = ColorCurves.clamp(saturation, -100, 100);
  42485. exposure = ColorCurves.clamp(exposure, -100, 100);
  42486. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42487. // so that the maximum filter density is only 50% control. This provides fine control
  42488. // for small values and reasonable range.
  42489. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42490. density *= 0.5;
  42491. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42492. if (density < 0) {
  42493. density *= -1;
  42494. hue = (hue + 180) % 360;
  42495. }
  42496. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42497. result.scaleToRef(2, result);
  42498. result.a = 1 + 0.01 * saturation;
  42499. };
  42500. /**
  42501. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42502. * @param value The input slider value in range [-100,100].
  42503. * @returns Adjusted value.
  42504. */
  42505. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42506. value /= 100;
  42507. var x = Math.abs(value);
  42508. x = Math.pow(x, 2);
  42509. if (value < 0) {
  42510. x *= -1;
  42511. }
  42512. x *= 100;
  42513. return x;
  42514. };
  42515. /**
  42516. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42517. * @param hue The hue (H) input.
  42518. * @param saturation The saturation (S) input.
  42519. * @param brightness The brightness (B) input.
  42520. * @result An RGBA color represented as Vector4.
  42521. */
  42522. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42523. var h = ColorCurves.clamp(hue, 0, 360);
  42524. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42525. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42526. if (s === 0) {
  42527. result.r = v;
  42528. result.g = v;
  42529. result.b = v;
  42530. }
  42531. else {
  42532. // sector 0 to 5
  42533. h /= 60;
  42534. var i = Math.floor(h);
  42535. // fractional part of h
  42536. var f = h - i;
  42537. var p = v * (1 - s);
  42538. var q = v * (1 - s * f);
  42539. var t = v * (1 - s * (1 - f));
  42540. switch (i) {
  42541. case 0:
  42542. result.r = v;
  42543. result.g = t;
  42544. result.b = p;
  42545. break;
  42546. case 1:
  42547. result.r = q;
  42548. result.g = v;
  42549. result.b = p;
  42550. break;
  42551. case 2:
  42552. result.r = p;
  42553. result.g = v;
  42554. result.b = t;
  42555. break;
  42556. case 3:
  42557. result.r = p;
  42558. result.g = q;
  42559. result.b = v;
  42560. break;
  42561. case 4:
  42562. result.r = t;
  42563. result.g = p;
  42564. result.b = v;
  42565. break;
  42566. default: // case 5:
  42567. result.r = v;
  42568. result.g = p;
  42569. result.b = q;
  42570. break;
  42571. }
  42572. }
  42573. result.a = 1;
  42574. };
  42575. /**
  42576. * Returns a value clamped between min and max
  42577. * @param value The value to clamp
  42578. * @param min The minimum of value
  42579. * @param max The maximum of value
  42580. * @returns The clamped value.
  42581. */
  42582. ColorCurves.clamp = function (value, min, max) {
  42583. return Math.min(Math.max(value, min), max);
  42584. };
  42585. /**
  42586. * Clones the current color curve instance.
  42587. * @return The cloned curves
  42588. */
  42589. ColorCurves.prototype.clone = function () {
  42590. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42591. };
  42592. /**
  42593. * Serializes the current color curve instance to a json representation.
  42594. * @return a JSON representation
  42595. */
  42596. ColorCurves.prototype.serialize = function () {
  42597. return BABYLON.SerializationHelper.Serialize(this);
  42598. };
  42599. /**
  42600. * Parses the color curve from a json representation.
  42601. * @param source the JSON source to parse
  42602. * @return The parsed curves
  42603. */
  42604. ColorCurves.Parse = function (source) {
  42605. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42606. };
  42607. __decorate([
  42608. BABYLON.serialize()
  42609. ], ColorCurves.prototype, "_globalHue", void 0);
  42610. __decorate([
  42611. BABYLON.serialize()
  42612. ], ColorCurves.prototype, "_globalDensity", void 0);
  42613. __decorate([
  42614. BABYLON.serialize()
  42615. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42616. __decorate([
  42617. BABYLON.serialize()
  42618. ], ColorCurves.prototype, "_globalExposure", void 0);
  42619. __decorate([
  42620. BABYLON.serialize()
  42621. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42622. __decorate([
  42623. BABYLON.serialize()
  42624. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42625. __decorate([
  42626. BABYLON.serialize()
  42627. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42628. __decorate([
  42629. BABYLON.serialize()
  42630. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42631. __decorate([
  42632. BABYLON.serialize()
  42633. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42634. __decorate([
  42635. BABYLON.serialize()
  42636. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42637. __decorate([
  42638. BABYLON.serialize()
  42639. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42640. __decorate([
  42641. BABYLON.serialize()
  42642. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42643. return ColorCurves;
  42644. }());
  42645. BABYLON.ColorCurves = ColorCurves;
  42646. })(BABYLON || (BABYLON = {}));
  42647. //# sourceMappingURL=babylon.colorCurves.js.map
  42648. //# sourceMappingURL=babylon.behavior.js.map
  42649. var BABYLON;
  42650. (function (BABYLON) {
  42651. /**
  42652. * "Static Class" containing the most commonly used helper while dealing with material for
  42653. * rendering purpose.
  42654. *
  42655. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42656. *
  42657. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42658. */
  42659. var MaterialHelper = /** @class */ (function () {
  42660. function MaterialHelper() {
  42661. }
  42662. /**
  42663. * Bind the current view position to an effect.
  42664. * @param effect The effect to be bound
  42665. * @param scene The scene the eyes position is used from
  42666. */
  42667. MaterialHelper.BindEyePosition = function (effect, scene) {
  42668. if (scene._forcedViewPosition) {
  42669. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42670. return;
  42671. }
  42672. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42673. };
  42674. /**
  42675. * Helps preparing the defines values about the UVs in used in the effect.
  42676. * UVs are shared as much as we can accross chanels in the shaders.
  42677. * @param texture The texture we are preparing the UVs for
  42678. * @param defines The defines to update
  42679. * @param key The chanel key "diffuse", "specular"... used in the shader
  42680. */
  42681. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42682. defines._needUVs = true;
  42683. defines[key] = true;
  42684. if (texture.getTextureMatrix().isIdentity(true)) {
  42685. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42686. if (texture.coordinatesIndex === 0) {
  42687. defines["MAINUV1"] = true;
  42688. }
  42689. else {
  42690. defines["MAINUV2"] = true;
  42691. }
  42692. }
  42693. else {
  42694. defines[key + "DIRECTUV"] = 0;
  42695. }
  42696. };
  42697. /**
  42698. * Binds a texture matrix value to its corrsponding uniform
  42699. * @param texture The texture to bind the matrix for
  42700. * @param uniformBuffer The uniform buffer receivin the data
  42701. * @param key The chanel key "diffuse", "specular"... used in the shader
  42702. */
  42703. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42704. var matrix = texture.getTextureMatrix();
  42705. if (!matrix.isIdentity(true)) {
  42706. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42707. }
  42708. };
  42709. /**
  42710. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42711. * @param mesh defines the current mesh
  42712. * @param scene defines the current scene
  42713. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42714. * @param pointsCloud defines if point cloud rendering has to be turned on
  42715. * @param fogEnabled defines if fog has to be turned on
  42716. * @param alphaTest defines if alpha testing has to be turned on
  42717. * @param defines defines the current list of defines
  42718. */
  42719. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42720. if (defines._areMiscDirty) {
  42721. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42722. defines["POINTSIZE"] = pointsCloud;
  42723. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42724. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42725. defines["ALPHATEST"] = alphaTest;
  42726. }
  42727. };
  42728. /**
  42729. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42730. * @param scene defines the current scene
  42731. * @param engine defines the current engine
  42732. * @param defines specifies the list of active defines
  42733. * @param useInstances defines if instances have to be turned on
  42734. * @param useClipPlane defines if clip plane have to be turned on
  42735. */
  42736. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42737. if (useClipPlane === void 0) { useClipPlane = null; }
  42738. var changed = false;
  42739. if (useClipPlane == null) {
  42740. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42741. }
  42742. if (defines["CLIPPLANE"] !== useClipPlane) {
  42743. defines["CLIPPLANE"] = useClipPlane;
  42744. changed = true;
  42745. }
  42746. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42747. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42748. changed = true;
  42749. }
  42750. if (defines["INSTANCES"] !== useInstances) {
  42751. defines["INSTANCES"] = useInstances;
  42752. changed = true;
  42753. }
  42754. if (changed) {
  42755. defines.markAsUnprocessed();
  42756. }
  42757. };
  42758. /**
  42759. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42760. * @param mesh The mesh containing the geometry data we will draw
  42761. * @param defines The defines to update
  42762. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42763. * @param useBones Precise whether bones should be used or not (override mesh info)
  42764. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42765. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42766. * @returns false if defines are considered not dirty and have not been checked
  42767. */
  42768. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42769. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42770. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42771. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42772. return false;
  42773. }
  42774. defines._normals = defines._needNormals;
  42775. defines._uvs = defines._needUVs;
  42776. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42777. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42778. defines["TANGENT"] = true;
  42779. }
  42780. if (defines._needUVs) {
  42781. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42782. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42783. }
  42784. else {
  42785. defines["UV1"] = false;
  42786. defines["UV2"] = false;
  42787. }
  42788. if (useVertexColor) {
  42789. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42790. defines["VERTEXCOLOR"] = hasVertexColors;
  42791. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42792. }
  42793. if (useBones) {
  42794. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42795. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42796. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42797. }
  42798. else {
  42799. defines["NUM_BONE_INFLUENCERS"] = 0;
  42800. defines["BonesPerMesh"] = 0;
  42801. }
  42802. }
  42803. if (useMorphTargets) {
  42804. var manager = mesh.morphTargetManager;
  42805. if (manager) {
  42806. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42807. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42808. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42809. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42810. }
  42811. else {
  42812. defines["MORPHTARGETS_TANGENT"] = false;
  42813. defines["MORPHTARGETS_NORMAL"] = false;
  42814. defines["MORPHTARGETS"] = false;
  42815. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42816. }
  42817. }
  42818. return true;
  42819. };
  42820. /**
  42821. * Prepares the defines related to the light information passed in parameter
  42822. * @param scene The scene we are intending to draw
  42823. * @param mesh The mesh the effect is compiling for
  42824. * @param defines The defines to update
  42825. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42826. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42827. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42828. * @returns true if normals will be required for the rest of the effect
  42829. */
  42830. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42831. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42832. if (disableLighting === void 0) { disableLighting = false; }
  42833. if (!defines._areLightsDirty) {
  42834. return defines._needNormals;
  42835. }
  42836. var lightIndex = 0;
  42837. var needNormals = false;
  42838. var needRebuild = false;
  42839. var lightmapMode = false;
  42840. var shadowEnabled = false;
  42841. var specularEnabled = false;
  42842. if (scene.lightsEnabled && !disableLighting) {
  42843. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42844. var light = _a[_i];
  42845. needNormals = true;
  42846. if (defines["LIGHT" + lightIndex] === undefined) {
  42847. needRebuild = true;
  42848. }
  42849. defines["LIGHT" + lightIndex] = true;
  42850. defines["SPOTLIGHT" + lightIndex] = false;
  42851. defines["HEMILIGHT" + lightIndex] = false;
  42852. defines["POINTLIGHT" + lightIndex] = false;
  42853. defines["DIRLIGHT" + lightIndex] = false;
  42854. var type;
  42855. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42856. type = "SPOTLIGHT" + lightIndex;
  42857. var spotLight = light;
  42858. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42859. }
  42860. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42861. type = "HEMILIGHT" + lightIndex;
  42862. }
  42863. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42864. type = "POINTLIGHT" + lightIndex;
  42865. }
  42866. else {
  42867. type = "DIRLIGHT" + lightIndex;
  42868. }
  42869. defines[type] = true;
  42870. // Specular
  42871. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42872. specularEnabled = true;
  42873. }
  42874. // Shadows
  42875. defines["SHADOW" + lightIndex] = false;
  42876. defines["SHADOWPCF" + lightIndex] = false;
  42877. defines["SHADOWPCSS" + lightIndex] = false;
  42878. defines["SHADOWPOISSON" + lightIndex] = false;
  42879. defines["SHADOWESM" + lightIndex] = false;
  42880. defines["SHADOWCUBE" + lightIndex] = false;
  42881. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42882. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42883. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42884. var shadowGenerator = light.getShadowGenerator();
  42885. if (shadowGenerator) {
  42886. shadowEnabled = true;
  42887. shadowGenerator.prepareDefines(defines, lightIndex);
  42888. }
  42889. }
  42890. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42891. lightmapMode = true;
  42892. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42893. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42894. }
  42895. else {
  42896. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42897. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42898. }
  42899. lightIndex++;
  42900. if (lightIndex === maxSimultaneousLights)
  42901. break;
  42902. }
  42903. }
  42904. defines["SPECULARTERM"] = specularEnabled;
  42905. defines["SHADOWS"] = shadowEnabled;
  42906. // Resetting all other lights if any
  42907. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42908. if (defines["LIGHT" + index] !== undefined) {
  42909. defines["LIGHT" + index] = false;
  42910. defines["HEMILIGHT" + lightIndex] = false;
  42911. defines["POINTLIGHT" + lightIndex] = false;
  42912. defines["DIRLIGHT" + lightIndex] = false;
  42913. defines["SPOTLIGHT" + lightIndex] = false;
  42914. defines["SHADOW" + lightIndex] = false;
  42915. }
  42916. }
  42917. var caps = scene.getEngine().getCaps();
  42918. if (defines["SHADOWFLOAT"] === undefined) {
  42919. needRebuild = true;
  42920. }
  42921. defines["SHADOWFLOAT"] = shadowEnabled &&
  42922. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42923. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42924. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42925. if (needRebuild) {
  42926. defines.rebuild();
  42927. }
  42928. return needNormals;
  42929. };
  42930. /**
  42931. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42932. * that won t be acctive due to defines being turned off.
  42933. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42934. * @param samplersList The samplers list
  42935. * @param defines The defines helping in the list generation
  42936. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42937. */
  42938. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42939. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42940. var uniformsList;
  42941. var uniformBuffersList = null;
  42942. if (uniformsListOrOptions.uniformsNames) {
  42943. var options = uniformsListOrOptions;
  42944. uniformsList = options.uniformsNames;
  42945. uniformBuffersList = options.uniformBuffersNames;
  42946. samplersList = options.samplers;
  42947. defines = options.defines;
  42948. maxSimultaneousLights = options.maxSimultaneousLights;
  42949. }
  42950. else {
  42951. uniformsList = uniformsListOrOptions;
  42952. if (!samplersList) {
  42953. samplersList = [];
  42954. }
  42955. }
  42956. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42957. if (!defines["LIGHT" + lightIndex]) {
  42958. break;
  42959. }
  42960. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42961. if (uniformBuffersList) {
  42962. uniformBuffersList.push("Light" + lightIndex);
  42963. }
  42964. samplersList.push("shadowSampler" + lightIndex);
  42965. samplersList.push("depthSampler" + lightIndex);
  42966. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42967. samplersList.push("projectionLightSampler" + lightIndex);
  42968. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42969. }
  42970. }
  42971. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42972. uniformsList.push("morphTargetInfluences");
  42973. }
  42974. };
  42975. /**
  42976. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42977. * @param defines The defines to update while falling back
  42978. * @param fallbacks The authorized effect fallbacks
  42979. * @param maxSimultaneousLights The maximum number of lights allowed
  42980. * @param rank the current rank of the Effect
  42981. * @returns The newly affected rank
  42982. */
  42983. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42984. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42985. if (rank === void 0) { rank = 0; }
  42986. var lightFallbackRank = 0;
  42987. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42988. if (!defines["LIGHT" + lightIndex]) {
  42989. break;
  42990. }
  42991. if (lightIndex > 0) {
  42992. lightFallbackRank = rank + lightIndex;
  42993. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42994. }
  42995. if (!defines["SHADOWS"]) {
  42996. if (defines["SHADOW" + lightIndex]) {
  42997. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42998. }
  42999. if (defines["SHADOWPCF" + lightIndex]) {
  43000. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  43001. }
  43002. if (defines["SHADOWPCSS" + lightIndex]) {
  43003. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  43004. }
  43005. if (defines["SHADOWPOISSON" + lightIndex]) {
  43006. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  43007. }
  43008. if (defines["SHADOWESM" + lightIndex]) {
  43009. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  43010. }
  43011. }
  43012. }
  43013. return lightFallbackRank++;
  43014. };
  43015. /**
  43016. * Prepares the list of attributes required for morph targets according to the effect defines.
  43017. * @param attribs The current list of supported attribs
  43018. * @param mesh The mesh to prepare the morph targets attributes for
  43019. * @param defines The current Defines of the effect
  43020. */
  43021. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  43022. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  43023. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  43024. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  43025. var manager = mesh.morphTargetManager;
  43026. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  43027. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  43028. for (var index = 0; index < influencers; index++) {
  43029. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  43030. if (normal) {
  43031. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  43032. }
  43033. if (tangent) {
  43034. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  43035. }
  43036. if (attribs.length > maxAttributesCount) {
  43037. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  43038. }
  43039. }
  43040. }
  43041. };
  43042. /**
  43043. * Prepares the list of attributes required for bones according to the effect defines.
  43044. * @param attribs The current list of supported attribs
  43045. * @param mesh The mesh to prepare the bones attributes for
  43046. * @param defines The current Defines of the effect
  43047. * @param fallbacks The current efffect fallback strategy
  43048. */
  43049. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  43050. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  43051. fallbacks.addCPUSkinningFallback(0, mesh);
  43052. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43053. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43054. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  43055. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43056. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43057. }
  43058. }
  43059. };
  43060. /**
  43061. * Prepares the list of attributes required for instances according to the effect defines.
  43062. * @param attribs The current list of supported attribs
  43063. * @param defines The current Defines of the effect
  43064. */
  43065. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  43066. if (defines["INSTANCES"]) {
  43067. attribs.push("world0");
  43068. attribs.push("world1");
  43069. attribs.push("world2");
  43070. attribs.push("world3");
  43071. }
  43072. };
  43073. /**
  43074. * Binds the light shadow information to the effect for the given mesh.
  43075. * @param light The light containing the generator
  43076. * @param scene The scene the lights belongs to
  43077. * @param mesh The mesh we are binding the information to render
  43078. * @param lightIndex The light index in the effect used to render the mesh
  43079. * @param effect The effect we are binding the data to
  43080. */
  43081. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  43082. if (light.shadowEnabled && mesh.receiveShadows) {
  43083. var shadowGenerator = light.getShadowGenerator();
  43084. if (shadowGenerator) {
  43085. shadowGenerator.bindShadowLight(lightIndex, effect);
  43086. }
  43087. }
  43088. };
  43089. /**
  43090. * Binds the light information to the effect.
  43091. * @param light The light containing the generator
  43092. * @param effect The effect we are binding the data to
  43093. * @param lightIndex The light index in the effect used to render
  43094. */
  43095. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  43096. light.transferToEffect(effect, lightIndex + "");
  43097. };
  43098. /**
  43099. * Binds the lights information from the scene to the effect for the given mesh.
  43100. * @param scene The scene the lights belongs to
  43101. * @param mesh The mesh we are binding the information to render
  43102. * @param effect The effect we are binding the data to
  43103. * @param defines The generated defines for the effect
  43104. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  43105. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  43106. */
  43107. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  43108. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  43109. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  43110. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  43111. for (var i = 0; i < len; i++) {
  43112. var light = mesh._lightSources[i];
  43113. var iAsString = i.toString();
  43114. var scaledIntensity = light.getScaledIntensity();
  43115. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  43116. MaterialHelper.BindLightProperties(light, effect, i);
  43117. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  43118. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  43119. if (defines["SPECULARTERM"]) {
  43120. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  43121. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  43122. }
  43123. // Shadows
  43124. if (scene.shadowsEnabled) {
  43125. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  43126. }
  43127. light._uniformBuffer.update();
  43128. }
  43129. };
  43130. /**
  43131. * Binds the fog information from the scene to the effect for the given mesh.
  43132. * @param scene The scene the lights belongs to
  43133. * @param mesh The mesh we are binding the information to render
  43134. * @param effect The effect we are binding the data to
  43135. */
  43136. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  43137. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  43138. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  43139. effect.setColor3("vFogColor", scene.fogColor);
  43140. }
  43141. };
  43142. /**
  43143. * Binds the bones information from the mesh to the effect.
  43144. * @param mesh The mesh we are binding the information to render
  43145. * @param effect The effect we are binding the data to
  43146. */
  43147. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  43148. if (!effect || !mesh) {
  43149. return;
  43150. }
  43151. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  43152. mesh.computeBonesUsingShaders = false;
  43153. }
  43154. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  43155. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  43156. if (matrices) {
  43157. effect.setMatrices("mBones", matrices);
  43158. }
  43159. }
  43160. };
  43161. /**
  43162. * Binds the morph targets information from the mesh to the effect.
  43163. * @param abstractMesh The mesh we are binding the information to render
  43164. * @param effect The effect we are binding the data to
  43165. */
  43166. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  43167. var manager = abstractMesh.morphTargetManager;
  43168. if (!abstractMesh || !manager) {
  43169. return;
  43170. }
  43171. effect.setFloatArray("morphTargetInfluences", manager.influences);
  43172. };
  43173. /**
  43174. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  43175. * @param defines The generated defines used in the effect
  43176. * @param effect The effect we are binding the data to
  43177. * @param scene The scene we are willing to render with logarithmic scale for
  43178. */
  43179. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  43180. if (defines["LOGARITHMICDEPTH"]) {
  43181. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  43182. }
  43183. };
  43184. /**
  43185. * Binds the clip plane information from the scene to the effect.
  43186. * @param scene The scene the clip plane information are extracted from
  43187. * @param effect The effect we are binding the data to
  43188. */
  43189. MaterialHelper.BindClipPlane = function (effect, scene) {
  43190. if (scene.clipPlane) {
  43191. var clipPlane = scene.clipPlane;
  43192. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43193. }
  43194. };
  43195. return MaterialHelper;
  43196. }());
  43197. BABYLON.MaterialHelper = MaterialHelper;
  43198. })(BABYLON || (BABYLON = {}));
  43199. //# sourceMappingURL=babylon.materialHelper.js.map
  43200. var BABYLON;
  43201. (function (BABYLON) {
  43202. var PushMaterial = /** @class */ (function (_super) {
  43203. __extends(PushMaterial, _super);
  43204. function PushMaterial(name, scene) {
  43205. var _this = _super.call(this, name, scene) || this;
  43206. _this._normalMatrix = new BABYLON.Matrix();
  43207. _this.storeEffectOnSubMeshes = true;
  43208. return _this;
  43209. }
  43210. PushMaterial.prototype.getEffect = function () {
  43211. return this._activeEffect;
  43212. };
  43213. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  43214. if (!mesh) {
  43215. return false;
  43216. }
  43217. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  43218. return true;
  43219. }
  43220. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  43221. };
  43222. /**
  43223. * Binds the given world matrix to the active effect
  43224. *
  43225. * @param world the matrix to bind
  43226. */
  43227. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43228. this._activeEffect.setMatrix("world", world);
  43229. };
  43230. /**
  43231. * Binds the given normal matrix to the active effect
  43232. *
  43233. * @param normalMatrix the matrix to bind
  43234. */
  43235. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  43236. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  43237. };
  43238. PushMaterial.prototype.bind = function (world, mesh) {
  43239. if (!mesh) {
  43240. return;
  43241. }
  43242. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  43243. };
  43244. PushMaterial.prototype._afterBind = function (mesh, effect) {
  43245. if (effect === void 0) { effect = null; }
  43246. _super.prototype._afterBind.call(this, mesh);
  43247. this.getScene()._cachedEffect = effect;
  43248. };
  43249. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  43250. if (visibility === void 0) { visibility = 1; }
  43251. return scene.isCachedMaterialInvalid(this, effect, visibility);
  43252. };
  43253. return PushMaterial;
  43254. }(BABYLON.Material));
  43255. BABYLON.PushMaterial = PushMaterial;
  43256. })(BABYLON || (BABYLON = {}));
  43257. //# sourceMappingURL=babylon.pushMaterial.js.map
  43258. var BABYLON;
  43259. (function (BABYLON) {
  43260. /** @hidden */
  43261. var StandardMaterialDefines = /** @class */ (function (_super) {
  43262. __extends(StandardMaterialDefines, _super);
  43263. function StandardMaterialDefines() {
  43264. var _this = _super.call(this) || this;
  43265. _this.MAINUV1 = false;
  43266. _this.MAINUV2 = false;
  43267. _this.DIFFUSE = false;
  43268. _this.DIFFUSEDIRECTUV = 0;
  43269. _this.AMBIENT = false;
  43270. _this.AMBIENTDIRECTUV = 0;
  43271. _this.OPACITY = false;
  43272. _this.OPACITYDIRECTUV = 0;
  43273. _this.OPACITYRGB = false;
  43274. _this.REFLECTION = false;
  43275. _this.EMISSIVE = false;
  43276. _this.EMISSIVEDIRECTUV = 0;
  43277. _this.SPECULAR = false;
  43278. _this.SPECULARDIRECTUV = 0;
  43279. _this.BUMP = false;
  43280. _this.BUMPDIRECTUV = 0;
  43281. _this.PARALLAX = false;
  43282. _this.PARALLAXOCCLUSION = false;
  43283. _this.SPECULAROVERALPHA = false;
  43284. _this.CLIPPLANE = false;
  43285. _this.ALPHATEST = false;
  43286. _this.DEPTHPREPASS = false;
  43287. _this.ALPHAFROMDIFFUSE = false;
  43288. _this.POINTSIZE = false;
  43289. _this.FOG = false;
  43290. _this.SPECULARTERM = false;
  43291. _this.DIFFUSEFRESNEL = false;
  43292. _this.OPACITYFRESNEL = false;
  43293. _this.REFLECTIONFRESNEL = false;
  43294. _this.REFRACTIONFRESNEL = false;
  43295. _this.EMISSIVEFRESNEL = false;
  43296. _this.FRESNEL = false;
  43297. _this.NORMAL = false;
  43298. _this.UV1 = false;
  43299. _this.UV2 = false;
  43300. _this.VERTEXCOLOR = false;
  43301. _this.VERTEXALPHA = false;
  43302. _this.NUM_BONE_INFLUENCERS = 0;
  43303. _this.BonesPerMesh = 0;
  43304. _this.INSTANCES = false;
  43305. _this.GLOSSINESS = false;
  43306. _this.ROUGHNESS = false;
  43307. _this.EMISSIVEASILLUMINATION = false;
  43308. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43309. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43310. _this.LIGHTMAP = false;
  43311. _this.LIGHTMAPDIRECTUV = 0;
  43312. _this.OBJECTSPACE_NORMALMAP = false;
  43313. _this.USELIGHTMAPASSHADOWMAP = false;
  43314. _this.REFLECTIONMAP_3D = false;
  43315. _this.REFLECTIONMAP_SPHERICAL = false;
  43316. _this.REFLECTIONMAP_PLANAR = false;
  43317. _this.REFLECTIONMAP_CUBIC = false;
  43318. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43319. _this.REFLECTIONMAP_PROJECTION = false;
  43320. _this.REFLECTIONMAP_SKYBOX = false;
  43321. _this.REFLECTIONMAP_EXPLICIT = false;
  43322. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43323. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43324. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43325. _this.INVERTCUBICMAP = false;
  43326. _this.LOGARITHMICDEPTH = false;
  43327. _this.REFRACTION = false;
  43328. _this.REFRACTIONMAP_3D = false;
  43329. _this.REFLECTIONOVERALPHA = false;
  43330. _this.TWOSIDEDLIGHTING = false;
  43331. _this.SHADOWFLOAT = false;
  43332. _this.MORPHTARGETS = false;
  43333. _this.MORPHTARGETS_NORMAL = false;
  43334. _this.MORPHTARGETS_TANGENT = false;
  43335. _this.NUM_MORPH_INFLUENCERS = 0;
  43336. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  43337. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  43338. _this.IMAGEPROCESSING = false;
  43339. _this.VIGNETTE = false;
  43340. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43341. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43342. _this.TONEMAPPING = false;
  43343. _this.CONTRAST = false;
  43344. _this.COLORCURVES = false;
  43345. _this.COLORGRADING = false;
  43346. _this.COLORGRADING3D = false;
  43347. _this.SAMPLER3DGREENDEPTH = false;
  43348. _this.SAMPLER3DBGRMAP = false;
  43349. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43350. /**
  43351. * If the reflection texture on this material is in linear color space
  43352. * @hidden
  43353. */
  43354. _this.IS_REFLECTION_LINEAR = false;
  43355. /**
  43356. * If the refraction texture on this material is in linear color space
  43357. * @hidden
  43358. */
  43359. _this.IS_REFRACTION_LINEAR = false;
  43360. _this.EXPOSURE = false;
  43361. _this.rebuild();
  43362. return _this;
  43363. }
  43364. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43365. var modes = [
  43366. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43367. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43368. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43369. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43370. ];
  43371. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43372. var mode = modes_1[_i];
  43373. this[mode] = (mode === modeToEnable);
  43374. }
  43375. };
  43376. return StandardMaterialDefines;
  43377. }(BABYLON.MaterialDefines));
  43378. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43379. var StandardMaterial = /** @class */ (function (_super) {
  43380. __extends(StandardMaterial, _super);
  43381. function StandardMaterial(name, scene) {
  43382. var _this = _super.call(this, name, scene) || this;
  43383. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43384. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43385. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43386. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43387. _this.specularPower = 64;
  43388. _this._useAlphaFromDiffuseTexture = false;
  43389. _this._useEmissiveAsIllumination = false;
  43390. _this._linkEmissiveWithDiffuse = false;
  43391. _this._useSpecularOverAlpha = false;
  43392. _this._useReflectionOverAlpha = false;
  43393. _this._disableLighting = false;
  43394. _this._useObjectSpaceNormalMap = false;
  43395. _this._useParallax = false;
  43396. _this._useParallaxOcclusion = false;
  43397. _this.parallaxScaleBias = 0.05;
  43398. _this._roughness = 0;
  43399. _this.indexOfRefraction = 0.98;
  43400. _this.invertRefractionY = true;
  43401. /**
  43402. * Defines the alpha limits in alpha test mode
  43403. */
  43404. _this.alphaCutOff = 0.4;
  43405. _this._useLightmapAsShadowmap = false;
  43406. _this._useReflectionFresnelFromSpecular = false;
  43407. _this._useGlossinessFromSpecularMapAlpha = false;
  43408. _this._maxSimultaneousLights = 4;
  43409. /**
  43410. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  43411. */
  43412. _this._invertNormalMapX = false;
  43413. /**
  43414. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  43415. */
  43416. _this._invertNormalMapY = false;
  43417. /**
  43418. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43419. */
  43420. _this._twoSidedLighting = false;
  43421. _this._renderTargets = new BABYLON.SmartArray(16);
  43422. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43423. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43424. // Setup the default processing configuration to the scene.
  43425. _this._attachImageProcessingConfiguration(null);
  43426. _this.getRenderTargetTextures = function () {
  43427. _this._renderTargets.reset();
  43428. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43429. _this._renderTargets.push(_this._reflectionTexture);
  43430. }
  43431. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43432. _this._renderTargets.push(_this._refractionTexture);
  43433. }
  43434. return _this._renderTargets;
  43435. };
  43436. return _this;
  43437. }
  43438. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43439. /**
  43440. * Gets the image processing configuration used either in this material.
  43441. */
  43442. get: function () {
  43443. return this._imageProcessingConfiguration;
  43444. },
  43445. /**
  43446. * Sets the Default image processing configuration used either in the this material.
  43447. *
  43448. * If sets to null, the scene one is in use.
  43449. */
  43450. set: function (value) {
  43451. this._attachImageProcessingConfiguration(value);
  43452. // Ensure the effect will be rebuilt.
  43453. this._markAllSubMeshesAsTexturesDirty();
  43454. },
  43455. enumerable: true,
  43456. configurable: true
  43457. });
  43458. /**
  43459. * Attaches a new image processing configuration to the Standard Material.
  43460. * @param configuration
  43461. */
  43462. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43463. var _this = this;
  43464. if (configuration === this._imageProcessingConfiguration) {
  43465. return;
  43466. }
  43467. // Detaches observer.
  43468. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43469. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43470. }
  43471. // Pick the scene configuration if needed.
  43472. if (!configuration) {
  43473. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43474. }
  43475. else {
  43476. this._imageProcessingConfiguration = configuration;
  43477. }
  43478. // Attaches observer.
  43479. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43480. _this._markAllSubMeshesAsImageProcessingDirty();
  43481. });
  43482. };
  43483. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43484. /**
  43485. * Gets wether the color curves effect is enabled.
  43486. */
  43487. get: function () {
  43488. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43489. },
  43490. /**
  43491. * Sets wether the color curves effect is enabled.
  43492. */
  43493. set: function (value) {
  43494. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43495. },
  43496. enumerable: true,
  43497. configurable: true
  43498. });
  43499. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43500. /**
  43501. * Gets wether the color grading effect is enabled.
  43502. */
  43503. get: function () {
  43504. return this.imageProcessingConfiguration.colorGradingEnabled;
  43505. },
  43506. /**
  43507. * Gets wether the color grading effect is enabled.
  43508. */
  43509. set: function (value) {
  43510. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43511. },
  43512. enumerable: true,
  43513. configurable: true
  43514. });
  43515. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43516. /**
  43517. * Gets wether tonemapping is enabled or not.
  43518. */
  43519. get: function () {
  43520. return this._imageProcessingConfiguration.toneMappingEnabled;
  43521. },
  43522. /**
  43523. * Sets wether tonemapping is enabled or not
  43524. */
  43525. set: function (value) {
  43526. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43527. },
  43528. enumerable: true,
  43529. configurable: true
  43530. });
  43531. ;
  43532. ;
  43533. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43534. /**
  43535. * The camera exposure used on this material.
  43536. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43537. * This corresponds to a photographic exposure.
  43538. */
  43539. get: function () {
  43540. return this._imageProcessingConfiguration.exposure;
  43541. },
  43542. /**
  43543. * The camera exposure used on this material.
  43544. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43545. * This corresponds to a photographic exposure.
  43546. */
  43547. set: function (value) {
  43548. this._imageProcessingConfiguration.exposure = value;
  43549. },
  43550. enumerable: true,
  43551. configurable: true
  43552. });
  43553. ;
  43554. ;
  43555. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43556. /**
  43557. * Gets The camera contrast used on this material.
  43558. */
  43559. get: function () {
  43560. return this._imageProcessingConfiguration.contrast;
  43561. },
  43562. /**
  43563. * Sets The camera contrast used on this material.
  43564. */
  43565. set: function (value) {
  43566. this._imageProcessingConfiguration.contrast = value;
  43567. },
  43568. enumerable: true,
  43569. configurable: true
  43570. });
  43571. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43572. /**
  43573. * Gets the Color Grading 2D Lookup Texture.
  43574. */
  43575. get: function () {
  43576. return this._imageProcessingConfiguration.colorGradingTexture;
  43577. },
  43578. /**
  43579. * Sets the Color Grading 2D Lookup Texture.
  43580. */
  43581. set: function (value) {
  43582. this._imageProcessingConfiguration.colorGradingTexture = value;
  43583. },
  43584. enumerable: true,
  43585. configurable: true
  43586. });
  43587. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43588. /**
  43589. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43590. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43591. * 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;
  43592. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43593. */
  43594. get: function () {
  43595. return this._imageProcessingConfiguration.colorCurves;
  43596. },
  43597. /**
  43598. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43599. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43600. * 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;
  43601. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43602. */
  43603. set: function (value) {
  43604. this._imageProcessingConfiguration.colorCurves = value;
  43605. },
  43606. enumerable: true,
  43607. configurable: true
  43608. });
  43609. StandardMaterial.prototype.getClassName = function () {
  43610. return "StandardMaterial";
  43611. };
  43612. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43613. get: function () {
  43614. return this._useLogarithmicDepth;
  43615. },
  43616. set: function (value) {
  43617. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43618. this._markAllSubMeshesAsMiscDirty();
  43619. },
  43620. enumerable: true,
  43621. configurable: true
  43622. });
  43623. StandardMaterial.prototype.needAlphaBlending = function () {
  43624. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43625. };
  43626. StandardMaterial.prototype.needAlphaTesting = function () {
  43627. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43628. };
  43629. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43630. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43631. };
  43632. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43633. return this._diffuseTexture;
  43634. };
  43635. /**
  43636. * Child classes can use it to update shaders
  43637. */
  43638. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43639. if (useInstances === void 0) { useInstances = false; }
  43640. if (subMesh.effect && this.isFrozen) {
  43641. if (this._wasPreviouslyReady && subMesh.effect) {
  43642. return true;
  43643. }
  43644. }
  43645. if (!subMesh._materialDefines) {
  43646. subMesh._materialDefines = new StandardMaterialDefines();
  43647. }
  43648. var scene = this.getScene();
  43649. var defines = subMesh._materialDefines;
  43650. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43651. if (defines._renderId === scene.getRenderId()) {
  43652. return true;
  43653. }
  43654. }
  43655. var engine = scene.getEngine();
  43656. // Lights
  43657. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43658. // Textures
  43659. if (defines._areTexturesDirty) {
  43660. defines._needUVs = false;
  43661. defines.MAINUV1 = false;
  43662. defines.MAINUV2 = false;
  43663. if (scene.texturesEnabled) {
  43664. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43665. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43666. return false;
  43667. }
  43668. else {
  43669. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43670. }
  43671. }
  43672. else {
  43673. defines.DIFFUSE = false;
  43674. }
  43675. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43676. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43677. return false;
  43678. }
  43679. else {
  43680. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43681. }
  43682. }
  43683. else {
  43684. defines.AMBIENT = false;
  43685. }
  43686. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43687. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43688. return false;
  43689. }
  43690. else {
  43691. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43692. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43693. }
  43694. }
  43695. else {
  43696. defines.OPACITY = false;
  43697. }
  43698. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43699. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43700. return false;
  43701. }
  43702. else {
  43703. defines._needNormals = true;
  43704. defines.REFLECTION = true;
  43705. defines.ROUGHNESS = (this._roughness > 0);
  43706. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43707. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43708. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43709. switch (this._reflectionTexture.coordinatesMode) {
  43710. case BABYLON.Texture.EXPLICIT_MODE:
  43711. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43712. break;
  43713. case BABYLON.Texture.PLANAR_MODE:
  43714. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43715. break;
  43716. case BABYLON.Texture.PROJECTION_MODE:
  43717. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43718. break;
  43719. case BABYLON.Texture.SKYBOX_MODE:
  43720. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43721. break;
  43722. case BABYLON.Texture.SPHERICAL_MODE:
  43723. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43724. break;
  43725. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43726. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43727. break;
  43728. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43729. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43730. break;
  43731. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43732. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43733. break;
  43734. case BABYLON.Texture.CUBIC_MODE:
  43735. case BABYLON.Texture.INVCUBIC_MODE:
  43736. default:
  43737. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43738. break;
  43739. }
  43740. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43741. }
  43742. }
  43743. else {
  43744. defines.REFLECTION = false;
  43745. }
  43746. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43747. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43748. return false;
  43749. }
  43750. else {
  43751. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43752. }
  43753. }
  43754. else {
  43755. defines.EMISSIVE = false;
  43756. }
  43757. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43758. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43759. return false;
  43760. }
  43761. else {
  43762. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43763. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43764. }
  43765. }
  43766. else {
  43767. defines.LIGHTMAP = false;
  43768. }
  43769. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43770. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43771. return false;
  43772. }
  43773. else {
  43774. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43775. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43776. }
  43777. }
  43778. else {
  43779. defines.SPECULAR = false;
  43780. }
  43781. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43782. // Bump texure can not be not blocking.
  43783. if (!this._bumpTexture.isReady()) {
  43784. return false;
  43785. }
  43786. else {
  43787. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43788. defines.PARALLAX = this._useParallax;
  43789. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43790. }
  43791. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43792. }
  43793. else {
  43794. defines.BUMP = false;
  43795. }
  43796. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43797. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43798. return false;
  43799. }
  43800. else {
  43801. defines._needUVs = true;
  43802. defines.REFRACTION = true;
  43803. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43804. }
  43805. }
  43806. else {
  43807. defines.REFRACTION = false;
  43808. }
  43809. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43810. }
  43811. else {
  43812. defines.DIFFUSE = false;
  43813. defines.AMBIENT = false;
  43814. defines.OPACITY = false;
  43815. defines.REFLECTION = false;
  43816. defines.EMISSIVE = false;
  43817. defines.LIGHTMAP = false;
  43818. defines.BUMP = false;
  43819. defines.REFRACTION = false;
  43820. }
  43821. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43822. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43823. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43824. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43825. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43826. }
  43827. if (defines._areImageProcessingDirty) {
  43828. if (!this._imageProcessingConfiguration.isReady()) {
  43829. return false;
  43830. }
  43831. this._imageProcessingConfiguration.prepareDefines(defines);
  43832. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43833. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43834. }
  43835. if (defines._areFresnelDirty) {
  43836. if (StandardMaterial.FresnelEnabled) {
  43837. // Fresnel
  43838. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43839. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43840. this._reflectionFresnelParameters) {
  43841. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43842. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43843. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43844. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43845. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43846. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43847. defines._needNormals = true;
  43848. defines.FRESNEL = true;
  43849. }
  43850. }
  43851. else {
  43852. defines.FRESNEL = false;
  43853. }
  43854. }
  43855. // Misc.
  43856. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43857. // Attribs
  43858. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43859. // Values that need to be evaluated on every frame
  43860. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43861. // Get correct effect
  43862. if (defines.isDirty) {
  43863. defines.markAsProcessed();
  43864. scene.resetCachedMaterial();
  43865. // Fallbacks
  43866. var fallbacks = new BABYLON.EffectFallbacks();
  43867. if (defines.REFLECTION) {
  43868. fallbacks.addFallback(0, "REFLECTION");
  43869. }
  43870. if (defines.SPECULAR) {
  43871. fallbacks.addFallback(0, "SPECULAR");
  43872. }
  43873. if (defines.BUMP) {
  43874. fallbacks.addFallback(0, "BUMP");
  43875. }
  43876. if (defines.PARALLAX) {
  43877. fallbacks.addFallback(1, "PARALLAX");
  43878. }
  43879. if (defines.PARALLAXOCCLUSION) {
  43880. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43881. }
  43882. if (defines.SPECULAROVERALPHA) {
  43883. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43884. }
  43885. if (defines.FOG) {
  43886. fallbacks.addFallback(1, "FOG");
  43887. }
  43888. if (defines.POINTSIZE) {
  43889. fallbacks.addFallback(0, "POINTSIZE");
  43890. }
  43891. if (defines.LOGARITHMICDEPTH) {
  43892. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43893. }
  43894. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43895. if (defines.SPECULARTERM) {
  43896. fallbacks.addFallback(0, "SPECULARTERM");
  43897. }
  43898. if (defines.DIFFUSEFRESNEL) {
  43899. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43900. }
  43901. if (defines.OPACITYFRESNEL) {
  43902. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43903. }
  43904. if (defines.REFLECTIONFRESNEL) {
  43905. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43906. }
  43907. if (defines.EMISSIVEFRESNEL) {
  43908. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43909. }
  43910. if (defines.FRESNEL) {
  43911. fallbacks.addFallback(4, "FRESNEL");
  43912. }
  43913. //Attributes
  43914. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43915. if (defines.NORMAL) {
  43916. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43917. }
  43918. if (defines.UV1) {
  43919. attribs.push(BABYLON.VertexBuffer.UVKind);
  43920. }
  43921. if (defines.UV2) {
  43922. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43923. }
  43924. if (defines.VERTEXCOLOR) {
  43925. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43926. }
  43927. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43928. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43929. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43930. var shaderName = "default";
  43931. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43932. "vFogInfos", "vFogColor", "pointSize",
  43933. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43934. "mBones",
  43935. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43936. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43937. "vReflectionPosition", "vReflectionSize",
  43938. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43939. ];
  43940. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43941. var uniformBuffers = ["Material", "Scene"];
  43942. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43943. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43944. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43945. uniformsNames: uniforms,
  43946. uniformBuffersNames: uniformBuffers,
  43947. samplers: samplers,
  43948. defines: defines,
  43949. maxSimultaneousLights: this._maxSimultaneousLights
  43950. });
  43951. if (this.customShaderNameResolve) {
  43952. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43953. }
  43954. var join = defines.toString();
  43955. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43956. attributes: attribs,
  43957. uniformsNames: uniforms,
  43958. uniformBuffersNames: uniformBuffers,
  43959. samplers: samplers,
  43960. defines: join,
  43961. fallbacks: fallbacks,
  43962. onCompiled: this.onCompiled,
  43963. onError: this.onError,
  43964. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43965. }, engine), defines);
  43966. this.buildUniformLayout();
  43967. }
  43968. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43969. return false;
  43970. }
  43971. defines._renderId = scene.getRenderId();
  43972. this._wasPreviouslyReady = true;
  43973. return true;
  43974. };
  43975. StandardMaterial.prototype.buildUniformLayout = function () {
  43976. // Order is important !
  43977. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43978. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43979. this._uniformBuffer.addUniform("opacityParts", 4);
  43980. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43981. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43982. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43983. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43984. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43985. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43986. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43987. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43988. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43989. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43990. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43991. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43992. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43993. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43994. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43995. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43996. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43997. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43998. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43999. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44000. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44001. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44002. this._uniformBuffer.addUniform("specularMatrix", 16);
  44003. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44004. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44005. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44006. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44007. this._uniformBuffer.addUniform("vSpecularColor", 4);
  44008. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44009. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  44010. this._uniformBuffer.addUniform("pointSize", 1);
  44011. this._uniformBuffer.create();
  44012. };
  44013. StandardMaterial.prototype.unbind = function () {
  44014. if (this._activeEffect) {
  44015. var needFlag = false;
  44016. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44017. this._activeEffect.setTexture("reflection2DSampler", null);
  44018. needFlag = true;
  44019. }
  44020. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44021. this._activeEffect.setTexture("refraction2DSampler", null);
  44022. needFlag = true;
  44023. }
  44024. if (needFlag) {
  44025. this._markAllSubMeshesAsTexturesDirty();
  44026. }
  44027. }
  44028. _super.prototype.unbind.call(this);
  44029. };
  44030. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44031. var scene = this.getScene();
  44032. var defines = subMesh._materialDefines;
  44033. if (!defines) {
  44034. return;
  44035. }
  44036. var effect = subMesh.effect;
  44037. if (!effect) {
  44038. return;
  44039. }
  44040. this._activeEffect = effect;
  44041. // Matrices
  44042. this.bindOnlyWorldMatrix(world);
  44043. // Normal Matrix
  44044. if (defines.OBJECTSPACE_NORMALMAP) {
  44045. world.toNormalMatrix(this._normalMatrix);
  44046. this.bindOnlyNormalMatrix(this._normalMatrix);
  44047. }
  44048. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44049. // Bones
  44050. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  44051. if (mustRebind) {
  44052. this._uniformBuffer.bindToEffect(effect, "Material");
  44053. this.bindViewProjection(effect);
  44054. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44055. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  44056. // Fresnel
  44057. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  44058. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  44059. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  44060. }
  44061. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44062. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  44063. }
  44064. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  44065. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  44066. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  44067. }
  44068. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  44069. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  44070. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  44071. }
  44072. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44073. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  44074. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  44075. }
  44076. }
  44077. // Textures
  44078. if (scene.texturesEnabled) {
  44079. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44080. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  44081. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  44082. if (this._diffuseTexture.hasAlpha) {
  44083. effect.setFloat("alphaCutOff", this.alphaCutOff);
  44084. }
  44085. }
  44086. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44087. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  44088. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44089. }
  44090. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44091. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44092. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44093. }
  44094. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44095. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  44096. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  44097. if (this._reflectionTexture.boundingBoxSize) {
  44098. var cubeTexture = this._reflectionTexture;
  44099. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44100. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44101. }
  44102. }
  44103. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44104. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44105. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44106. }
  44107. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44108. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44109. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44110. }
  44111. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44112. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  44113. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  44114. }
  44115. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44116. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  44117. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44118. if (scene._mirroredCameraPosition) {
  44119. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44120. }
  44121. else {
  44122. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44123. }
  44124. }
  44125. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44126. var depth = 1.0;
  44127. if (!this._refractionTexture.isCube) {
  44128. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  44129. if (this._refractionTexture.depth) {
  44130. depth = this._refractionTexture.depth;
  44131. }
  44132. }
  44133. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44134. }
  44135. }
  44136. // Point size
  44137. if (this.pointsCloud) {
  44138. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44139. }
  44140. if (defines.SPECULARTERM) {
  44141. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  44142. }
  44143. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  44144. // Diffuse
  44145. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  44146. }
  44147. // Textures
  44148. if (scene.texturesEnabled) {
  44149. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44150. effect.setTexture("diffuseSampler", this._diffuseTexture);
  44151. }
  44152. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44153. effect.setTexture("ambientSampler", this._ambientTexture);
  44154. }
  44155. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44156. effect.setTexture("opacitySampler", this._opacityTexture);
  44157. }
  44158. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44159. if (this._reflectionTexture.isCube) {
  44160. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  44161. }
  44162. else {
  44163. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  44164. }
  44165. }
  44166. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44167. effect.setTexture("emissiveSampler", this._emissiveTexture);
  44168. }
  44169. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44170. effect.setTexture("lightmapSampler", this._lightmapTexture);
  44171. }
  44172. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44173. effect.setTexture("specularSampler", this._specularTexture);
  44174. }
  44175. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44176. effect.setTexture("bumpSampler", this._bumpTexture);
  44177. }
  44178. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44179. var depth = 1.0;
  44180. if (this._refractionTexture.isCube) {
  44181. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  44182. }
  44183. else {
  44184. effect.setTexture("refraction2DSampler", this._refractionTexture);
  44185. }
  44186. }
  44187. }
  44188. // Clip plane
  44189. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  44190. // Colors
  44191. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44192. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  44193. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44194. }
  44195. if (mustRebind || !this.isFrozen) {
  44196. // Lights
  44197. if (scene.lightsEnabled && !this._disableLighting) {
  44198. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  44199. }
  44200. // View
  44201. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  44202. this.bindView(effect);
  44203. }
  44204. // Fog
  44205. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  44206. // Morph targets
  44207. if (defines.NUM_MORPH_INFLUENCERS) {
  44208. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  44209. }
  44210. // Log. depth
  44211. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  44212. // image processing
  44213. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  44214. this._imageProcessingConfiguration.bind(this._activeEffect);
  44215. }
  44216. }
  44217. this._uniformBuffer.update();
  44218. this._afterBind(mesh, this._activeEffect);
  44219. };
  44220. StandardMaterial.prototype.getAnimatables = function () {
  44221. var results = [];
  44222. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  44223. results.push(this._diffuseTexture);
  44224. }
  44225. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44226. results.push(this._ambientTexture);
  44227. }
  44228. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44229. results.push(this._opacityTexture);
  44230. }
  44231. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44232. results.push(this._reflectionTexture);
  44233. }
  44234. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44235. results.push(this._emissiveTexture);
  44236. }
  44237. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  44238. results.push(this._specularTexture);
  44239. }
  44240. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44241. results.push(this._bumpTexture);
  44242. }
  44243. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44244. results.push(this._lightmapTexture);
  44245. }
  44246. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44247. results.push(this._refractionTexture);
  44248. }
  44249. return results;
  44250. };
  44251. StandardMaterial.prototype.getActiveTextures = function () {
  44252. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44253. if (this._diffuseTexture) {
  44254. activeTextures.push(this._diffuseTexture);
  44255. }
  44256. if (this._ambientTexture) {
  44257. activeTextures.push(this._ambientTexture);
  44258. }
  44259. if (this._opacityTexture) {
  44260. activeTextures.push(this._opacityTexture);
  44261. }
  44262. if (this._reflectionTexture) {
  44263. activeTextures.push(this._reflectionTexture);
  44264. }
  44265. if (this._emissiveTexture) {
  44266. activeTextures.push(this._emissiveTexture);
  44267. }
  44268. if (this._specularTexture) {
  44269. activeTextures.push(this._specularTexture);
  44270. }
  44271. if (this._bumpTexture) {
  44272. activeTextures.push(this._bumpTexture);
  44273. }
  44274. if (this._lightmapTexture) {
  44275. activeTextures.push(this._lightmapTexture);
  44276. }
  44277. if (this._refractionTexture) {
  44278. activeTextures.push(this._refractionTexture);
  44279. }
  44280. return activeTextures;
  44281. };
  44282. StandardMaterial.prototype.hasTexture = function (texture) {
  44283. if (_super.prototype.hasTexture.call(this, texture)) {
  44284. return true;
  44285. }
  44286. if (this._diffuseTexture === texture) {
  44287. return true;
  44288. }
  44289. if (this._ambientTexture === texture) {
  44290. return true;
  44291. }
  44292. if (this._opacityTexture === texture) {
  44293. return true;
  44294. }
  44295. if (this._reflectionTexture === texture) {
  44296. return true;
  44297. }
  44298. if (this._emissiveTexture === texture) {
  44299. return true;
  44300. }
  44301. if (this._specularTexture === texture) {
  44302. return true;
  44303. }
  44304. if (this._bumpTexture === texture) {
  44305. return true;
  44306. }
  44307. if (this._lightmapTexture === texture) {
  44308. return true;
  44309. }
  44310. if (this._refractionTexture === texture) {
  44311. return true;
  44312. }
  44313. return false;
  44314. };
  44315. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44316. if (forceDisposeTextures) {
  44317. if (this._diffuseTexture) {
  44318. this._diffuseTexture.dispose();
  44319. }
  44320. if (this._ambientTexture) {
  44321. this._ambientTexture.dispose();
  44322. }
  44323. if (this._opacityTexture) {
  44324. this._opacityTexture.dispose();
  44325. }
  44326. if (this._reflectionTexture) {
  44327. this._reflectionTexture.dispose();
  44328. }
  44329. if (this._emissiveTexture) {
  44330. this._emissiveTexture.dispose();
  44331. }
  44332. if (this._specularTexture) {
  44333. this._specularTexture.dispose();
  44334. }
  44335. if (this._bumpTexture) {
  44336. this._bumpTexture.dispose();
  44337. }
  44338. if (this._lightmapTexture) {
  44339. this._lightmapTexture.dispose();
  44340. }
  44341. if (this._refractionTexture) {
  44342. this._refractionTexture.dispose();
  44343. }
  44344. }
  44345. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44346. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44347. }
  44348. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44349. };
  44350. StandardMaterial.prototype.clone = function (name) {
  44351. var _this = this;
  44352. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44353. result.name = name;
  44354. result.id = name;
  44355. return result;
  44356. };
  44357. StandardMaterial.prototype.serialize = function () {
  44358. return BABYLON.SerializationHelper.Serialize(this);
  44359. };
  44360. // Statics
  44361. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44362. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44363. };
  44364. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44365. get: function () {
  44366. return StandardMaterial._DiffuseTextureEnabled;
  44367. },
  44368. set: function (value) {
  44369. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44370. return;
  44371. }
  44372. StandardMaterial._DiffuseTextureEnabled = value;
  44373. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44374. },
  44375. enumerable: true,
  44376. configurable: true
  44377. });
  44378. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44379. get: function () {
  44380. return StandardMaterial._AmbientTextureEnabled;
  44381. },
  44382. set: function (value) {
  44383. if (StandardMaterial._AmbientTextureEnabled === value) {
  44384. return;
  44385. }
  44386. StandardMaterial._AmbientTextureEnabled = value;
  44387. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44388. },
  44389. enumerable: true,
  44390. configurable: true
  44391. });
  44392. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44393. get: function () {
  44394. return StandardMaterial._OpacityTextureEnabled;
  44395. },
  44396. set: function (value) {
  44397. if (StandardMaterial._OpacityTextureEnabled === value) {
  44398. return;
  44399. }
  44400. StandardMaterial._OpacityTextureEnabled = value;
  44401. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44402. },
  44403. enumerable: true,
  44404. configurable: true
  44405. });
  44406. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44407. get: function () {
  44408. return StandardMaterial._ReflectionTextureEnabled;
  44409. },
  44410. set: function (value) {
  44411. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44412. return;
  44413. }
  44414. StandardMaterial._ReflectionTextureEnabled = value;
  44415. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44416. },
  44417. enumerable: true,
  44418. configurable: true
  44419. });
  44420. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44421. get: function () {
  44422. return StandardMaterial._EmissiveTextureEnabled;
  44423. },
  44424. set: function (value) {
  44425. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44426. return;
  44427. }
  44428. StandardMaterial._EmissiveTextureEnabled = value;
  44429. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44430. },
  44431. enumerable: true,
  44432. configurable: true
  44433. });
  44434. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44435. get: function () {
  44436. return StandardMaterial._SpecularTextureEnabled;
  44437. },
  44438. set: function (value) {
  44439. if (StandardMaterial._SpecularTextureEnabled === value) {
  44440. return;
  44441. }
  44442. StandardMaterial._SpecularTextureEnabled = value;
  44443. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44444. },
  44445. enumerable: true,
  44446. configurable: true
  44447. });
  44448. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44449. get: function () {
  44450. return StandardMaterial._BumpTextureEnabled;
  44451. },
  44452. set: function (value) {
  44453. if (StandardMaterial._BumpTextureEnabled === value) {
  44454. return;
  44455. }
  44456. StandardMaterial._BumpTextureEnabled = value;
  44457. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44458. },
  44459. enumerable: true,
  44460. configurable: true
  44461. });
  44462. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44463. get: function () {
  44464. return StandardMaterial._LightmapTextureEnabled;
  44465. },
  44466. set: function (value) {
  44467. if (StandardMaterial._LightmapTextureEnabled === value) {
  44468. return;
  44469. }
  44470. StandardMaterial._LightmapTextureEnabled = value;
  44471. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44472. },
  44473. enumerable: true,
  44474. configurable: true
  44475. });
  44476. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44477. get: function () {
  44478. return StandardMaterial._RefractionTextureEnabled;
  44479. },
  44480. set: function (value) {
  44481. if (StandardMaterial._RefractionTextureEnabled === value) {
  44482. return;
  44483. }
  44484. StandardMaterial._RefractionTextureEnabled = value;
  44485. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44486. },
  44487. enumerable: true,
  44488. configurable: true
  44489. });
  44490. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44491. get: function () {
  44492. return StandardMaterial._ColorGradingTextureEnabled;
  44493. },
  44494. set: function (value) {
  44495. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44496. return;
  44497. }
  44498. StandardMaterial._ColorGradingTextureEnabled = value;
  44499. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44500. },
  44501. enumerable: true,
  44502. configurable: true
  44503. });
  44504. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44505. get: function () {
  44506. return StandardMaterial._FresnelEnabled;
  44507. },
  44508. set: function (value) {
  44509. if (StandardMaterial._FresnelEnabled === value) {
  44510. return;
  44511. }
  44512. StandardMaterial._FresnelEnabled = value;
  44513. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44514. },
  44515. enumerable: true,
  44516. configurable: true
  44517. });
  44518. // Flags used to enable or disable a type of texture for all Standard Materials
  44519. StandardMaterial._DiffuseTextureEnabled = true;
  44520. StandardMaterial._AmbientTextureEnabled = true;
  44521. StandardMaterial._OpacityTextureEnabled = true;
  44522. StandardMaterial._ReflectionTextureEnabled = true;
  44523. StandardMaterial._EmissiveTextureEnabled = true;
  44524. StandardMaterial._SpecularTextureEnabled = true;
  44525. StandardMaterial._BumpTextureEnabled = true;
  44526. StandardMaterial._LightmapTextureEnabled = true;
  44527. StandardMaterial._RefractionTextureEnabled = true;
  44528. StandardMaterial._ColorGradingTextureEnabled = true;
  44529. StandardMaterial._FresnelEnabled = true;
  44530. __decorate([
  44531. BABYLON.serializeAsTexture("diffuseTexture")
  44532. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44533. __decorate([
  44534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44535. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44536. __decorate([
  44537. BABYLON.serializeAsTexture("ambientTexture")
  44538. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44539. __decorate([
  44540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44541. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44542. __decorate([
  44543. BABYLON.serializeAsTexture("opacityTexture")
  44544. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44545. __decorate([
  44546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44547. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44548. __decorate([
  44549. BABYLON.serializeAsTexture("reflectionTexture")
  44550. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44551. __decorate([
  44552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44553. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44554. __decorate([
  44555. BABYLON.serializeAsTexture("emissiveTexture")
  44556. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44557. __decorate([
  44558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44559. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44560. __decorate([
  44561. BABYLON.serializeAsTexture("specularTexture")
  44562. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44563. __decorate([
  44564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44565. ], StandardMaterial.prototype, "specularTexture", void 0);
  44566. __decorate([
  44567. BABYLON.serializeAsTexture("bumpTexture")
  44568. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44569. __decorate([
  44570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44571. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44572. __decorate([
  44573. BABYLON.serializeAsTexture("lightmapTexture")
  44574. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44575. __decorate([
  44576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44577. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44578. __decorate([
  44579. BABYLON.serializeAsTexture("refractionTexture")
  44580. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44581. __decorate([
  44582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44583. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44584. __decorate([
  44585. BABYLON.serializeAsColor3("ambient")
  44586. ], StandardMaterial.prototype, "ambientColor", void 0);
  44587. __decorate([
  44588. BABYLON.serializeAsColor3("diffuse")
  44589. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44590. __decorate([
  44591. BABYLON.serializeAsColor3("specular")
  44592. ], StandardMaterial.prototype, "specularColor", void 0);
  44593. __decorate([
  44594. BABYLON.serializeAsColor3("emissive")
  44595. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44596. __decorate([
  44597. BABYLON.serialize()
  44598. ], StandardMaterial.prototype, "specularPower", void 0);
  44599. __decorate([
  44600. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44601. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44602. __decorate([
  44603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44604. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44605. __decorate([
  44606. BABYLON.serialize("useEmissiveAsIllumination")
  44607. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44608. __decorate([
  44609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44610. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44611. __decorate([
  44612. BABYLON.serialize("linkEmissiveWithDiffuse")
  44613. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44614. __decorate([
  44615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44616. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44617. __decorate([
  44618. BABYLON.serialize("useSpecularOverAlpha")
  44619. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44620. __decorate([
  44621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44622. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44623. __decorate([
  44624. BABYLON.serialize("useReflectionOverAlpha")
  44625. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44626. __decorate([
  44627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44628. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44629. __decorate([
  44630. BABYLON.serialize("disableLighting")
  44631. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44632. __decorate([
  44633. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44634. ], StandardMaterial.prototype, "disableLighting", void 0);
  44635. __decorate([
  44636. BABYLON.serialize("useObjectSpaceNormalMap")
  44637. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44638. __decorate([
  44639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44640. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44641. __decorate([
  44642. BABYLON.serialize("useParallax")
  44643. ], StandardMaterial.prototype, "_useParallax", void 0);
  44644. __decorate([
  44645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44646. ], StandardMaterial.prototype, "useParallax", void 0);
  44647. __decorate([
  44648. BABYLON.serialize("useParallaxOcclusion")
  44649. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44650. __decorate([
  44651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44652. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44653. __decorate([
  44654. BABYLON.serialize()
  44655. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44656. __decorate([
  44657. BABYLON.serialize("roughness")
  44658. ], StandardMaterial.prototype, "_roughness", void 0);
  44659. __decorate([
  44660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44661. ], StandardMaterial.prototype, "roughness", void 0);
  44662. __decorate([
  44663. BABYLON.serialize()
  44664. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44665. __decorate([
  44666. BABYLON.serialize()
  44667. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44668. __decorate([
  44669. BABYLON.serialize()
  44670. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44671. __decorate([
  44672. BABYLON.serialize("useLightmapAsShadowmap")
  44673. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44674. __decorate([
  44675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44676. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44677. __decorate([
  44678. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44679. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44680. __decorate([
  44681. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44682. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44683. __decorate([
  44684. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44685. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44686. __decorate([
  44687. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44688. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44689. __decorate([
  44690. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44691. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44692. __decorate([
  44693. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44694. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44695. __decorate([
  44696. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44697. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44698. __decorate([
  44699. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44700. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44701. __decorate([
  44702. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44703. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44704. __decorate([
  44705. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44706. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44707. __decorate([
  44708. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44709. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44710. __decorate([
  44711. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44712. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44713. __decorate([
  44714. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44715. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44716. __decorate([
  44717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44718. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44719. __decorate([
  44720. BABYLON.serialize("maxSimultaneousLights")
  44721. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44722. __decorate([
  44723. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44724. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44725. __decorate([
  44726. BABYLON.serialize("invertNormalMapX")
  44727. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44728. __decorate([
  44729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44730. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44731. __decorate([
  44732. BABYLON.serialize("invertNormalMapY")
  44733. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44734. __decorate([
  44735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44736. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44737. __decorate([
  44738. BABYLON.serialize("twoSidedLighting")
  44739. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44740. __decorate([
  44741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44742. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44743. __decorate([
  44744. BABYLON.serialize()
  44745. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44746. return StandardMaterial;
  44747. }(BABYLON.PushMaterial));
  44748. BABYLON.StandardMaterial = StandardMaterial;
  44749. })(BABYLON || (BABYLON = {}));
  44750. //# sourceMappingURL=babylon.standardMaterial.js.map
  44751. var BABYLON;
  44752. (function (BABYLON) {
  44753. /**
  44754. * Manages the defines for the PBR Material.
  44755. * @hiddenChildren
  44756. */
  44757. var PBRMaterialDefines = /** @class */ (function (_super) {
  44758. __extends(PBRMaterialDefines, _super);
  44759. /**
  44760. * Initializes the PBR Material defines.
  44761. */
  44762. function PBRMaterialDefines() {
  44763. var _this = _super.call(this) || this;
  44764. _this.PBR = true;
  44765. _this.MAINUV1 = false;
  44766. _this.MAINUV2 = false;
  44767. _this.UV1 = false;
  44768. _this.UV2 = false;
  44769. _this.ALBEDO = false;
  44770. _this.ALBEDODIRECTUV = 0;
  44771. _this.VERTEXCOLOR = false;
  44772. _this.AMBIENT = false;
  44773. _this.AMBIENTDIRECTUV = 0;
  44774. _this.AMBIENTINGRAYSCALE = false;
  44775. _this.OPACITY = false;
  44776. _this.VERTEXALPHA = false;
  44777. _this.OPACITYDIRECTUV = 0;
  44778. _this.OPACITYRGB = false;
  44779. _this.ALPHATEST = false;
  44780. _this.DEPTHPREPASS = false;
  44781. _this.ALPHABLEND = false;
  44782. _this.ALPHAFROMALBEDO = false;
  44783. _this.ALPHATESTVALUE = "0.5";
  44784. _this.SPECULAROVERALPHA = false;
  44785. _this.RADIANCEOVERALPHA = false;
  44786. _this.ALPHAFRESNEL = false;
  44787. _this.LINEARALPHAFRESNEL = false;
  44788. _this.PREMULTIPLYALPHA = false;
  44789. _this.EMISSIVE = false;
  44790. _this.EMISSIVEDIRECTUV = 0;
  44791. _this.REFLECTIVITY = false;
  44792. _this.REFLECTIVITYDIRECTUV = 0;
  44793. _this.SPECULARTERM = false;
  44794. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44795. _this.MICROSURFACEAUTOMATIC = false;
  44796. _this.LODBASEDMICROSFURACE = false;
  44797. _this.MICROSURFACEMAP = false;
  44798. _this.MICROSURFACEMAPDIRECTUV = 0;
  44799. _this.METALLICWORKFLOW = false;
  44800. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44801. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44802. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44803. _this.AOSTOREINMETALMAPRED = false;
  44804. _this.ENVIRONMENTBRDF = false;
  44805. _this.NORMAL = false;
  44806. _this.TANGENT = false;
  44807. _this.BUMP = false;
  44808. _this.BUMPDIRECTUV = 0;
  44809. _this.OBJECTSPACE_NORMALMAP = false;
  44810. _this.PARALLAX = false;
  44811. _this.PARALLAXOCCLUSION = false;
  44812. _this.NORMALXYSCALE = true;
  44813. _this.LIGHTMAP = false;
  44814. _this.LIGHTMAPDIRECTUV = 0;
  44815. _this.USELIGHTMAPASSHADOWMAP = false;
  44816. _this.GAMMALIGHTMAP = false;
  44817. _this.REFLECTION = false;
  44818. _this.REFLECTIONMAP_3D = false;
  44819. _this.REFLECTIONMAP_SPHERICAL = false;
  44820. _this.REFLECTIONMAP_PLANAR = false;
  44821. _this.REFLECTIONMAP_CUBIC = false;
  44822. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44823. _this.REFLECTIONMAP_PROJECTION = false;
  44824. _this.REFLECTIONMAP_SKYBOX = false;
  44825. _this.REFLECTIONMAP_EXPLICIT = false;
  44826. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44827. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44828. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44829. _this.INVERTCUBICMAP = false;
  44830. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44831. _this.USESPHERICALINVERTEX = false;
  44832. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44833. _this.LODINREFLECTIONALPHA = false;
  44834. _this.GAMMAREFLECTION = false;
  44835. _this.RGBDREFLECTION = false;
  44836. _this.RADIANCEOCCLUSION = false;
  44837. _this.HORIZONOCCLUSION = false;
  44838. _this.REFRACTION = false;
  44839. _this.REFRACTIONMAP_3D = false;
  44840. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44841. _this.LODINREFRACTIONALPHA = false;
  44842. _this.GAMMAREFRACTION = false;
  44843. _this.RGBDREFRACTION = false;
  44844. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44845. _this.INSTANCES = false;
  44846. _this.NUM_BONE_INFLUENCERS = 0;
  44847. _this.BonesPerMesh = 0;
  44848. _this.NONUNIFORMSCALING = false;
  44849. _this.MORPHTARGETS = false;
  44850. _this.MORPHTARGETS_NORMAL = false;
  44851. _this.MORPHTARGETS_TANGENT = false;
  44852. _this.NUM_MORPH_INFLUENCERS = 0;
  44853. _this.IMAGEPROCESSING = false;
  44854. _this.VIGNETTE = false;
  44855. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44856. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44857. _this.TONEMAPPING = false;
  44858. _this.CONTRAST = false;
  44859. _this.COLORCURVES = false;
  44860. _this.COLORGRADING = false;
  44861. _this.COLORGRADING3D = false;
  44862. _this.SAMPLER3DGREENDEPTH = false;
  44863. _this.SAMPLER3DBGRMAP = false;
  44864. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44865. _this.EXPOSURE = false;
  44866. _this.USEPHYSICALLIGHTFALLOFF = false;
  44867. _this.TWOSIDEDLIGHTING = false;
  44868. _this.SHADOWFLOAT = false;
  44869. _this.CLIPPLANE = false;
  44870. _this.POINTSIZE = false;
  44871. _this.FOG = false;
  44872. _this.LOGARITHMICDEPTH = false;
  44873. _this.FORCENORMALFORWARD = false;
  44874. _this.SPECULARAA = false;
  44875. _this.UNLIT = false;
  44876. _this.rebuild();
  44877. return _this;
  44878. }
  44879. /**
  44880. * Resets the PBR Material defines.
  44881. */
  44882. PBRMaterialDefines.prototype.reset = function () {
  44883. _super.prototype.reset.call(this);
  44884. this.ALPHATESTVALUE = "0.5";
  44885. this.PBR = true;
  44886. };
  44887. return PBRMaterialDefines;
  44888. }(BABYLON.MaterialDefines));
  44889. /**
  44890. * The Physically based material base class of BJS.
  44891. *
  44892. * This offers the main features of a standard PBR material.
  44893. * For more information, please refer to the documentation :
  44894. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44895. */
  44896. var PBRBaseMaterial = /** @class */ (function (_super) {
  44897. __extends(PBRBaseMaterial, _super);
  44898. /**
  44899. * Instantiates a new PBRMaterial instance.
  44900. *
  44901. * @param name The material name
  44902. * @param scene The scene the material will be use in.
  44903. */
  44904. function PBRBaseMaterial(name, scene) {
  44905. var _this = _super.call(this, name, scene) || this;
  44906. /**
  44907. * Intensity of the direct lights e.g. the four lights available in your scene.
  44908. * This impacts both the direct diffuse and specular highlights.
  44909. */
  44910. _this._directIntensity = 1.0;
  44911. /**
  44912. * Intensity of the emissive part of the material.
  44913. * This helps controlling the emissive effect without modifying the emissive color.
  44914. */
  44915. _this._emissiveIntensity = 1.0;
  44916. /**
  44917. * Intensity of the environment e.g. how much the environment will light the object
  44918. * either through harmonics for rough material or through the refelction for shiny ones.
  44919. */
  44920. _this._environmentIntensity = 1.0;
  44921. /**
  44922. * This is a special control allowing the reduction of the specular highlights coming from the
  44923. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44924. */
  44925. _this._specularIntensity = 1.0;
  44926. /**
  44927. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44928. */
  44929. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44930. /**
  44931. * Debug Control allowing disabling the bump map on this material.
  44932. */
  44933. _this._disableBumpMap = false;
  44934. /**
  44935. * AKA Occlusion Texture Intensity in other nomenclature.
  44936. */
  44937. _this._ambientTextureStrength = 1.0;
  44938. /**
  44939. * The color of a material in ambient lighting.
  44940. */
  44941. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44942. /**
  44943. * AKA Diffuse Color in other nomenclature.
  44944. */
  44945. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44946. /**
  44947. * AKA Specular Color in other nomenclature.
  44948. */
  44949. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44950. /**
  44951. * The color applied when light is reflected from a material.
  44952. */
  44953. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44954. /**
  44955. * The color applied when light is emitted from a material.
  44956. */
  44957. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44958. /**
  44959. * AKA Glossiness in other nomenclature.
  44960. */
  44961. _this._microSurface = 0.9;
  44962. /**
  44963. * source material index of refraction (IOR)' / 'destination material IOR.
  44964. */
  44965. _this._indexOfRefraction = 0.66;
  44966. /**
  44967. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44968. */
  44969. _this._invertRefractionY = false;
  44970. /**
  44971. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44972. * Materials half opaque for instance using refraction could benefit from this control.
  44973. */
  44974. _this._linkRefractionWithTransparency = false;
  44975. /**
  44976. * Specifies that the material will use the light map as a show map.
  44977. */
  44978. _this._useLightmapAsShadowmap = false;
  44979. /**
  44980. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44981. * makes the reflect vector face the model (under horizon).
  44982. */
  44983. _this._useHorizonOcclusion = true;
  44984. /**
  44985. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44986. * too much the area relying on ambient texture to define their ambient occlusion.
  44987. */
  44988. _this._useRadianceOcclusion = true;
  44989. /**
  44990. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44991. */
  44992. _this._useAlphaFromAlbedoTexture = false;
  44993. /**
  44994. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44995. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44996. */
  44997. _this._useSpecularOverAlpha = true;
  44998. /**
  44999. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45000. */
  45001. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  45002. /**
  45003. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45004. */
  45005. _this._useRoughnessFromMetallicTextureAlpha = true;
  45006. /**
  45007. * Specifies if the metallic texture contains the roughness information in its green channel.
  45008. */
  45009. _this._useRoughnessFromMetallicTextureGreen = false;
  45010. /**
  45011. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45012. */
  45013. _this._useMetallnessFromMetallicTextureBlue = false;
  45014. /**
  45015. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45016. */
  45017. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  45018. /**
  45019. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45020. */
  45021. _this._useAmbientInGrayScale = false;
  45022. /**
  45023. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45024. * The material will try to infer what glossiness each pixel should be.
  45025. */
  45026. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  45027. /**
  45028. * BJS is using an harcoded light falloff based on a manually sets up range.
  45029. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45030. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45031. */
  45032. _this._usePhysicalLightFalloff = true;
  45033. /**
  45034. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45035. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45036. */
  45037. _this._useRadianceOverAlpha = true;
  45038. /**
  45039. * Allows using an object space normal map (instead of tangent space).
  45040. */
  45041. _this._useObjectSpaceNormalMap = false;
  45042. /**
  45043. * Allows using the bump map in parallax mode.
  45044. */
  45045. _this._useParallax = false;
  45046. /**
  45047. * Allows using the bump map in parallax occlusion mode.
  45048. */
  45049. _this._useParallaxOcclusion = false;
  45050. /**
  45051. * Controls the scale bias of the parallax mode.
  45052. */
  45053. _this._parallaxScaleBias = 0.05;
  45054. /**
  45055. * If sets to true, disables all the lights affecting the material.
  45056. */
  45057. _this._disableLighting = false;
  45058. /**
  45059. * Number of Simultaneous lights allowed on the material.
  45060. */
  45061. _this._maxSimultaneousLights = 4;
  45062. /**
  45063. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  45064. */
  45065. _this._invertNormalMapX = false;
  45066. /**
  45067. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  45068. */
  45069. _this._invertNormalMapY = false;
  45070. /**
  45071. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45072. */
  45073. _this._twoSidedLighting = false;
  45074. /**
  45075. * Defines the alpha limits in alpha test mode.
  45076. */
  45077. _this._alphaCutOff = 0.4;
  45078. /**
  45079. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45080. */
  45081. _this._forceAlphaTest = false;
  45082. /**
  45083. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45084. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45085. */
  45086. _this._useAlphaFresnel = false;
  45087. /**
  45088. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45089. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45090. */
  45091. _this._useLinearAlphaFresnel = false;
  45092. /**
  45093. * The transparency mode of the material.
  45094. */
  45095. _this._transparencyMode = null;
  45096. /**
  45097. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  45098. * from cos thetav and roughness:
  45099. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  45100. */
  45101. _this._environmentBRDFTexture = null;
  45102. /**
  45103. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45104. */
  45105. _this._forceIrradianceInFragment = false;
  45106. /**
  45107. * Force normal to face away from face.
  45108. */
  45109. _this._forceNormalForward = false;
  45110. /**
  45111. * Enables specular anti aliasing in the PBR shader.
  45112. * It will both interacts on the Geometry for analytical and IBL lighting.
  45113. * It also prefilter the roughness map based on the bump values.
  45114. */
  45115. _this._enableSpecularAntiAliasing = false;
  45116. /**
  45117. * Stores the available render targets.
  45118. */
  45119. _this._renderTargets = new BABYLON.SmartArray(16);
  45120. /**
  45121. * Sets the global ambient color for the material used in lighting calculations.
  45122. */
  45123. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  45124. /**
  45125. * If set to true, no lighting calculations will be applied.
  45126. */
  45127. _this._unlit = false;
  45128. // Setup the default processing configuration to the scene.
  45129. _this._attachImageProcessingConfiguration(null);
  45130. _this.getRenderTargetTextures = function () {
  45131. _this._renderTargets.reset();
  45132. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  45133. _this._renderTargets.push(_this._reflectionTexture);
  45134. }
  45135. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  45136. _this._renderTargets.push(_this._refractionTexture);
  45137. }
  45138. return _this._renderTargets;
  45139. };
  45140. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45141. return _this;
  45142. }
  45143. /**
  45144. * Attaches a new image processing configuration to the PBR Material.
  45145. * @param configuration
  45146. */
  45147. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  45148. var _this = this;
  45149. if (configuration === this._imageProcessingConfiguration) {
  45150. return;
  45151. }
  45152. // Detaches observer.
  45153. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45154. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45155. }
  45156. // Pick the scene configuration if needed.
  45157. if (!configuration) {
  45158. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  45159. }
  45160. else {
  45161. this._imageProcessingConfiguration = configuration;
  45162. }
  45163. // Attaches observer.
  45164. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  45165. _this._markAllSubMeshesAsImageProcessingDirty();
  45166. });
  45167. };
  45168. /**
  45169. * Gets the name of the material class.
  45170. */
  45171. PBRBaseMaterial.prototype.getClassName = function () {
  45172. return "PBRBaseMaterial";
  45173. };
  45174. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  45175. /**
  45176. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45177. */
  45178. get: function () {
  45179. return this._useLogarithmicDepth;
  45180. },
  45181. /**
  45182. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45183. */
  45184. set: function (value) {
  45185. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  45186. },
  45187. enumerable: true,
  45188. configurable: true
  45189. });
  45190. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  45191. /**
  45192. * Gets the current transparency mode.
  45193. */
  45194. get: function () {
  45195. return this._transparencyMode;
  45196. },
  45197. /**
  45198. * Sets the transparency mode of the material.
  45199. *
  45200. * | Value | Type | Description |
  45201. * | ----- | ----------------------------------- | ----------- |
  45202. * | 0 | OPAQUE | |
  45203. * | 1 | ALPHATEST | |
  45204. * | 2 | ALPHABLEND | |
  45205. * | 3 | ALPHATESTANDBLEND | |
  45206. *
  45207. */
  45208. set: function (value) {
  45209. if (this._transparencyMode === value) {
  45210. return;
  45211. }
  45212. this._transparencyMode = value;
  45213. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  45214. this._markAllSubMeshesAsTexturesAndMiscDirty();
  45215. },
  45216. enumerable: true,
  45217. configurable: true
  45218. });
  45219. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  45220. /**
  45221. * Returns true if alpha blending should be disabled.
  45222. */
  45223. get: function () {
  45224. return (this._linkRefractionWithTransparency ||
  45225. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  45226. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45227. },
  45228. enumerable: true,
  45229. configurable: true
  45230. });
  45231. /**
  45232. * Specifies whether or not this material should be rendered in alpha blend mode.
  45233. */
  45234. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  45235. if (this._disableAlphaBlending) {
  45236. return false;
  45237. }
  45238. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  45239. };
  45240. /**
  45241. * Specifies if the mesh will require alpha blending.
  45242. * @param mesh - BJS mesh.
  45243. */
  45244. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  45245. if (this._disableAlphaBlending) {
  45246. return false;
  45247. }
  45248. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  45249. };
  45250. /**
  45251. * Specifies whether or not this material should be rendered in alpha test mode.
  45252. */
  45253. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  45254. if (this._forceAlphaTest) {
  45255. return true;
  45256. }
  45257. if (this._linkRefractionWithTransparency) {
  45258. return false;
  45259. }
  45260. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45261. };
  45262. /**
  45263. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45264. */
  45265. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45266. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45267. };
  45268. /**
  45269. * Gets the texture used for the alpha test.
  45270. */
  45271. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45272. return this._albedoTexture;
  45273. };
  45274. /**
  45275. * Specifies that the submesh is ready to be used.
  45276. * @param mesh - BJS mesh.
  45277. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45278. * @param useInstances - Specifies that instances should be used.
  45279. * @returns - boolean indicating that the submesh is ready or not.
  45280. */
  45281. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45282. if (subMesh.effect && this.isFrozen) {
  45283. if (this._wasPreviouslyReady) {
  45284. return true;
  45285. }
  45286. }
  45287. if (!subMesh._materialDefines) {
  45288. subMesh._materialDefines = new PBRMaterialDefines();
  45289. }
  45290. var defines = subMesh._materialDefines;
  45291. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45292. if (defines._renderId === this.getScene().getRenderId()) {
  45293. return true;
  45294. }
  45295. }
  45296. var scene = this.getScene();
  45297. var engine = scene.getEngine();
  45298. if (defines._areTexturesDirty) {
  45299. if (scene.texturesEnabled) {
  45300. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45301. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45302. return false;
  45303. }
  45304. }
  45305. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45306. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45307. return false;
  45308. }
  45309. }
  45310. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45311. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45312. return false;
  45313. }
  45314. }
  45315. var reflectionTexture = this._getReflectionTexture();
  45316. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45317. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45318. return false;
  45319. }
  45320. }
  45321. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45322. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45323. return false;
  45324. }
  45325. }
  45326. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45327. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45328. return false;
  45329. }
  45330. }
  45331. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45332. if (this._metallicTexture) {
  45333. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45334. return false;
  45335. }
  45336. }
  45337. else if (this._reflectivityTexture) {
  45338. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45339. return false;
  45340. }
  45341. }
  45342. if (this._microSurfaceTexture) {
  45343. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45344. return false;
  45345. }
  45346. }
  45347. }
  45348. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45349. // Bump texture cannot be not blocking.
  45350. if (!this._bumpTexture.isReady()) {
  45351. return false;
  45352. }
  45353. }
  45354. var refractionTexture = this._getRefractionTexture();
  45355. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45356. if (!refractionTexture.isReadyOrNotBlocking()) {
  45357. return false;
  45358. }
  45359. }
  45360. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45361. // This is blocking.
  45362. if (!this._environmentBRDFTexture.isReady()) {
  45363. return false;
  45364. }
  45365. }
  45366. }
  45367. }
  45368. if (defines._areImageProcessingDirty) {
  45369. if (!this._imageProcessingConfiguration.isReady()) {
  45370. return false;
  45371. }
  45372. }
  45373. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45374. mesh.createNormals(true);
  45375. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45376. }
  45377. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45378. if (effect) {
  45379. scene.resetCachedMaterial();
  45380. subMesh.setEffect(effect, defines);
  45381. this.buildUniformLayout();
  45382. }
  45383. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45384. return false;
  45385. }
  45386. defines._renderId = scene.getRenderId();
  45387. this._wasPreviouslyReady = true;
  45388. return true;
  45389. };
  45390. /**
  45391. * Specifies if the material uses metallic roughness workflow.
  45392. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45393. */
  45394. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45395. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45396. return true;
  45397. }
  45398. return false;
  45399. };
  45400. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45401. if (onCompiled === void 0) { onCompiled = null; }
  45402. if (onError === void 0) { onError = null; }
  45403. if (useInstances === void 0) { useInstances = null; }
  45404. if (useClipPlane === void 0) { useClipPlane = null; }
  45405. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45406. if (!defines.isDirty) {
  45407. return null;
  45408. }
  45409. defines.markAsProcessed();
  45410. var scene = this.getScene();
  45411. var engine = scene.getEngine();
  45412. // Fallbacks
  45413. var fallbacks = new BABYLON.EffectFallbacks();
  45414. var fallbackRank = 0;
  45415. if (defines.USESPHERICALINVERTEX) {
  45416. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45417. }
  45418. if (defines.FOG) {
  45419. fallbacks.addFallback(fallbackRank, "FOG");
  45420. }
  45421. if (defines.SPECULARAA) {
  45422. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45423. }
  45424. if (defines.POINTSIZE) {
  45425. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45426. }
  45427. if (defines.LOGARITHMICDEPTH) {
  45428. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45429. }
  45430. if (defines.PARALLAX) {
  45431. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45432. }
  45433. if (defines.PARALLAXOCCLUSION) {
  45434. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45435. }
  45436. if (defines.ENVIRONMENTBRDF) {
  45437. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45438. }
  45439. if (defines.TANGENT) {
  45440. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45441. }
  45442. if (defines.BUMP) {
  45443. fallbacks.addFallback(fallbackRank++, "BUMP");
  45444. }
  45445. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45446. if (defines.SPECULARTERM) {
  45447. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45448. }
  45449. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45450. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45451. }
  45452. if (defines.LIGHTMAP) {
  45453. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45454. }
  45455. if (defines.NORMAL) {
  45456. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45457. }
  45458. if (defines.AMBIENT) {
  45459. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45460. }
  45461. if (defines.EMISSIVE) {
  45462. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45463. }
  45464. if (defines.VERTEXCOLOR) {
  45465. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45466. }
  45467. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45468. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45469. }
  45470. if (defines.MORPHTARGETS) {
  45471. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45472. }
  45473. //Attributes
  45474. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45475. if (defines.NORMAL) {
  45476. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45477. }
  45478. if (defines.TANGENT) {
  45479. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45480. }
  45481. if (defines.UV1) {
  45482. attribs.push(BABYLON.VertexBuffer.UVKind);
  45483. }
  45484. if (defines.UV2) {
  45485. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45486. }
  45487. if (defines.VERTEXCOLOR) {
  45488. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45489. }
  45490. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45491. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45492. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45493. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45494. "vFogInfos", "vFogColor", "pointSize",
  45495. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45496. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45497. "mBones",
  45498. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45499. "vLightingIntensity",
  45500. "logarithmicDepthConstant",
  45501. "vSphericalX", "vSphericalY", "vSphericalZ",
  45502. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45503. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45504. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45505. "vTangentSpaceParams"
  45506. ];
  45507. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45508. "bumpSampler", "lightmapSampler", "opacitySampler",
  45509. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45510. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45511. "microSurfaceSampler", "environmentBrdfSampler"];
  45512. var uniformBuffers = ["Material", "Scene"];
  45513. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45514. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45515. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45516. uniformsNames: uniforms,
  45517. uniformBuffersNames: uniformBuffers,
  45518. samplers: samplers,
  45519. defines: defines,
  45520. maxSimultaneousLights: this._maxSimultaneousLights
  45521. });
  45522. var join = defines.toString();
  45523. return engine.createEffect("pbr", {
  45524. attributes: attribs,
  45525. uniformsNames: uniforms,
  45526. uniformBuffersNames: uniformBuffers,
  45527. samplers: samplers,
  45528. defines: join,
  45529. fallbacks: fallbacks,
  45530. onCompiled: onCompiled,
  45531. onError: onError,
  45532. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45533. }, engine);
  45534. };
  45535. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45536. if (useInstances === void 0) { useInstances = null; }
  45537. if (useClipPlane === void 0) { useClipPlane = null; }
  45538. var scene = this.getScene();
  45539. var engine = scene.getEngine();
  45540. // Lights
  45541. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45542. defines._needNormals = true;
  45543. // Textures
  45544. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45545. if (defines._areTexturesDirty) {
  45546. defines._needUVs = false;
  45547. if (scene.texturesEnabled) {
  45548. if (scene.getEngine().getCaps().textureLOD) {
  45549. defines.LODBASEDMICROSFURACE = true;
  45550. }
  45551. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45552. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45553. }
  45554. else {
  45555. defines.ALBEDO = false;
  45556. }
  45557. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45558. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45559. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45560. }
  45561. else {
  45562. defines.AMBIENT = false;
  45563. }
  45564. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45565. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45566. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45567. }
  45568. else {
  45569. defines.OPACITY = false;
  45570. }
  45571. var reflectionTexture = this._getReflectionTexture();
  45572. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45573. defines.REFLECTION = true;
  45574. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45575. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  45576. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45577. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45578. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45579. defines.INVERTCUBICMAP = true;
  45580. }
  45581. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45582. switch (reflectionTexture.coordinatesMode) {
  45583. case BABYLON.Texture.EXPLICIT_MODE:
  45584. defines.REFLECTIONMAP_EXPLICIT = true;
  45585. break;
  45586. case BABYLON.Texture.PLANAR_MODE:
  45587. defines.REFLECTIONMAP_PLANAR = true;
  45588. break;
  45589. case BABYLON.Texture.PROJECTION_MODE:
  45590. defines.REFLECTIONMAP_PROJECTION = true;
  45591. break;
  45592. case BABYLON.Texture.SKYBOX_MODE:
  45593. defines.REFLECTIONMAP_SKYBOX = true;
  45594. break;
  45595. case BABYLON.Texture.SPHERICAL_MODE:
  45596. defines.REFLECTIONMAP_SPHERICAL = true;
  45597. break;
  45598. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45599. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45600. break;
  45601. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45602. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45603. break;
  45604. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45605. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45606. break;
  45607. case BABYLON.Texture.CUBIC_MODE:
  45608. case BABYLON.Texture.INVCUBIC_MODE:
  45609. default:
  45610. defines.REFLECTIONMAP_CUBIC = true;
  45611. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45612. break;
  45613. }
  45614. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45615. if (reflectionTexture.sphericalPolynomial) {
  45616. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45617. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45618. defines.USESPHERICALINVERTEX = false;
  45619. }
  45620. else {
  45621. defines.USESPHERICALINVERTEX = true;
  45622. }
  45623. }
  45624. }
  45625. }
  45626. else {
  45627. defines.REFLECTION = false;
  45628. defines.REFLECTIONMAP_3D = false;
  45629. defines.REFLECTIONMAP_SPHERICAL = false;
  45630. defines.REFLECTIONMAP_PLANAR = false;
  45631. defines.REFLECTIONMAP_CUBIC = false;
  45632. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45633. defines.REFLECTIONMAP_PROJECTION = false;
  45634. defines.REFLECTIONMAP_SKYBOX = false;
  45635. defines.REFLECTIONMAP_EXPLICIT = false;
  45636. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45637. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45638. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45639. defines.INVERTCUBICMAP = false;
  45640. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45641. defines.USESPHERICALINVERTEX = false;
  45642. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45643. defines.LODINREFLECTIONALPHA = false;
  45644. defines.GAMMAREFLECTION = false;
  45645. defines.RGBDREFLECTION = false;
  45646. }
  45647. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45648. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45649. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45650. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45651. }
  45652. else {
  45653. defines.LIGHTMAP = false;
  45654. }
  45655. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45656. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45657. }
  45658. else {
  45659. defines.EMISSIVE = false;
  45660. }
  45661. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45662. if (this._metallicTexture) {
  45663. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45664. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45665. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45666. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45667. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45668. }
  45669. else if (this._reflectivityTexture) {
  45670. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45671. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45672. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45673. }
  45674. else {
  45675. defines.REFLECTIVITY = false;
  45676. }
  45677. if (this._microSurfaceTexture) {
  45678. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45679. }
  45680. else {
  45681. defines.MICROSURFACEMAP = false;
  45682. }
  45683. }
  45684. else {
  45685. defines.REFLECTIVITY = false;
  45686. defines.MICROSURFACEMAP = false;
  45687. }
  45688. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45689. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45690. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45691. defines.PARALLAX = true;
  45692. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45693. }
  45694. else {
  45695. defines.PARALLAX = false;
  45696. }
  45697. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45698. }
  45699. else {
  45700. defines.BUMP = false;
  45701. }
  45702. var refractionTexture = this._getRefractionTexture();
  45703. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45704. defines.REFRACTION = true;
  45705. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45706. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45707. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  45708. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45709. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45710. if (this._linkRefractionWithTransparency) {
  45711. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45712. }
  45713. }
  45714. else {
  45715. defines.REFRACTION = false;
  45716. }
  45717. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45718. defines.ENVIRONMENTBRDF = true;
  45719. }
  45720. else {
  45721. defines.ENVIRONMENTBRDF = false;
  45722. }
  45723. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45724. defines.ALPHAFROMALBEDO = true;
  45725. }
  45726. else {
  45727. defines.ALPHAFROMALBEDO = false;
  45728. }
  45729. }
  45730. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45731. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45732. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45733. if (!this.backFaceCulling && this._twoSidedLighting) {
  45734. defines.TWOSIDEDLIGHTING = true;
  45735. }
  45736. else {
  45737. defines.TWOSIDEDLIGHTING = false;
  45738. }
  45739. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45740. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45741. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45742. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45743. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45744. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45745. }
  45746. if (defines._areImageProcessingDirty) {
  45747. this._imageProcessingConfiguration.prepareDefines(defines);
  45748. }
  45749. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45750. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45751. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45752. // Misc.
  45753. if (defines._areMiscDirty) {
  45754. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45755. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45756. }
  45757. // Values that need to be evaluated on every frame
  45758. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45759. // Attribs
  45760. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45761. };
  45762. /**
  45763. * Force shader compilation
  45764. */
  45765. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45766. var _this = this;
  45767. var localOptions = __assign({ clipPlane: false }, options);
  45768. var defines = new PBRMaterialDefines();
  45769. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45770. if (effect.isReady()) {
  45771. if (onCompiled) {
  45772. onCompiled(this);
  45773. }
  45774. }
  45775. else {
  45776. effect.onCompileObservable.add(function () {
  45777. if (onCompiled) {
  45778. onCompiled(_this);
  45779. }
  45780. });
  45781. }
  45782. };
  45783. /**
  45784. * Initializes the uniform buffer layout for the shader.
  45785. */
  45786. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45787. // Order is important !
  45788. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45789. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45790. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45791. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45792. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45793. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45794. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45795. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45796. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45797. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45798. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45799. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45800. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45801. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45802. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45803. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45804. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45805. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45806. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45807. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45808. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45809. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45810. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45811. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45812. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45813. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45814. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45815. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45816. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45817. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45818. this._uniformBuffer.addUniform("pointSize", 1);
  45819. this._uniformBuffer.create();
  45820. };
  45821. /**
  45822. * Unbinds the textures.
  45823. */
  45824. PBRBaseMaterial.prototype.unbind = function () {
  45825. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45826. this._uniformBuffer.setTexture("reflectionSampler", null);
  45827. }
  45828. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45829. this._uniformBuffer.setTexture("refractionSampler", null);
  45830. }
  45831. _super.prototype.unbind.call(this);
  45832. };
  45833. /**
  45834. * Binds the submesh data.
  45835. * @param world - The world matrix.
  45836. * @param mesh - The BJS mesh.
  45837. * @param subMesh - A submesh of the BJS mesh.
  45838. */
  45839. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45840. var scene = this.getScene();
  45841. var defines = subMesh._materialDefines;
  45842. if (!defines) {
  45843. return;
  45844. }
  45845. var effect = subMesh.effect;
  45846. if (!effect) {
  45847. return;
  45848. }
  45849. this._activeEffect = effect;
  45850. // Matrices
  45851. this.bindOnlyWorldMatrix(world);
  45852. // Normal Matrix
  45853. if (defines.OBJECTSPACE_NORMALMAP) {
  45854. world.toNormalMatrix(this._normalMatrix);
  45855. this.bindOnlyNormalMatrix(this._normalMatrix);
  45856. }
  45857. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45858. // Bones
  45859. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45860. var reflectionTexture = null;
  45861. if (mustRebind) {
  45862. this._uniformBuffer.bindToEffect(effect, "Material");
  45863. this.bindViewProjection(effect);
  45864. reflectionTexture = this._getReflectionTexture();
  45865. var refractionTexture = this._getRefractionTexture();
  45866. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45867. // Texture uniforms
  45868. if (scene.texturesEnabled) {
  45869. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45870. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45871. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45872. }
  45873. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45874. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45875. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45876. }
  45877. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45878. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45879. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45880. }
  45881. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45882. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45883. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45884. if (reflectionTexture.boundingBoxSize) {
  45885. var cubeTexture = reflectionTexture;
  45886. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45887. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45888. }
  45889. var polynomials = reflectionTexture.sphericalPolynomial;
  45890. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45891. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45892. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45893. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45894. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45895. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45896. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45897. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45898. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45899. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45900. }
  45901. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45902. }
  45903. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45904. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45905. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45906. }
  45907. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45908. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45909. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45910. }
  45911. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45912. if (this._metallicTexture) {
  45913. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45914. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45915. }
  45916. else if (this._reflectivityTexture) {
  45917. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45918. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45919. }
  45920. if (this._microSurfaceTexture) {
  45921. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45922. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45923. }
  45924. }
  45925. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45926. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45927. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45928. if (scene._mirroredCameraPosition) {
  45929. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45930. }
  45931. else {
  45932. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45933. }
  45934. }
  45935. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45936. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45937. var depth = 1.0;
  45938. if (!refractionTexture.isCube) {
  45939. if (refractionTexture.depth) {
  45940. depth = refractionTexture.depth;
  45941. }
  45942. }
  45943. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45944. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45945. }
  45946. }
  45947. // Point size
  45948. if (this.pointsCloud) {
  45949. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45950. }
  45951. // Colors
  45952. if (defines.METALLICWORKFLOW) {
  45953. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45954. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45955. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45956. }
  45957. else {
  45958. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45959. }
  45960. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45961. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45962. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45963. // Misc
  45964. this._lightingInfos.x = this._directIntensity;
  45965. this._lightingInfos.y = this._emissiveIntensity;
  45966. this._lightingInfos.z = this._environmentIntensity;
  45967. this._lightingInfos.w = this._specularIntensity;
  45968. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45969. }
  45970. // Textures
  45971. if (scene.texturesEnabled) {
  45972. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45973. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45974. }
  45975. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45976. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45977. }
  45978. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45979. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45980. }
  45981. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45982. if (defines.LODBASEDMICROSFURACE) {
  45983. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45984. }
  45985. else {
  45986. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45987. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45988. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45989. }
  45990. }
  45991. if (defines.ENVIRONMENTBRDF) {
  45992. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45993. }
  45994. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45995. if (defines.LODBASEDMICROSFURACE) {
  45996. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45997. }
  45998. else {
  45999. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  46000. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  46001. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  46002. }
  46003. }
  46004. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46005. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  46006. }
  46007. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46008. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  46009. }
  46010. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46011. if (this._metallicTexture) {
  46012. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  46013. }
  46014. else if (this._reflectivityTexture) {
  46015. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  46016. }
  46017. if (this._microSurfaceTexture) {
  46018. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  46019. }
  46020. }
  46021. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46022. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  46023. }
  46024. }
  46025. // Clip plane
  46026. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  46027. // Colors
  46028. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  46029. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  46030. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  46031. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  46032. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  46033. }
  46034. if (mustRebind || !this.isFrozen) {
  46035. // Lights
  46036. if (scene.lightsEnabled && !this._disableLighting) {
  46037. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  46038. }
  46039. // View
  46040. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  46041. this.bindView(effect);
  46042. }
  46043. // Fog
  46044. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  46045. // Morph targets
  46046. if (defines.NUM_MORPH_INFLUENCERS) {
  46047. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  46048. }
  46049. // image processing
  46050. this._imageProcessingConfiguration.bind(this._activeEffect);
  46051. // Log. depth
  46052. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  46053. }
  46054. this._uniformBuffer.update();
  46055. this._afterBind(mesh, this._activeEffect);
  46056. };
  46057. /**
  46058. * Returns the animatable textures.
  46059. * @returns - Array of animatable textures.
  46060. */
  46061. PBRBaseMaterial.prototype.getAnimatables = function () {
  46062. var results = [];
  46063. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  46064. results.push(this._albedoTexture);
  46065. }
  46066. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  46067. results.push(this._ambientTexture);
  46068. }
  46069. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  46070. results.push(this._opacityTexture);
  46071. }
  46072. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  46073. results.push(this._reflectionTexture);
  46074. }
  46075. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  46076. results.push(this._emissiveTexture);
  46077. }
  46078. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  46079. results.push(this._metallicTexture);
  46080. }
  46081. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  46082. results.push(this._reflectivityTexture);
  46083. }
  46084. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  46085. results.push(this._bumpTexture);
  46086. }
  46087. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  46088. results.push(this._lightmapTexture);
  46089. }
  46090. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  46091. results.push(this._refractionTexture);
  46092. }
  46093. return results;
  46094. };
  46095. /**
  46096. * Returns the texture used for reflections.
  46097. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  46098. */
  46099. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  46100. if (this._reflectionTexture) {
  46101. return this._reflectionTexture;
  46102. }
  46103. return this.getScene().environmentTexture;
  46104. };
  46105. /**
  46106. * Returns the texture used for refraction or null if none is used.
  46107. * @returns - Refection texture if present. If no refraction texture and refraction
  46108. * is linked with transparency, returns environment texture. Otherwise, returns null.
  46109. */
  46110. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  46111. if (this._refractionTexture) {
  46112. return this._refractionTexture;
  46113. }
  46114. if (this._linkRefractionWithTransparency) {
  46115. return this.getScene().environmentTexture;
  46116. }
  46117. return null;
  46118. };
  46119. /**
  46120. * Disposes the resources of the material.
  46121. * @param forceDisposeEffect - Forces the disposal of effects.
  46122. * @param forceDisposeTextures - Forces the disposal of all textures.
  46123. */
  46124. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46125. if (forceDisposeTextures) {
  46126. if (this._albedoTexture) {
  46127. this._albedoTexture.dispose();
  46128. }
  46129. if (this._ambientTexture) {
  46130. this._ambientTexture.dispose();
  46131. }
  46132. if (this._opacityTexture) {
  46133. this._opacityTexture.dispose();
  46134. }
  46135. if (this._reflectionTexture) {
  46136. this._reflectionTexture.dispose();
  46137. }
  46138. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  46139. this._environmentBRDFTexture.dispose();
  46140. }
  46141. if (this._emissiveTexture) {
  46142. this._emissiveTexture.dispose();
  46143. }
  46144. if (this._metallicTexture) {
  46145. this._metallicTexture.dispose();
  46146. }
  46147. if (this._reflectivityTexture) {
  46148. this._reflectivityTexture.dispose();
  46149. }
  46150. if (this._bumpTexture) {
  46151. this._bumpTexture.dispose();
  46152. }
  46153. if (this._lightmapTexture) {
  46154. this._lightmapTexture.dispose();
  46155. }
  46156. if (this._refractionTexture) {
  46157. this._refractionTexture.dispose();
  46158. }
  46159. }
  46160. this._renderTargets.dispose();
  46161. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  46162. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  46163. }
  46164. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46165. };
  46166. /**
  46167. * Stores the reflectivity values based on metallic roughness workflow.
  46168. */
  46169. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  46170. __decorate([
  46171. BABYLON.serializeAsImageProcessingConfiguration()
  46172. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  46173. __decorate([
  46174. BABYLON.serialize()
  46175. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  46176. __decorate([
  46177. BABYLON.serialize()
  46178. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  46179. return PBRBaseMaterial;
  46180. }(BABYLON.PushMaterial));
  46181. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  46182. })(BABYLON || (BABYLON = {}));
  46183. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  46184. var BABYLON;
  46185. (function (BABYLON) {
  46186. /**
  46187. * The Physically based simple base material of BJS.
  46188. *
  46189. * This enables better naming and convention enforcements on top of the pbrMaterial.
  46190. * It is used as the base class for both the specGloss and metalRough conventions.
  46191. */
  46192. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  46193. __extends(PBRBaseSimpleMaterial, _super);
  46194. /**
  46195. * Instantiates a new PBRMaterial instance.
  46196. *
  46197. * @param name The material name
  46198. * @param scene The scene the material will be use in.
  46199. */
  46200. function PBRBaseSimpleMaterial(name, scene) {
  46201. var _this = _super.call(this, name, scene) || this;
  46202. /**
  46203. * Number of Simultaneous lights allowed on the material.
  46204. */
  46205. _this.maxSimultaneousLights = 4;
  46206. /**
  46207. * If sets to true, disables all the lights affecting the material.
  46208. */
  46209. _this.disableLighting = false;
  46210. /**
  46211. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46212. */
  46213. _this.invertNormalMapX = false;
  46214. /**
  46215. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46216. */
  46217. _this.invertNormalMapY = false;
  46218. /**
  46219. * Emissivie color used to self-illuminate the model.
  46220. */
  46221. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46222. /**
  46223. * Occlusion Channel Strenght.
  46224. */
  46225. _this.occlusionStrength = 1.0;
  46226. _this.useLightmapAsShadowmap = false;
  46227. _this._useAlphaFromAlbedoTexture = true;
  46228. _this._useAmbientInGrayScale = true;
  46229. return _this;
  46230. }
  46231. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  46232. /**
  46233. * Gets the current double sided mode.
  46234. */
  46235. get: function () {
  46236. return this._twoSidedLighting;
  46237. },
  46238. /**
  46239. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46240. */
  46241. set: function (value) {
  46242. if (this._twoSidedLighting === value) {
  46243. return;
  46244. }
  46245. this._twoSidedLighting = value;
  46246. this.backFaceCulling = !value;
  46247. this._markAllSubMeshesAsTexturesDirty();
  46248. },
  46249. enumerable: true,
  46250. configurable: true
  46251. });
  46252. /**
  46253. * Return the active textures of the material.
  46254. */
  46255. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  46256. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46257. if (this.environmentTexture) {
  46258. activeTextures.push(this.environmentTexture);
  46259. }
  46260. if (this.normalTexture) {
  46261. activeTextures.push(this.normalTexture);
  46262. }
  46263. if (this.emissiveTexture) {
  46264. activeTextures.push(this.emissiveTexture);
  46265. }
  46266. if (this.occlusionTexture) {
  46267. activeTextures.push(this.occlusionTexture);
  46268. }
  46269. if (this.lightmapTexture) {
  46270. activeTextures.push(this.lightmapTexture);
  46271. }
  46272. return activeTextures;
  46273. };
  46274. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46275. if (_super.prototype.hasTexture.call(this, texture)) {
  46276. return true;
  46277. }
  46278. if (this.lightmapTexture === texture) {
  46279. return true;
  46280. }
  46281. return false;
  46282. };
  46283. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46284. return "PBRBaseSimpleMaterial";
  46285. };
  46286. __decorate([
  46287. BABYLON.serialize(),
  46288. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46289. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46290. __decorate([
  46291. BABYLON.serialize(),
  46292. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46293. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46294. __decorate([
  46295. BABYLON.serializeAsTexture(),
  46296. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46297. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46298. __decorate([
  46299. BABYLON.serialize(),
  46300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46301. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46302. __decorate([
  46303. BABYLON.serialize(),
  46304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46305. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46306. __decorate([
  46307. BABYLON.serializeAsTexture(),
  46308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46309. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46310. __decorate([
  46311. BABYLON.serializeAsColor3("emissive"),
  46312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46313. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46314. __decorate([
  46315. BABYLON.serializeAsTexture(),
  46316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46317. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46318. __decorate([
  46319. BABYLON.serialize(),
  46320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46321. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46322. __decorate([
  46323. BABYLON.serializeAsTexture(),
  46324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46325. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46326. __decorate([
  46327. BABYLON.serialize(),
  46328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46329. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46330. __decorate([
  46331. BABYLON.serialize()
  46332. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46333. __decorate([
  46334. BABYLON.serializeAsTexture(),
  46335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46336. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46337. __decorate([
  46338. BABYLON.serialize(),
  46339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46340. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46341. return PBRBaseSimpleMaterial;
  46342. }(BABYLON.PBRBaseMaterial));
  46343. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46344. })(BABYLON || (BABYLON = {}));
  46345. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46346. var BABYLON;
  46347. (function (BABYLON) {
  46348. /**
  46349. * The Physically based material of BJS.
  46350. *
  46351. * This offers the main features of a standard PBR material.
  46352. * For more information, please refer to the documentation :
  46353. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46354. */
  46355. var PBRMaterial = /** @class */ (function (_super) {
  46356. __extends(PBRMaterial, _super);
  46357. /**
  46358. * Instantiates a new PBRMaterial instance.
  46359. *
  46360. * @param name The material name
  46361. * @param scene The scene the material will be use in.
  46362. */
  46363. function PBRMaterial(name, scene) {
  46364. var _this = _super.call(this, name, scene) || this;
  46365. /**
  46366. * Intensity of the direct lights e.g. the four lights available in your scene.
  46367. * This impacts both the direct diffuse and specular highlights.
  46368. */
  46369. _this.directIntensity = 1.0;
  46370. /**
  46371. * Intensity of the emissive part of the material.
  46372. * This helps controlling the emissive effect without modifying the emissive color.
  46373. */
  46374. _this.emissiveIntensity = 1.0;
  46375. /**
  46376. * Intensity of the environment e.g. how much the environment will light the object
  46377. * either through harmonics for rough material or through the refelction for shiny ones.
  46378. */
  46379. _this.environmentIntensity = 1.0;
  46380. /**
  46381. * This is a special control allowing the reduction of the specular highlights coming from the
  46382. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46383. */
  46384. _this.specularIntensity = 1.0;
  46385. /**
  46386. * Debug Control allowing disabling the bump map on this material.
  46387. */
  46388. _this.disableBumpMap = false;
  46389. /**
  46390. * AKA Occlusion Texture Intensity in other nomenclature.
  46391. */
  46392. _this.ambientTextureStrength = 1.0;
  46393. /**
  46394. * The color of a material in ambient lighting.
  46395. */
  46396. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46397. /**
  46398. * AKA Diffuse Color in other nomenclature.
  46399. */
  46400. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46401. /**
  46402. * AKA Specular Color in other nomenclature.
  46403. */
  46404. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46405. /**
  46406. * The color reflected from the material.
  46407. */
  46408. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46409. /**
  46410. * The color emitted from the material.
  46411. */
  46412. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46413. /**
  46414. * AKA Glossiness in other nomenclature.
  46415. */
  46416. _this.microSurface = 1.0;
  46417. /**
  46418. * source material index of refraction (IOR)' / 'destination material IOR.
  46419. */
  46420. _this.indexOfRefraction = 0.66;
  46421. /**
  46422. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46423. */
  46424. _this.invertRefractionY = false;
  46425. /**
  46426. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46427. * Materials half opaque for instance using refraction could benefit from this control.
  46428. */
  46429. _this.linkRefractionWithTransparency = false;
  46430. _this.useLightmapAsShadowmap = false;
  46431. /**
  46432. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46433. */
  46434. _this.useAlphaFromAlbedoTexture = false;
  46435. /**
  46436. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46437. */
  46438. _this.forceAlphaTest = false;
  46439. /**
  46440. * Defines the alpha limits in alpha test mode.
  46441. */
  46442. _this.alphaCutOff = 0.4;
  46443. /**
  46444. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  46445. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46446. */
  46447. _this.useSpecularOverAlpha = true;
  46448. /**
  46449. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46450. */
  46451. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46452. /**
  46453. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46454. */
  46455. _this.useRoughnessFromMetallicTextureAlpha = true;
  46456. /**
  46457. * Specifies if the metallic texture contains the roughness information in its green channel.
  46458. */
  46459. _this.useRoughnessFromMetallicTextureGreen = false;
  46460. /**
  46461. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46462. */
  46463. _this.useMetallnessFromMetallicTextureBlue = false;
  46464. /**
  46465. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46466. */
  46467. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46468. /**
  46469. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46470. */
  46471. _this.useAmbientInGrayScale = false;
  46472. /**
  46473. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46474. * The material will try to infer what glossiness each pixel should be.
  46475. */
  46476. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46477. /**
  46478. * BJS is using an harcoded light falloff based on a manually sets up range.
  46479. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46480. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46481. */
  46482. _this.usePhysicalLightFalloff = true;
  46483. /**
  46484. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46485. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46486. */
  46487. _this.useRadianceOverAlpha = true;
  46488. /**
  46489. * Allows using an object space normal map (instead of tangent space).
  46490. */
  46491. _this.useObjectSpaceNormalMap = false;
  46492. /**
  46493. * Allows using the bump map in parallax mode.
  46494. */
  46495. _this.useParallax = false;
  46496. /**
  46497. * Allows using the bump map in parallax occlusion mode.
  46498. */
  46499. _this.useParallaxOcclusion = false;
  46500. /**
  46501. * Controls the scale bias of the parallax mode.
  46502. */
  46503. _this.parallaxScaleBias = 0.05;
  46504. /**
  46505. * If sets to true, disables all the lights affecting the material.
  46506. */
  46507. _this.disableLighting = false;
  46508. /**
  46509. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46510. */
  46511. _this.forceIrradianceInFragment = false;
  46512. /**
  46513. * Number of Simultaneous lights allowed on the material.
  46514. */
  46515. _this.maxSimultaneousLights = 4;
  46516. /**
  46517. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46518. */
  46519. _this.invertNormalMapX = false;
  46520. /**
  46521. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46522. */
  46523. _this.invertNormalMapY = false;
  46524. /**
  46525. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46526. */
  46527. _this.twoSidedLighting = false;
  46528. /**
  46529. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46530. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46531. */
  46532. _this.useAlphaFresnel = false;
  46533. /**
  46534. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46535. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46536. */
  46537. _this.useLinearAlphaFresnel = false;
  46538. /**
  46539. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46540. * And/Or occlude the blended part.
  46541. */
  46542. _this.environmentBRDFTexture = null;
  46543. /**
  46544. * Force normal to face away from face.
  46545. */
  46546. _this.forceNormalForward = false;
  46547. /**
  46548. * Enables specular anti aliasing in the PBR shader.
  46549. * It will both interacts on the Geometry for analytical and IBL lighting.
  46550. * It also prefilter the roughness map based on the bump values.
  46551. */
  46552. _this.enableSpecularAntiAliasing = false;
  46553. /**
  46554. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46555. * makes the reflect vector face the model (under horizon).
  46556. */
  46557. _this.useHorizonOcclusion = true;
  46558. /**
  46559. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46560. * too much the area relying on ambient texture to define their ambient occlusion.
  46561. */
  46562. _this.useRadianceOcclusion = true;
  46563. /**
  46564. * If set to true, no lighting calculations will be applied.
  46565. */
  46566. _this.unlit = false;
  46567. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46568. return _this;
  46569. }
  46570. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  46571. /**
  46572. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46573. */
  46574. get: function () {
  46575. return this._PBRMATERIAL_OPAQUE;
  46576. },
  46577. enumerable: true,
  46578. configurable: true
  46579. });
  46580. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  46581. /**
  46582. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46583. */
  46584. get: function () {
  46585. return this._PBRMATERIAL_ALPHATEST;
  46586. },
  46587. enumerable: true,
  46588. configurable: true
  46589. });
  46590. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  46591. /**
  46592. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46593. */
  46594. get: function () {
  46595. return this._PBRMATERIAL_ALPHABLEND;
  46596. },
  46597. enumerable: true,
  46598. configurable: true
  46599. });
  46600. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46601. /**
  46602. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46603. * They are also discarded below the alpha cutoff threshold to improve performances.
  46604. */
  46605. get: function () {
  46606. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46607. },
  46608. enumerable: true,
  46609. configurable: true
  46610. });
  46611. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46612. /**
  46613. * Gets the image processing configuration used either in this material.
  46614. */
  46615. get: function () {
  46616. return this._imageProcessingConfiguration;
  46617. },
  46618. /**
  46619. * Sets the Default image processing configuration used either in the this material.
  46620. *
  46621. * If sets to null, the scene one is in use.
  46622. */
  46623. set: function (value) {
  46624. this._attachImageProcessingConfiguration(value);
  46625. // Ensure the effect will be rebuilt.
  46626. this._markAllSubMeshesAsTexturesDirty();
  46627. },
  46628. enumerable: true,
  46629. configurable: true
  46630. });
  46631. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46632. /**
  46633. * Gets wether the color curves effect is enabled.
  46634. */
  46635. get: function () {
  46636. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46637. },
  46638. /**
  46639. * Sets wether the color curves effect is enabled.
  46640. */
  46641. set: function (value) {
  46642. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46643. },
  46644. enumerable: true,
  46645. configurable: true
  46646. });
  46647. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46648. /**
  46649. * Gets wether the color grading effect is enabled.
  46650. */
  46651. get: function () {
  46652. return this.imageProcessingConfiguration.colorGradingEnabled;
  46653. },
  46654. /**
  46655. * Gets wether the color grading effect is enabled.
  46656. */
  46657. set: function (value) {
  46658. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46659. },
  46660. enumerable: true,
  46661. configurable: true
  46662. });
  46663. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46664. /**
  46665. * Gets wether tonemapping is enabled or not.
  46666. */
  46667. get: function () {
  46668. return this._imageProcessingConfiguration.toneMappingEnabled;
  46669. },
  46670. /**
  46671. * Sets wether tonemapping is enabled or not
  46672. */
  46673. set: function (value) {
  46674. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46675. },
  46676. enumerable: true,
  46677. configurable: true
  46678. });
  46679. ;
  46680. ;
  46681. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46682. /**
  46683. * The camera exposure used on this material.
  46684. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46685. * This corresponds to a photographic exposure.
  46686. */
  46687. get: function () {
  46688. return this._imageProcessingConfiguration.exposure;
  46689. },
  46690. /**
  46691. * The camera exposure used on this material.
  46692. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46693. * This corresponds to a photographic exposure.
  46694. */
  46695. set: function (value) {
  46696. this._imageProcessingConfiguration.exposure = value;
  46697. },
  46698. enumerable: true,
  46699. configurable: true
  46700. });
  46701. ;
  46702. ;
  46703. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46704. /**
  46705. * Gets The camera contrast used on this material.
  46706. */
  46707. get: function () {
  46708. return this._imageProcessingConfiguration.contrast;
  46709. },
  46710. /**
  46711. * Sets The camera contrast used on this material.
  46712. */
  46713. set: function (value) {
  46714. this._imageProcessingConfiguration.contrast = value;
  46715. },
  46716. enumerable: true,
  46717. configurable: true
  46718. });
  46719. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46720. /**
  46721. * Gets the Color Grading 2D Lookup Texture.
  46722. */
  46723. get: function () {
  46724. return this._imageProcessingConfiguration.colorGradingTexture;
  46725. },
  46726. /**
  46727. * Sets the Color Grading 2D Lookup Texture.
  46728. */
  46729. set: function (value) {
  46730. this._imageProcessingConfiguration.colorGradingTexture = value;
  46731. },
  46732. enumerable: true,
  46733. configurable: true
  46734. });
  46735. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46736. /**
  46737. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46738. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46739. * 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;
  46740. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46741. */
  46742. get: function () {
  46743. return this._imageProcessingConfiguration.colorCurves;
  46744. },
  46745. /**
  46746. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46747. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46748. * 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;
  46749. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46750. */
  46751. set: function (value) {
  46752. this._imageProcessingConfiguration.colorCurves = value;
  46753. },
  46754. enumerable: true,
  46755. configurable: true
  46756. });
  46757. /**
  46758. * Returns the name of this material class.
  46759. */
  46760. PBRMaterial.prototype.getClassName = function () {
  46761. return "PBRMaterial";
  46762. };
  46763. /**
  46764. * Returns an array of the actively used textures.
  46765. * @returns - Array of BaseTextures
  46766. */
  46767. PBRMaterial.prototype.getActiveTextures = function () {
  46768. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46769. if (this._albedoTexture) {
  46770. activeTextures.push(this._albedoTexture);
  46771. }
  46772. if (this._ambientTexture) {
  46773. activeTextures.push(this._ambientTexture);
  46774. }
  46775. if (this._opacityTexture) {
  46776. activeTextures.push(this._opacityTexture);
  46777. }
  46778. if (this._reflectionTexture) {
  46779. activeTextures.push(this._reflectionTexture);
  46780. }
  46781. if (this._emissiveTexture) {
  46782. activeTextures.push(this._emissiveTexture);
  46783. }
  46784. if (this._reflectivityTexture) {
  46785. activeTextures.push(this._reflectivityTexture);
  46786. }
  46787. if (this._metallicTexture) {
  46788. activeTextures.push(this._metallicTexture);
  46789. }
  46790. if (this._microSurfaceTexture) {
  46791. activeTextures.push(this._microSurfaceTexture);
  46792. }
  46793. if (this._bumpTexture) {
  46794. activeTextures.push(this._bumpTexture);
  46795. }
  46796. if (this._lightmapTexture) {
  46797. activeTextures.push(this._lightmapTexture);
  46798. }
  46799. if (this._refractionTexture) {
  46800. activeTextures.push(this._refractionTexture);
  46801. }
  46802. return activeTextures;
  46803. };
  46804. /**
  46805. * Checks to see if a texture is used in the material.
  46806. * @param texture - Base texture to use.
  46807. * @returns - Boolean specifying if a texture is used in the material.
  46808. */
  46809. PBRMaterial.prototype.hasTexture = function (texture) {
  46810. if (_super.prototype.hasTexture.call(this, texture)) {
  46811. return true;
  46812. }
  46813. if (this._albedoTexture === texture) {
  46814. return true;
  46815. }
  46816. if (this._ambientTexture === texture) {
  46817. return true;
  46818. }
  46819. if (this._opacityTexture === texture) {
  46820. return true;
  46821. }
  46822. if (this._reflectionTexture === texture) {
  46823. return true;
  46824. }
  46825. if (this._reflectivityTexture === texture) {
  46826. return true;
  46827. }
  46828. if (this._metallicTexture === texture) {
  46829. return true;
  46830. }
  46831. if (this._microSurfaceTexture === texture) {
  46832. return true;
  46833. }
  46834. if (this._bumpTexture === texture) {
  46835. return true;
  46836. }
  46837. if (this._lightmapTexture === texture) {
  46838. return true;
  46839. }
  46840. if (this._refractionTexture === texture) {
  46841. return true;
  46842. }
  46843. return false;
  46844. };
  46845. /**
  46846. * Makes a duplicate of the current material.
  46847. * @param name - name to use for the new material.
  46848. */
  46849. PBRMaterial.prototype.clone = function (name) {
  46850. var _this = this;
  46851. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46852. clone.id = name;
  46853. clone.name = name;
  46854. return clone;
  46855. };
  46856. /**
  46857. * Serializes this PBR Material.
  46858. * @returns - An object with the serialized material.
  46859. */
  46860. PBRMaterial.prototype.serialize = function () {
  46861. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46862. serializationObject.customType = "BABYLON.PBRMaterial";
  46863. return serializationObject;
  46864. };
  46865. // Statics
  46866. /**
  46867. * Parses a PBR Material from a serialized object.
  46868. * @param source - Serialized object.
  46869. * @param scene - BJS scene instance.
  46870. * @param rootUrl - url for the scene object
  46871. * @returns - PBRMaterial
  46872. */
  46873. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46874. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46875. };
  46876. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46877. /**
  46878. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46879. */
  46880. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46881. /**
  46882. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46883. */
  46884. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46885. /**
  46886. * 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.
  46887. * They are also discarded below the alpha cutoff threshold to improve performances.
  46888. */
  46889. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46890. __decorate([
  46891. BABYLON.serialize(),
  46892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46893. ], PBRMaterial.prototype, "directIntensity", void 0);
  46894. __decorate([
  46895. BABYLON.serialize(),
  46896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46897. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46898. __decorate([
  46899. BABYLON.serialize(),
  46900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46901. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46902. __decorate([
  46903. BABYLON.serialize(),
  46904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46905. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46906. __decorate([
  46907. BABYLON.serialize(),
  46908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46909. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46910. __decorate([
  46911. BABYLON.serializeAsTexture(),
  46912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46913. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46914. __decorate([
  46915. BABYLON.serializeAsTexture(),
  46916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46917. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46918. __decorate([
  46919. BABYLON.serialize(),
  46920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46921. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46922. __decorate([
  46923. BABYLON.serializeAsTexture(),
  46924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46925. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46926. __decorate([
  46927. BABYLON.serializeAsTexture(),
  46928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46929. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46930. __decorate([
  46931. BABYLON.serializeAsTexture(),
  46932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46933. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46934. __decorate([
  46935. BABYLON.serializeAsTexture(),
  46936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46937. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46938. __decorate([
  46939. BABYLON.serializeAsTexture(),
  46940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46941. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46942. __decorate([
  46943. BABYLON.serialize(),
  46944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46945. ], PBRMaterial.prototype, "metallic", void 0);
  46946. __decorate([
  46947. BABYLON.serialize(),
  46948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46949. ], PBRMaterial.prototype, "roughness", void 0);
  46950. __decorate([
  46951. BABYLON.serializeAsTexture(),
  46952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46953. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46954. __decorate([
  46955. BABYLON.serializeAsTexture(),
  46956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46957. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46958. __decorate([
  46959. BABYLON.serializeAsTexture(),
  46960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46961. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46962. __decorate([
  46963. BABYLON.serializeAsTexture(),
  46964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46965. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46966. __decorate([
  46967. BABYLON.serializeAsColor3("ambient"),
  46968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46969. ], PBRMaterial.prototype, "ambientColor", void 0);
  46970. __decorate([
  46971. BABYLON.serializeAsColor3("albedo"),
  46972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46973. ], PBRMaterial.prototype, "albedoColor", void 0);
  46974. __decorate([
  46975. BABYLON.serializeAsColor3("reflectivity"),
  46976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46977. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46978. __decorate([
  46979. BABYLON.serializeAsColor3("reflection"),
  46980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46981. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46982. __decorate([
  46983. BABYLON.serializeAsColor3("emissive"),
  46984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46985. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46986. __decorate([
  46987. BABYLON.serialize(),
  46988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46989. ], PBRMaterial.prototype, "microSurface", void 0);
  46990. __decorate([
  46991. BABYLON.serialize(),
  46992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46993. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46994. __decorate([
  46995. BABYLON.serialize(),
  46996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46997. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46998. __decorate([
  46999. BABYLON.serialize(),
  47000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47001. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  47002. __decorate([
  47003. BABYLON.serialize(),
  47004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47005. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  47006. __decorate([
  47007. BABYLON.serialize(),
  47008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47009. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  47010. __decorate([
  47011. BABYLON.serialize(),
  47012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47013. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  47014. __decorate([
  47015. BABYLON.serialize(),
  47016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47017. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  47018. __decorate([
  47019. BABYLON.serialize(),
  47020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47021. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  47022. __decorate([
  47023. BABYLON.serialize(),
  47024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47025. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  47026. __decorate([
  47027. BABYLON.serialize(),
  47028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47029. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  47030. __decorate([
  47031. BABYLON.serialize(),
  47032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47033. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  47034. __decorate([
  47035. BABYLON.serialize(),
  47036. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47037. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  47038. __decorate([
  47039. BABYLON.serialize(),
  47040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47041. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  47042. __decorate([
  47043. BABYLON.serialize(),
  47044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47045. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  47046. __decorate([
  47047. BABYLON.serialize(),
  47048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47049. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  47050. __decorate([
  47051. BABYLON.serialize(),
  47052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47053. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  47054. __decorate([
  47055. BABYLON.serialize(),
  47056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47057. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  47058. __decorate([
  47059. BABYLON.serialize(),
  47060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47061. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  47062. __decorate([
  47063. BABYLON.serialize(),
  47064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47065. ], PBRMaterial.prototype, "useParallax", void 0);
  47066. __decorate([
  47067. BABYLON.serialize(),
  47068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47069. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  47070. __decorate([
  47071. BABYLON.serialize(),
  47072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47073. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  47074. __decorate([
  47075. BABYLON.serialize(),
  47076. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47077. ], PBRMaterial.prototype, "disableLighting", void 0);
  47078. __decorate([
  47079. BABYLON.serialize(),
  47080. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47081. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  47082. __decorate([
  47083. BABYLON.serialize(),
  47084. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47085. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  47086. __decorate([
  47087. BABYLON.serialize(),
  47088. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47089. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  47090. __decorate([
  47091. BABYLON.serialize(),
  47092. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47093. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  47094. __decorate([
  47095. BABYLON.serialize(),
  47096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47097. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  47098. __decorate([
  47099. BABYLON.serialize(),
  47100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47101. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  47102. __decorate([
  47103. BABYLON.serialize(),
  47104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47105. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  47106. __decorate([
  47107. BABYLON.serializeAsTexture(),
  47108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47109. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  47110. __decorate([
  47111. BABYLON.serialize(),
  47112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47113. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  47114. __decorate([
  47115. BABYLON.serialize(),
  47116. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47117. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  47118. __decorate([
  47119. BABYLON.serialize(),
  47120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47121. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  47122. __decorate([
  47123. BABYLON.serialize(),
  47124. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47125. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  47126. __decorate([
  47127. BABYLON.serialize(),
  47128. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  47129. ], PBRMaterial.prototype, "unlit", void 0);
  47130. return PBRMaterial;
  47131. }(BABYLON.PBRBaseMaterial));
  47132. BABYLON.PBRMaterial = PBRMaterial;
  47133. })(BABYLON || (BABYLON = {}));
  47134. //# sourceMappingURL=babylon.pbrMaterial.js.map
  47135. var BABYLON;
  47136. (function (BABYLON) {
  47137. /**
  47138. * The PBR material of BJS following the metal roughness convention.
  47139. *
  47140. * This fits to the PBR convention in the GLTF definition:
  47141. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  47142. */
  47143. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  47144. __extends(PBRMetallicRoughnessMaterial, _super);
  47145. /**
  47146. * Instantiates a new PBRMetalRoughnessMaterial instance.
  47147. *
  47148. * @param name The material name
  47149. * @param scene The scene the material will be use in.
  47150. */
  47151. function PBRMetallicRoughnessMaterial(name, scene) {
  47152. var _this = _super.call(this, name, scene) || this;
  47153. _this._useRoughnessFromMetallicTextureAlpha = false;
  47154. _this._useRoughnessFromMetallicTextureGreen = true;
  47155. _this._useMetallnessFromMetallicTextureBlue = true;
  47156. _this.metallic = 1.0;
  47157. _this.roughness = 1.0;
  47158. return _this;
  47159. }
  47160. /**
  47161. * Return the currrent class name of the material.
  47162. */
  47163. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  47164. return "PBRMetallicRoughnessMaterial";
  47165. };
  47166. /**
  47167. * Return the active textures of the material.
  47168. */
  47169. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  47170. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47171. if (this.baseTexture) {
  47172. activeTextures.push(this.baseTexture);
  47173. }
  47174. if (this.metallicRoughnessTexture) {
  47175. activeTextures.push(this.metallicRoughnessTexture);
  47176. }
  47177. return activeTextures;
  47178. };
  47179. /**
  47180. * Checks to see if a texture is used in the material.
  47181. * @param texture - Base texture to use.
  47182. * @returns - Boolean specifying if a texture is used in the material.
  47183. */
  47184. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  47185. if (_super.prototype.hasTexture.call(this, texture)) {
  47186. return true;
  47187. }
  47188. if (this.baseTexture === texture) {
  47189. return true;
  47190. }
  47191. if (this.metallicRoughnessTexture === texture) {
  47192. return true;
  47193. }
  47194. return false;
  47195. };
  47196. /**
  47197. * Makes a duplicate of the current material.
  47198. * @param name - name to use for the new material.
  47199. */
  47200. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  47201. var _this = this;
  47202. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  47203. clone.id = name;
  47204. clone.name = name;
  47205. return clone;
  47206. };
  47207. /**
  47208. * Serialize the material to a parsable JSON object.
  47209. */
  47210. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  47211. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47212. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  47213. return serializationObject;
  47214. };
  47215. /**
  47216. * Parses a JSON object correponding to the serialize function.
  47217. */
  47218. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  47219. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  47220. };
  47221. __decorate([
  47222. BABYLON.serializeAsColor3(),
  47223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47224. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  47225. __decorate([
  47226. BABYLON.serializeAsTexture(),
  47227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47228. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  47229. __decorate([
  47230. BABYLON.serialize(),
  47231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47232. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  47233. __decorate([
  47234. BABYLON.serialize(),
  47235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47236. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  47237. __decorate([
  47238. BABYLON.serializeAsTexture(),
  47239. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  47240. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  47241. return PBRMetallicRoughnessMaterial;
  47242. }(BABYLON.PBRBaseSimpleMaterial));
  47243. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  47244. })(BABYLON || (BABYLON = {}));
  47245. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  47246. var BABYLON;
  47247. (function (BABYLON) {
  47248. /**
  47249. * The PBR material of BJS following the specular glossiness convention.
  47250. *
  47251. * This fits to the PBR convention in the GLTF definition:
  47252. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  47253. */
  47254. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  47255. __extends(PBRSpecularGlossinessMaterial, _super);
  47256. /**
  47257. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  47258. *
  47259. * @param name The material name
  47260. * @param scene The scene the material will be use in.
  47261. */
  47262. function PBRSpecularGlossinessMaterial(name, scene) {
  47263. var _this = _super.call(this, name, scene) || this;
  47264. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  47265. return _this;
  47266. }
  47267. /**
  47268. * Return the currrent class name of the material.
  47269. */
  47270. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47271. return "PBRSpecularGlossinessMaterial";
  47272. };
  47273. /**
  47274. * Return the active textures of the material.
  47275. */
  47276. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  47277. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47278. if (this.diffuseTexture) {
  47279. activeTextures.push(this.diffuseTexture);
  47280. }
  47281. if (this.specularGlossinessTexture) {
  47282. activeTextures.push(this.specularGlossinessTexture);
  47283. }
  47284. return activeTextures;
  47285. };
  47286. /**
  47287. * Checks to see if a texture is used in the material.
  47288. * @param texture - Base texture to use.
  47289. * @returns - Boolean specifying if a texture is used in the material.
  47290. */
  47291. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47292. if (_super.prototype.hasTexture.call(this, texture)) {
  47293. return true;
  47294. }
  47295. if (this.diffuseTexture === texture) {
  47296. return true;
  47297. }
  47298. if (this.specularGlossinessTexture === texture) {
  47299. return true;
  47300. }
  47301. return false;
  47302. };
  47303. /**
  47304. * Makes a duplicate of the current material.
  47305. * @param name - name to use for the new material.
  47306. */
  47307. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47308. var _this = this;
  47309. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47310. clone.id = name;
  47311. clone.name = name;
  47312. return clone;
  47313. };
  47314. /**
  47315. * Serialize the material to a parsable JSON object.
  47316. */
  47317. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47318. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47319. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47320. return serializationObject;
  47321. };
  47322. /**
  47323. * Parses a JSON object correponding to the serialize function.
  47324. */
  47325. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47326. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47327. };
  47328. __decorate([
  47329. BABYLON.serializeAsColor3("diffuse"),
  47330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47331. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47332. __decorate([
  47333. BABYLON.serializeAsTexture(),
  47334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47335. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47336. __decorate([
  47337. BABYLON.serializeAsColor3("specular"),
  47338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47339. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47340. __decorate([
  47341. BABYLON.serialize(),
  47342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47343. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47344. __decorate([
  47345. BABYLON.serializeAsTexture(),
  47346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47347. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47348. return PBRSpecularGlossinessMaterial;
  47349. }(BABYLON.PBRBaseSimpleMaterial));
  47350. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47351. })(BABYLON || (BABYLON = {}));
  47352. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47353. var BABYLON;
  47354. (function (BABYLON) {
  47355. BABYLON.CameraInputTypes = {};
  47356. var CameraInputsManager = /** @class */ (function () {
  47357. function CameraInputsManager(camera) {
  47358. this.attached = {};
  47359. this.camera = camera;
  47360. this.checkInputs = function () { };
  47361. }
  47362. /**
  47363. * Add an input method to a camera.
  47364. * builtin inputs example: camera.inputs.addGamepad();
  47365. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  47366. * @param input camera input method
  47367. */
  47368. CameraInputsManager.prototype.add = function (input) {
  47369. var type = input.getSimpleName();
  47370. if (this.attached[type]) {
  47371. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47372. return;
  47373. }
  47374. this.attached[type] = input;
  47375. input.camera = this.camera;
  47376. //for checkInputs, we are dynamically creating a function
  47377. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47378. if (input.checkInputs) {
  47379. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47380. }
  47381. if (this.attachedElement) {
  47382. input.attachControl(this.attachedElement);
  47383. }
  47384. };
  47385. /**
  47386. * Remove a specific input method from a camera
  47387. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47388. * @param inputToRemove camera input method
  47389. */
  47390. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47391. for (var cam in this.attached) {
  47392. var input = this.attached[cam];
  47393. if (input === inputToRemove) {
  47394. input.detachControl(this.attachedElement);
  47395. input.camera = null;
  47396. delete this.attached[cam];
  47397. this.rebuildInputCheck();
  47398. }
  47399. }
  47400. };
  47401. CameraInputsManager.prototype.removeByType = function (inputType) {
  47402. for (var cam in this.attached) {
  47403. var input = this.attached[cam];
  47404. if (input.getClassName() === inputType) {
  47405. input.detachControl(this.attachedElement);
  47406. input.camera = null;
  47407. delete this.attached[cam];
  47408. this.rebuildInputCheck();
  47409. }
  47410. }
  47411. };
  47412. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47413. var current = this.checkInputs;
  47414. return function () {
  47415. current();
  47416. fn();
  47417. };
  47418. };
  47419. CameraInputsManager.prototype.attachInput = function (input) {
  47420. if (this.attachedElement) {
  47421. input.attachControl(this.attachedElement, this.noPreventDefault);
  47422. }
  47423. };
  47424. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47425. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47426. if (this.attachedElement) {
  47427. return;
  47428. }
  47429. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47430. this.attachedElement = element;
  47431. this.noPreventDefault = noPreventDefault;
  47432. for (var cam in this.attached) {
  47433. this.attached[cam].attachControl(element, noPreventDefault);
  47434. }
  47435. };
  47436. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47437. if (disconnect === void 0) { disconnect = false; }
  47438. if (this.attachedElement !== element) {
  47439. return;
  47440. }
  47441. for (var cam in this.attached) {
  47442. this.attached[cam].detachControl(element);
  47443. if (disconnect) {
  47444. this.attached[cam].camera = null;
  47445. }
  47446. }
  47447. this.attachedElement = null;
  47448. };
  47449. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47450. this.checkInputs = function () { };
  47451. for (var cam in this.attached) {
  47452. var input = this.attached[cam];
  47453. if (input.checkInputs) {
  47454. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47455. }
  47456. }
  47457. };
  47458. /**
  47459. * Remove all attached input methods from a camera
  47460. */
  47461. CameraInputsManager.prototype.clear = function () {
  47462. if (this.attachedElement) {
  47463. this.detachElement(this.attachedElement, true);
  47464. }
  47465. this.attached = {};
  47466. this.attachedElement = null;
  47467. this.checkInputs = function () { };
  47468. };
  47469. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47470. var inputs = {};
  47471. for (var cam in this.attached) {
  47472. var input = this.attached[cam];
  47473. var res = BABYLON.SerializationHelper.Serialize(input);
  47474. inputs[input.getClassName()] = res;
  47475. }
  47476. serializedCamera.inputsmgr = inputs;
  47477. };
  47478. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47479. var parsedInputs = parsedCamera.inputsmgr;
  47480. if (parsedInputs) {
  47481. this.clear();
  47482. for (var n in parsedInputs) {
  47483. var construct = BABYLON.CameraInputTypes[n];
  47484. if (construct) {
  47485. var parsedinput = parsedInputs[n];
  47486. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47487. this.add(input);
  47488. }
  47489. }
  47490. }
  47491. else {
  47492. //2016-03-08 this part is for managing backward compatibility
  47493. for (var n in this.attached) {
  47494. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47495. if (construct) {
  47496. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47497. this.remove(this.attached[n]);
  47498. this.add(input);
  47499. }
  47500. }
  47501. }
  47502. };
  47503. return CameraInputsManager;
  47504. }());
  47505. BABYLON.CameraInputsManager = CameraInputsManager;
  47506. })(BABYLON || (BABYLON = {}));
  47507. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47508. var BABYLON;
  47509. (function (BABYLON) {
  47510. var TargetCamera = /** @class */ (function (_super) {
  47511. __extends(TargetCamera, _super);
  47512. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47513. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47514. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47515. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47516. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47517. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47518. _this.speed = 2.0;
  47519. _this.noRotationConstraint = false;
  47520. _this.lockedTarget = null;
  47521. _this._currentTarget = BABYLON.Vector3.Zero();
  47522. _this._viewMatrix = BABYLON.Matrix.Zero();
  47523. _this._camMatrix = BABYLON.Matrix.Zero();
  47524. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47525. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47526. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47527. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  47528. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47529. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47530. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47531. return _this;
  47532. }
  47533. TargetCamera.prototype.getFrontPosition = function (distance) {
  47534. this.getWorldMatrix();
  47535. var direction = this.getTarget().subtract(this.position);
  47536. direction.normalize();
  47537. direction.scaleInPlace(distance);
  47538. return this.globalPosition.add(direction);
  47539. };
  47540. TargetCamera.prototype._getLockedTargetPosition = function () {
  47541. if (!this.lockedTarget) {
  47542. return null;
  47543. }
  47544. if (this.lockedTarget.absolutePosition) {
  47545. this.lockedTarget.computeWorldMatrix();
  47546. }
  47547. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47548. };
  47549. TargetCamera.prototype.storeState = function () {
  47550. this._storedPosition = this.position.clone();
  47551. this._storedRotation = this.rotation.clone();
  47552. if (this.rotationQuaternion) {
  47553. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47554. }
  47555. return _super.prototype.storeState.call(this);
  47556. };
  47557. /**
  47558. * Restored camera state. You must call storeState() first
  47559. */
  47560. TargetCamera.prototype._restoreStateValues = function () {
  47561. if (!_super.prototype._restoreStateValues.call(this)) {
  47562. return false;
  47563. }
  47564. this.position = this._storedPosition.clone();
  47565. this.rotation = this._storedRotation.clone();
  47566. if (this.rotationQuaternion) {
  47567. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47568. }
  47569. this.cameraDirection.copyFromFloats(0, 0, 0);
  47570. this.cameraRotation.copyFromFloats(0, 0);
  47571. return true;
  47572. };
  47573. // Cache
  47574. TargetCamera.prototype._initCache = function () {
  47575. _super.prototype._initCache.call(this);
  47576. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47577. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47578. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47579. };
  47580. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47581. if (!ignoreParentClass) {
  47582. _super.prototype._updateCache.call(this);
  47583. }
  47584. var lockedTargetPosition = this._getLockedTargetPosition();
  47585. if (!lockedTargetPosition) {
  47586. this._cache.lockedTarget = null;
  47587. }
  47588. else {
  47589. if (!this._cache.lockedTarget) {
  47590. this._cache.lockedTarget = lockedTargetPosition.clone();
  47591. }
  47592. else {
  47593. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47594. }
  47595. }
  47596. this._cache.rotation.copyFrom(this.rotation);
  47597. if (this.rotationQuaternion)
  47598. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47599. };
  47600. // Synchronized
  47601. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47602. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47603. return false;
  47604. }
  47605. var lockedTargetPosition = this._getLockedTargetPosition();
  47606. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47607. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47608. };
  47609. // Methods
  47610. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47611. var engine = this.getEngine();
  47612. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47613. };
  47614. // Target
  47615. TargetCamera.prototype.setTarget = function (target) {
  47616. this.upVector.normalize();
  47617. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47618. this._camMatrix.invert();
  47619. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47620. var vDir = target.subtract(this.position);
  47621. if (vDir.x >= 0.0) {
  47622. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47623. }
  47624. else {
  47625. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47626. }
  47627. this.rotation.z = 0;
  47628. if (isNaN(this.rotation.x)) {
  47629. this.rotation.x = 0;
  47630. }
  47631. if (isNaN(this.rotation.y)) {
  47632. this.rotation.y = 0;
  47633. }
  47634. if (isNaN(this.rotation.z)) {
  47635. this.rotation.z = 0;
  47636. }
  47637. if (this.rotationQuaternion) {
  47638. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47639. }
  47640. };
  47641. /**
  47642. * Return the current target position of the camera. This value is expressed in local space.
  47643. */
  47644. TargetCamera.prototype.getTarget = function () {
  47645. return this._currentTarget;
  47646. };
  47647. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47648. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47649. };
  47650. TargetCamera.prototype._updatePosition = function () {
  47651. if (this.parent) {
  47652. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47653. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47654. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47655. return;
  47656. }
  47657. this.position.addInPlace(this.cameraDirection);
  47658. };
  47659. TargetCamera.prototype._checkInputs = function () {
  47660. var needToMove = this._decideIfNeedsToMove();
  47661. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47662. // Move
  47663. if (needToMove) {
  47664. this._updatePosition();
  47665. }
  47666. // Rotate
  47667. if (needToRotate) {
  47668. this.rotation.x += this.cameraRotation.x;
  47669. this.rotation.y += this.cameraRotation.y;
  47670. //rotate, if quaternion is set and rotation was used
  47671. if (this.rotationQuaternion) {
  47672. var len = this.rotation.lengthSquared();
  47673. if (len) {
  47674. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47675. }
  47676. }
  47677. if (!this.noRotationConstraint) {
  47678. var limit = (Math.PI / 2) * 0.95;
  47679. if (this.rotation.x > limit)
  47680. this.rotation.x = limit;
  47681. if (this.rotation.x < -limit)
  47682. this.rotation.x = -limit;
  47683. }
  47684. }
  47685. // Inertia
  47686. if (needToMove) {
  47687. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47688. this.cameraDirection.x = 0;
  47689. }
  47690. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47691. this.cameraDirection.y = 0;
  47692. }
  47693. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47694. this.cameraDirection.z = 0;
  47695. }
  47696. this.cameraDirection.scaleInPlace(this.inertia);
  47697. }
  47698. if (needToRotate) {
  47699. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47700. this.cameraRotation.x = 0;
  47701. }
  47702. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47703. this.cameraRotation.y = 0;
  47704. }
  47705. this.cameraRotation.scaleInPlace(this.inertia);
  47706. }
  47707. _super.prototype._checkInputs.call(this);
  47708. };
  47709. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47710. if (this.rotationQuaternion) {
  47711. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47712. }
  47713. else {
  47714. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47715. }
  47716. //update the up vector!
  47717. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47718. };
  47719. TargetCamera.prototype._getViewMatrix = function () {
  47720. if (this.lockedTarget) {
  47721. this.setTarget(this._getLockedTargetPosition());
  47722. }
  47723. // Compute
  47724. this._updateCameraRotationMatrix();
  47725. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47726. // Computing target and final matrix
  47727. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47728. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47729. return this._viewMatrix;
  47730. };
  47731. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47732. if (this.parent) {
  47733. var parentWorldMatrix = this.parent.getWorldMatrix();
  47734. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47735. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47736. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47737. this._markSyncedWithParent();
  47738. }
  47739. else {
  47740. this._globalPosition.copyFrom(this.position);
  47741. this._globalCurrentTarget.copyFrom(target);
  47742. this._globalCurrentUpVector.copyFrom(up);
  47743. }
  47744. if (this.getScene().useRightHandedSystem) {
  47745. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47746. }
  47747. else {
  47748. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47749. }
  47750. };
  47751. /**
  47752. * @override
  47753. * Override Camera.createRigCamera
  47754. */
  47755. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47756. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47757. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47758. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47759. if (!this.rotationQuaternion) {
  47760. this.rotationQuaternion = new BABYLON.Quaternion();
  47761. }
  47762. rigCamera._cameraRigParams = {};
  47763. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47764. }
  47765. return rigCamera;
  47766. }
  47767. return null;
  47768. };
  47769. /**
  47770. * @override
  47771. * Override Camera._updateRigCameras
  47772. */
  47773. TargetCamera.prototype._updateRigCameras = function () {
  47774. var camLeft = this._rigCameras[0];
  47775. var camRight = this._rigCameras[1];
  47776. switch (this.cameraRigMode) {
  47777. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47778. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47779. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47780. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47781. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47782. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47783. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47784. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47785. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47786. camLeft.setTarget(this.getTarget());
  47787. camRight.setTarget(this.getTarget());
  47788. break;
  47789. case BABYLON.Camera.RIG_MODE_VR:
  47790. if (camLeft.rotationQuaternion) {
  47791. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47792. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47793. }
  47794. else {
  47795. camLeft.rotation.copyFrom(this.rotation);
  47796. camRight.rotation.copyFrom(this.rotation);
  47797. }
  47798. camLeft.position.copyFrom(this.position);
  47799. camRight.position.copyFrom(this.position);
  47800. break;
  47801. }
  47802. _super.prototype._updateRigCameras.call(this);
  47803. };
  47804. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47805. if (!this._rigCamTransformMatrix) {
  47806. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47807. }
  47808. var target = this.getTarget();
  47809. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47810. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47811. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47812. };
  47813. TargetCamera.prototype.getClassName = function () {
  47814. return "TargetCamera";
  47815. };
  47816. __decorate([
  47817. BABYLON.serializeAsVector3()
  47818. ], TargetCamera.prototype, "rotation", void 0);
  47819. __decorate([
  47820. BABYLON.serialize()
  47821. ], TargetCamera.prototype, "speed", void 0);
  47822. __decorate([
  47823. BABYLON.serializeAsMeshReference("lockedTargetId")
  47824. ], TargetCamera.prototype, "lockedTarget", void 0);
  47825. return TargetCamera;
  47826. }(BABYLON.Camera));
  47827. BABYLON.TargetCamera = TargetCamera;
  47828. })(BABYLON || (BABYLON = {}));
  47829. //# sourceMappingURL=babylon.targetCamera.js.map
  47830. var BABYLON;
  47831. (function (BABYLON) {
  47832. var FreeCameraMouseInput = /** @class */ (function () {
  47833. function FreeCameraMouseInput(touchEnabled) {
  47834. if (touchEnabled === void 0) { touchEnabled = true; }
  47835. this.touchEnabled = touchEnabled;
  47836. this.buttons = [0, 1, 2];
  47837. this.angularSensibility = 2000.0;
  47838. this.previousPosition = null;
  47839. }
  47840. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47841. var _this = this;
  47842. var engine = this.camera.getEngine();
  47843. if (!this._pointerInput) {
  47844. this._pointerInput = function (p, s) {
  47845. var evt = p.event;
  47846. if (engine.isInVRExclusivePointerMode) {
  47847. return;
  47848. }
  47849. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47850. return;
  47851. }
  47852. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47853. return;
  47854. }
  47855. var srcElement = (evt.srcElement || evt.target);
  47856. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47857. try {
  47858. srcElement.setPointerCapture(evt.pointerId);
  47859. }
  47860. catch (e) {
  47861. //Nothing to do with the error. Execution will continue.
  47862. }
  47863. _this.previousPosition = {
  47864. x: evt.clientX,
  47865. y: evt.clientY
  47866. };
  47867. if (!noPreventDefault) {
  47868. evt.preventDefault();
  47869. element.focus();
  47870. }
  47871. }
  47872. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47873. try {
  47874. srcElement.releasePointerCapture(evt.pointerId);
  47875. }
  47876. catch (e) {
  47877. //Nothing to do with the error.
  47878. }
  47879. _this.previousPosition = null;
  47880. if (!noPreventDefault) {
  47881. evt.preventDefault();
  47882. }
  47883. }
  47884. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47885. if (!_this.previousPosition || engine.isPointerLock) {
  47886. return;
  47887. }
  47888. var offsetX = evt.clientX - _this.previousPosition.x;
  47889. if (_this.camera.getScene().useRightHandedSystem)
  47890. offsetX *= -1;
  47891. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47892. offsetX *= -1;
  47893. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47894. var offsetY = evt.clientY - _this.previousPosition.y;
  47895. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47896. _this.previousPosition = {
  47897. x: evt.clientX,
  47898. y: evt.clientY
  47899. };
  47900. if (!noPreventDefault) {
  47901. evt.preventDefault();
  47902. }
  47903. }
  47904. };
  47905. }
  47906. this._onMouseMove = function (evt) {
  47907. if (!engine.isPointerLock) {
  47908. return;
  47909. }
  47910. if (engine.isInVRExclusivePointerMode) {
  47911. return;
  47912. }
  47913. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47914. if (_this.camera.getScene().useRightHandedSystem)
  47915. offsetX *= -1;
  47916. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47917. offsetX *= -1;
  47918. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47919. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47920. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47921. _this.previousPosition = null;
  47922. if (!noPreventDefault) {
  47923. evt.preventDefault();
  47924. }
  47925. };
  47926. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47927. element.addEventListener("mousemove", this._onMouseMove, false);
  47928. };
  47929. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47930. if (this._observer && element) {
  47931. this.camera.getScene().onPointerObservable.remove(this._observer);
  47932. if (this._onMouseMove) {
  47933. element.removeEventListener("mousemove", this._onMouseMove);
  47934. }
  47935. this._observer = null;
  47936. this._onMouseMove = null;
  47937. this.previousPosition = null;
  47938. }
  47939. };
  47940. FreeCameraMouseInput.prototype.getClassName = function () {
  47941. return "FreeCameraMouseInput";
  47942. };
  47943. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47944. return "mouse";
  47945. };
  47946. __decorate([
  47947. BABYLON.serialize()
  47948. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47949. __decorate([
  47950. BABYLON.serialize()
  47951. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47952. return FreeCameraMouseInput;
  47953. }());
  47954. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47955. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47956. })(BABYLON || (BABYLON = {}));
  47957. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47958. var BABYLON;
  47959. (function (BABYLON) {
  47960. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47961. function FreeCameraKeyboardMoveInput() {
  47962. this._keys = new Array();
  47963. this.keysUp = [38];
  47964. this.keysDown = [40];
  47965. this.keysLeft = [37];
  47966. this.keysRight = [39];
  47967. }
  47968. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47969. var _this = this;
  47970. if (this._onCanvasBlurObserver) {
  47971. return;
  47972. }
  47973. this._scene = this.camera.getScene();
  47974. this._engine = this._scene.getEngine();
  47975. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47976. _this._keys = [];
  47977. });
  47978. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47979. var evt = info.event;
  47980. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47981. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47982. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47983. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47984. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47985. var index = _this._keys.indexOf(evt.keyCode);
  47986. if (index === -1) {
  47987. _this._keys.push(evt.keyCode);
  47988. }
  47989. if (!noPreventDefault) {
  47990. evt.preventDefault();
  47991. }
  47992. }
  47993. }
  47994. else {
  47995. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47996. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47997. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47998. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47999. var index = _this._keys.indexOf(evt.keyCode);
  48000. if (index >= 0) {
  48001. _this._keys.splice(index, 1);
  48002. }
  48003. if (!noPreventDefault) {
  48004. evt.preventDefault();
  48005. }
  48006. }
  48007. }
  48008. });
  48009. };
  48010. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48011. if (this._scene) {
  48012. if (this._onKeyboardObserver) {
  48013. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48014. }
  48015. if (this._onCanvasBlurObserver) {
  48016. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48017. }
  48018. this._onKeyboardObserver = null;
  48019. this._onCanvasBlurObserver = null;
  48020. }
  48021. this._keys = [];
  48022. };
  48023. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48024. if (this._onKeyboardObserver) {
  48025. var camera = this.camera;
  48026. // Keyboard
  48027. for (var index = 0; index < this._keys.length; index++) {
  48028. var keyCode = this._keys[index];
  48029. var speed = camera._computeLocalCameraSpeed();
  48030. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48031. camera._localDirection.copyFromFloats(-speed, 0, 0);
  48032. }
  48033. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48034. camera._localDirection.copyFromFloats(0, 0, speed);
  48035. }
  48036. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48037. camera._localDirection.copyFromFloats(speed, 0, 0);
  48038. }
  48039. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48040. camera._localDirection.copyFromFloats(0, 0, -speed);
  48041. }
  48042. if (camera.getScene().useRightHandedSystem) {
  48043. camera._localDirection.z *= -1;
  48044. }
  48045. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  48046. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  48047. camera.cameraDirection.addInPlace(camera._transformedDirection);
  48048. }
  48049. }
  48050. };
  48051. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  48052. return "FreeCameraKeyboardMoveInput";
  48053. };
  48054. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  48055. this._keys = [];
  48056. };
  48057. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48058. return "keyboard";
  48059. };
  48060. __decorate([
  48061. BABYLON.serialize()
  48062. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48063. __decorate([
  48064. BABYLON.serialize()
  48065. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48066. __decorate([
  48067. BABYLON.serialize()
  48068. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48069. __decorate([
  48070. BABYLON.serialize()
  48071. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48072. return FreeCameraKeyboardMoveInput;
  48073. }());
  48074. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  48075. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  48076. })(BABYLON || (BABYLON = {}));
  48077. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  48078. var BABYLON;
  48079. (function (BABYLON) {
  48080. var FreeCameraInputsManager = /** @class */ (function (_super) {
  48081. __extends(FreeCameraInputsManager, _super);
  48082. function FreeCameraInputsManager(camera) {
  48083. return _super.call(this, camera) || this;
  48084. }
  48085. FreeCameraInputsManager.prototype.addKeyboard = function () {
  48086. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  48087. return this;
  48088. };
  48089. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  48090. if (touchEnabled === void 0) { touchEnabled = true; }
  48091. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  48092. return this;
  48093. };
  48094. FreeCameraInputsManager.prototype.addGamepad = function () {
  48095. this.add(new BABYLON.FreeCameraGamepadInput());
  48096. return this;
  48097. };
  48098. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  48099. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  48100. return this;
  48101. };
  48102. FreeCameraInputsManager.prototype.addTouch = function () {
  48103. this.add(new BABYLON.FreeCameraTouchInput());
  48104. return this;
  48105. };
  48106. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  48107. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  48108. return this;
  48109. };
  48110. return FreeCameraInputsManager;
  48111. }(BABYLON.CameraInputsManager));
  48112. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  48113. })(BABYLON || (BABYLON = {}));
  48114. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  48115. var BABYLON;
  48116. (function (BABYLON) {
  48117. var FreeCamera = /** @class */ (function (_super) {
  48118. __extends(FreeCamera, _super);
  48119. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  48120. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48121. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48122. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  48123. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  48124. _this.checkCollisions = false;
  48125. _this.applyGravity = false;
  48126. _this._needMoveForGravity = false;
  48127. _this._oldPosition = BABYLON.Vector3.Zero();
  48128. _this._diffPosition = BABYLON.Vector3.Zero();
  48129. _this._newPosition = BABYLON.Vector3.Zero();
  48130. // Collisions
  48131. _this._collisionMask = -1;
  48132. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48133. if (collidedMesh === void 0) { collidedMesh = null; }
  48134. //TODO move this to the collision coordinator!
  48135. if (_this.getScene().workerCollisions)
  48136. newPosition.multiplyInPlace(_this._collider._radius);
  48137. var updatePosition = function (newPos) {
  48138. _this._newPosition.copyFrom(newPos);
  48139. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  48140. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  48141. _this.position.addInPlace(_this._diffPosition);
  48142. if (_this.onCollide && collidedMesh) {
  48143. _this.onCollide(collidedMesh);
  48144. }
  48145. }
  48146. };
  48147. updatePosition(newPosition);
  48148. };
  48149. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  48150. _this.inputs.addKeyboard().addMouse();
  48151. return _this;
  48152. }
  48153. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  48154. //-- begin properties for backward compatibility for inputs
  48155. /**
  48156. * Gets the input sensibility for a mouse input. (default is 2000.0)
  48157. * Higher values reduce sensitivity.
  48158. */
  48159. get: function () {
  48160. var mouse = this.inputs.attached["mouse"];
  48161. if (mouse)
  48162. return mouse.angularSensibility;
  48163. return 0;
  48164. },
  48165. /**
  48166. * Sets the input sensibility for a mouse input. (default is 2000.0)
  48167. * Higher values reduce sensitivity.
  48168. */
  48169. set: function (value) {
  48170. var mouse = this.inputs.attached["mouse"];
  48171. if (mouse)
  48172. mouse.angularSensibility = value;
  48173. },
  48174. enumerable: true,
  48175. configurable: true
  48176. });
  48177. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  48178. get: function () {
  48179. var keyboard = this.inputs.attached["keyboard"];
  48180. if (keyboard)
  48181. return keyboard.keysUp;
  48182. return [];
  48183. },
  48184. set: function (value) {
  48185. var keyboard = this.inputs.attached["keyboard"];
  48186. if (keyboard)
  48187. keyboard.keysUp = value;
  48188. },
  48189. enumerable: true,
  48190. configurable: true
  48191. });
  48192. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  48193. get: function () {
  48194. var keyboard = this.inputs.attached["keyboard"];
  48195. if (keyboard)
  48196. return keyboard.keysDown;
  48197. return [];
  48198. },
  48199. set: function (value) {
  48200. var keyboard = this.inputs.attached["keyboard"];
  48201. if (keyboard)
  48202. keyboard.keysDown = value;
  48203. },
  48204. enumerable: true,
  48205. configurable: true
  48206. });
  48207. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  48208. get: function () {
  48209. var keyboard = this.inputs.attached["keyboard"];
  48210. if (keyboard)
  48211. return keyboard.keysLeft;
  48212. return [];
  48213. },
  48214. set: function (value) {
  48215. var keyboard = this.inputs.attached["keyboard"];
  48216. if (keyboard)
  48217. keyboard.keysLeft = value;
  48218. },
  48219. enumerable: true,
  48220. configurable: true
  48221. });
  48222. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  48223. get: function () {
  48224. var keyboard = this.inputs.attached["keyboard"];
  48225. if (keyboard)
  48226. return keyboard.keysRight;
  48227. return [];
  48228. },
  48229. set: function (value) {
  48230. var keyboard = this.inputs.attached["keyboard"];
  48231. if (keyboard)
  48232. keyboard.keysRight = value;
  48233. },
  48234. enumerable: true,
  48235. configurable: true
  48236. });
  48237. // Controls
  48238. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  48239. this.inputs.attachElement(element, noPreventDefault);
  48240. };
  48241. FreeCamera.prototype.detachControl = function (element) {
  48242. this.inputs.detachElement(element);
  48243. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48244. this.cameraRotation = new BABYLON.Vector2(0, 0);
  48245. };
  48246. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  48247. get: function () {
  48248. return this._collisionMask;
  48249. },
  48250. set: function (mask) {
  48251. this._collisionMask = !isNaN(mask) ? mask : -1;
  48252. },
  48253. enumerable: true,
  48254. configurable: true
  48255. });
  48256. FreeCamera.prototype._collideWithWorld = function (displacement) {
  48257. var globalPosition;
  48258. if (this.parent) {
  48259. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  48260. }
  48261. else {
  48262. globalPosition = this.position;
  48263. }
  48264. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  48265. this._oldPosition.addInPlace(this.ellipsoidOffset);
  48266. if (!this._collider) {
  48267. this._collider = new BABYLON.Collider();
  48268. }
  48269. this._collider._radius = this.ellipsoid;
  48270. this._collider.collisionMask = this._collisionMask;
  48271. //no need for clone, as long as gravity is not on.
  48272. var actualDisplacement = displacement;
  48273. //add gravity to the direction to prevent the dual-collision checking
  48274. if (this.applyGravity) {
  48275. //this prevents mending with cameraDirection, a global variable of the free camera class.
  48276. actualDisplacement = displacement.add(this.getScene().gravity);
  48277. }
  48278. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48279. };
  48280. FreeCamera.prototype._checkInputs = function () {
  48281. if (!this._localDirection) {
  48282. this._localDirection = BABYLON.Vector3.Zero();
  48283. this._transformedDirection = BABYLON.Vector3.Zero();
  48284. }
  48285. this.inputs.checkInputs();
  48286. _super.prototype._checkInputs.call(this);
  48287. };
  48288. FreeCamera.prototype._decideIfNeedsToMove = function () {
  48289. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48290. };
  48291. FreeCamera.prototype._updatePosition = function () {
  48292. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  48293. this._collideWithWorld(this.cameraDirection);
  48294. }
  48295. else {
  48296. _super.prototype._updatePosition.call(this);
  48297. }
  48298. };
  48299. FreeCamera.prototype.dispose = function () {
  48300. this.inputs.clear();
  48301. _super.prototype.dispose.call(this);
  48302. };
  48303. FreeCamera.prototype.getClassName = function () {
  48304. return "FreeCamera";
  48305. };
  48306. __decorate([
  48307. BABYLON.serializeAsVector3()
  48308. ], FreeCamera.prototype, "ellipsoid", void 0);
  48309. __decorate([
  48310. BABYLON.serializeAsVector3()
  48311. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  48312. __decorate([
  48313. BABYLON.serialize()
  48314. ], FreeCamera.prototype, "checkCollisions", void 0);
  48315. __decorate([
  48316. BABYLON.serialize()
  48317. ], FreeCamera.prototype, "applyGravity", void 0);
  48318. return FreeCamera;
  48319. }(BABYLON.TargetCamera));
  48320. BABYLON.FreeCamera = FreeCamera;
  48321. })(BABYLON || (BABYLON = {}));
  48322. //# sourceMappingURL=babylon.freeCamera.js.map
  48323. var BABYLON;
  48324. (function (BABYLON) {
  48325. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  48326. function ArcRotateCameraKeyboardMoveInput() {
  48327. this._keys = new Array();
  48328. this.keysUp = [38];
  48329. this.keysDown = [40];
  48330. this.keysLeft = [37];
  48331. this.keysRight = [39];
  48332. this.keysReset = [220];
  48333. this.panningSensibility = 50.0;
  48334. this.zoomingSensibility = 25.0;
  48335. this.useAltToZoom = true;
  48336. }
  48337. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48338. var _this = this;
  48339. if (this._onCanvasBlurObserver) {
  48340. return;
  48341. }
  48342. this._scene = this.camera.getScene();
  48343. this._engine = this._scene.getEngine();
  48344. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48345. _this._keys = [];
  48346. });
  48347. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48348. var evt = info.event;
  48349. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48350. _this._ctrlPressed = evt.ctrlKey;
  48351. _this._altPressed = evt.altKey;
  48352. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48353. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48354. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48355. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48356. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48357. var index = _this._keys.indexOf(evt.keyCode);
  48358. if (index === -1) {
  48359. _this._keys.push(evt.keyCode);
  48360. }
  48361. if (evt.preventDefault) {
  48362. if (!noPreventDefault) {
  48363. evt.preventDefault();
  48364. }
  48365. }
  48366. }
  48367. }
  48368. else {
  48369. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48370. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48371. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48372. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48373. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48374. var index = _this._keys.indexOf(evt.keyCode);
  48375. if (index >= 0) {
  48376. _this._keys.splice(index, 1);
  48377. }
  48378. if (evt.preventDefault) {
  48379. if (!noPreventDefault) {
  48380. evt.preventDefault();
  48381. }
  48382. }
  48383. }
  48384. }
  48385. });
  48386. };
  48387. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48388. if (this._scene) {
  48389. if (this._onKeyboardObserver) {
  48390. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48391. }
  48392. if (this._onCanvasBlurObserver) {
  48393. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48394. }
  48395. this._onKeyboardObserver = null;
  48396. this._onCanvasBlurObserver = null;
  48397. }
  48398. this._keys = [];
  48399. };
  48400. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48401. if (this._onKeyboardObserver) {
  48402. var camera = this.camera;
  48403. for (var index = 0; index < this._keys.length; index++) {
  48404. var keyCode = this._keys[index];
  48405. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48406. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48407. camera.inertialPanningX -= 1 / this.panningSensibility;
  48408. }
  48409. else {
  48410. camera.inertialAlphaOffset -= 0.01;
  48411. }
  48412. }
  48413. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48414. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48415. camera.inertialPanningY += 1 / this.panningSensibility;
  48416. }
  48417. else if (this._altPressed && this.useAltToZoom) {
  48418. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  48419. }
  48420. else {
  48421. camera.inertialBetaOffset -= 0.01;
  48422. }
  48423. }
  48424. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48425. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48426. camera.inertialPanningX += 1 / this.panningSensibility;
  48427. }
  48428. else {
  48429. camera.inertialAlphaOffset += 0.01;
  48430. }
  48431. }
  48432. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48433. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48434. camera.inertialPanningY -= 1 / this.panningSensibility;
  48435. }
  48436. else if (this._altPressed && this.useAltToZoom) {
  48437. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  48438. }
  48439. else {
  48440. camera.inertialBetaOffset += 0.01;
  48441. }
  48442. }
  48443. else if (this.keysReset.indexOf(keyCode) !== -1) {
  48444. camera.restoreState();
  48445. }
  48446. }
  48447. }
  48448. };
  48449. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48450. return "ArcRotateCameraKeyboardMoveInput";
  48451. };
  48452. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48453. return "keyboard";
  48454. };
  48455. __decorate([
  48456. BABYLON.serialize()
  48457. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48458. __decorate([
  48459. BABYLON.serialize()
  48460. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48461. __decorate([
  48462. BABYLON.serialize()
  48463. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48464. __decorate([
  48465. BABYLON.serialize()
  48466. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48467. __decorate([
  48468. BABYLON.serialize()
  48469. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48470. __decorate([
  48471. BABYLON.serialize()
  48472. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48473. __decorate([
  48474. BABYLON.serialize()
  48475. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48476. __decorate([
  48477. BABYLON.serialize()
  48478. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48479. return ArcRotateCameraKeyboardMoveInput;
  48480. }());
  48481. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48482. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48483. })(BABYLON || (BABYLON = {}));
  48484. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48485. var BABYLON;
  48486. (function (BABYLON) {
  48487. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48488. function ArcRotateCameraMouseWheelInput() {
  48489. this.wheelPrecision = 3.0;
  48490. /**
  48491. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48492. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48493. */
  48494. this.wheelDeltaPercentage = 0;
  48495. }
  48496. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48497. var _this = this;
  48498. this._wheel = function (p, s) {
  48499. //sanity check - this should be a PointerWheel event.
  48500. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48501. return;
  48502. var event = p.event;
  48503. var delta = 0;
  48504. if (event.wheelDelta) {
  48505. if (_this.wheelDeltaPercentage) {
  48506. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48507. if (event.wheelDelta > 0) {
  48508. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48509. }
  48510. else {
  48511. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48512. }
  48513. }
  48514. else {
  48515. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48516. }
  48517. }
  48518. else if (event.detail) {
  48519. delta = -event.detail / _this.wheelPrecision;
  48520. }
  48521. if (delta)
  48522. _this.camera.inertialRadiusOffset += delta;
  48523. if (event.preventDefault) {
  48524. if (!noPreventDefault) {
  48525. event.preventDefault();
  48526. }
  48527. }
  48528. };
  48529. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48530. };
  48531. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48532. if (this._observer && element) {
  48533. this.camera.getScene().onPointerObservable.remove(this._observer);
  48534. this._observer = null;
  48535. this._wheel = null;
  48536. }
  48537. };
  48538. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48539. return "ArcRotateCameraMouseWheelInput";
  48540. };
  48541. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48542. return "mousewheel";
  48543. };
  48544. __decorate([
  48545. BABYLON.serialize()
  48546. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48547. __decorate([
  48548. BABYLON.serialize()
  48549. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48550. return ArcRotateCameraMouseWheelInput;
  48551. }());
  48552. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48553. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48554. })(BABYLON || (BABYLON = {}));
  48555. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48556. var BABYLON;
  48557. (function (BABYLON) {
  48558. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48559. function ArcRotateCameraPointersInput() {
  48560. this.buttons = [0, 1, 2];
  48561. this.angularSensibilityX = 1000.0;
  48562. this.angularSensibilityY = 1000.0;
  48563. this.pinchPrecision = 12.0;
  48564. /**
  48565. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48566. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48567. */
  48568. this.pinchDeltaPercentage = 0;
  48569. this.panningSensibility = 1000.0;
  48570. this.multiTouchPanning = true;
  48571. this.multiTouchPanAndZoom = true;
  48572. this._isPanClick = false;
  48573. this.pinchInwards = true;
  48574. }
  48575. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48576. var _this = this;
  48577. var engine = this.camera.getEngine();
  48578. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48579. var pointA = null;
  48580. var pointB = null;
  48581. var previousPinchSquaredDistance = 0;
  48582. var initialDistance = 0;
  48583. var twoFingerActivityCount = 0;
  48584. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48585. this._pointerInput = function (p, s) {
  48586. var evt = p.event;
  48587. var isTouch = p.event.pointerType === "touch";
  48588. if (engine.isInVRExclusivePointerMode) {
  48589. return;
  48590. }
  48591. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48592. return;
  48593. }
  48594. var srcElement = (evt.srcElement || evt.target);
  48595. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48596. try {
  48597. srcElement.setPointerCapture(evt.pointerId);
  48598. }
  48599. catch (e) {
  48600. //Nothing to do with the error. Execution will continue.
  48601. }
  48602. // Manage panning with pan button click
  48603. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48604. // manage pointers
  48605. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48606. if (pointA === null) {
  48607. pointA = cacheSoloPointer;
  48608. }
  48609. else if (pointB === null) {
  48610. pointB = cacheSoloPointer;
  48611. }
  48612. if (!noPreventDefault) {
  48613. evt.preventDefault();
  48614. element.focus();
  48615. }
  48616. }
  48617. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48618. _this.camera.restoreState();
  48619. }
  48620. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48621. try {
  48622. srcElement.releasePointerCapture(evt.pointerId);
  48623. }
  48624. catch (e) {
  48625. //Nothing to do with the error.
  48626. }
  48627. cacheSoloPointer = null;
  48628. previousPinchSquaredDistance = 0;
  48629. previousMultiTouchPanPosition.isPaning = false;
  48630. previousMultiTouchPanPosition.isPinching = false;
  48631. twoFingerActivityCount = 0;
  48632. initialDistance = 0;
  48633. if (!isTouch) {
  48634. pointB = null; // Mouse and pen are mono pointer
  48635. }
  48636. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48637. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48638. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48639. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48640. if (engine._badOS) {
  48641. pointA = pointB = null;
  48642. }
  48643. else {
  48644. //only remove the impacted pointer in case of multitouch allowing on most
  48645. //platforms switching from rotate to zoom and pan seamlessly.
  48646. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48647. pointA = pointB;
  48648. pointB = null;
  48649. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48650. }
  48651. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48652. pointB = null;
  48653. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48654. }
  48655. else {
  48656. pointA = pointB = null;
  48657. }
  48658. }
  48659. if (!noPreventDefault) {
  48660. evt.preventDefault();
  48661. }
  48662. }
  48663. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48664. if (!noPreventDefault) {
  48665. evt.preventDefault();
  48666. }
  48667. // One button down
  48668. if (pointA && pointB === null && cacheSoloPointer) {
  48669. if (_this.panningSensibility !== 0 &&
  48670. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48671. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48672. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48673. }
  48674. else {
  48675. var offsetX = evt.clientX - cacheSoloPointer.x;
  48676. var offsetY = evt.clientY - cacheSoloPointer.y;
  48677. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48678. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48679. }
  48680. cacheSoloPointer.x = evt.clientX;
  48681. cacheSoloPointer.y = evt.clientY;
  48682. }
  48683. // Two buttons down: pinch/pan
  48684. else if (pointA && pointB) {
  48685. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48686. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48687. ed.x = evt.clientX;
  48688. ed.y = evt.clientY;
  48689. var direction = _this.pinchInwards ? 1 : -1;
  48690. var distX = pointA.x - pointB.x;
  48691. var distY = pointA.y - pointB.y;
  48692. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48693. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48694. if (previousPinchSquaredDistance === 0) {
  48695. initialDistance = pinchDistance;
  48696. previousPinchSquaredDistance = pinchSquaredDistance;
  48697. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48698. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48699. return;
  48700. }
  48701. if (_this.multiTouchPanAndZoom) {
  48702. if (_this.pinchDeltaPercentage) {
  48703. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48704. }
  48705. else {
  48706. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48707. (_this.pinchPrecision *
  48708. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48709. direction);
  48710. }
  48711. if (_this.panningSensibility !== 0) {
  48712. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48713. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48714. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48715. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48716. previousMultiTouchPanPosition.x = pointersCenterX;
  48717. previousMultiTouchPanPosition.y = pointersCenterY;
  48718. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48719. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48720. }
  48721. }
  48722. else {
  48723. twoFingerActivityCount++;
  48724. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48725. if (_this.pinchDeltaPercentage) {
  48726. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48727. }
  48728. else {
  48729. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48730. (_this.pinchPrecision *
  48731. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48732. direction);
  48733. }
  48734. previousMultiTouchPanPosition.isPaning = false;
  48735. previousMultiTouchPanPosition.isPinching = true;
  48736. }
  48737. else {
  48738. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48739. if (!previousMultiTouchPanPosition.isPaning) {
  48740. previousMultiTouchPanPosition.isPaning = true;
  48741. previousMultiTouchPanPosition.isPinching = false;
  48742. previousMultiTouchPanPosition.x = ed.x;
  48743. previousMultiTouchPanPosition.y = ed.y;
  48744. return;
  48745. }
  48746. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48747. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48748. }
  48749. }
  48750. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48751. previousMultiTouchPanPosition.x = ed.x;
  48752. previousMultiTouchPanPosition.y = ed.y;
  48753. }
  48754. }
  48755. previousPinchSquaredDistance = pinchSquaredDistance;
  48756. }
  48757. }
  48758. };
  48759. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48760. this._onContextMenu = function (evt) {
  48761. evt.preventDefault();
  48762. };
  48763. if (!this.camera._useCtrlForPanning) {
  48764. element.addEventListener("contextmenu", this._onContextMenu, false);
  48765. }
  48766. this._onLostFocus = function () {
  48767. //this._keys = [];
  48768. pointA = pointB = null;
  48769. previousPinchSquaredDistance = 0;
  48770. previousMultiTouchPanPosition.isPaning = false;
  48771. previousMultiTouchPanPosition.isPinching = false;
  48772. twoFingerActivityCount = 0;
  48773. cacheSoloPointer = null;
  48774. initialDistance = 0;
  48775. };
  48776. this._onMouseMove = function (evt) {
  48777. if (!engine.isPointerLock) {
  48778. return;
  48779. }
  48780. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48781. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48782. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48783. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48784. if (!noPreventDefault) {
  48785. evt.preventDefault();
  48786. }
  48787. };
  48788. this._onGestureStart = function (e) {
  48789. if (window.MSGesture === undefined) {
  48790. return;
  48791. }
  48792. if (!_this._MSGestureHandler) {
  48793. _this._MSGestureHandler = new MSGesture();
  48794. _this._MSGestureHandler.target = element;
  48795. }
  48796. _this._MSGestureHandler.addPointer(e.pointerId);
  48797. };
  48798. this._onGesture = function (e) {
  48799. _this.camera.radius *= e.scale;
  48800. if (e.preventDefault) {
  48801. if (!noPreventDefault) {
  48802. e.stopPropagation();
  48803. e.preventDefault();
  48804. }
  48805. }
  48806. };
  48807. element.addEventListener("mousemove", this._onMouseMove, false);
  48808. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48809. element.addEventListener("MSGestureChange", this._onGesture, false);
  48810. BABYLON.Tools.RegisterTopRootEvents([
  48811. { name: "blur", handler: this._onLostFocus }
  48812. ]);
  48813. };
  48814. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48815. if (this._onLostFocus) {
  48816. BABYLON.Tools.UnregisterTopRootEvents([
  48817. { name: "blur", handler: this._onLostFocus }
  48818. ]);
  48819. }
  48820. if (element && this._observer) {
  48821. this.camera.getScene().onPointerObservable.remove(this._observer);
  48822. this._observer = null;
  48823. if (this._onContextMenu) {
  48824. element.removeEventListener("contextmenu", this._onContextMenu);
  48825. }
  48826. if (this._onMouseMove) {
  48827. element.removeEventListener("mousemove", this._onMouseMove);
  48828. }
  48829. if (this._onGestureStart) {
  48830. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48831. }
  48832. if (this._onGesture) {
  48833. element.removeEventListener("MSGestureChange", this._onGesture);
  48834. }
  48835. this._isPanClick = false;
  48836. this.pinchInwards = true;
  48837. this._onMouseMove = null;
  48838. this._onGestureStart = null;
  48839. this._onGesture = null;
  48840. this._MSGestureHandler = null;
  48841. this._onLostFocus = null;
  48842. this._onContextMenu = null;
  48843. }
  48844. };
  48845. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48846. return "ArcRotateCameraPointersInput";
  48847. };
  48848. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48849. return "pointers";
  48850. };
  48851. __decorate([
  48852. BABYLON.serialize()
  48853. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48854. __decorate([
  48855. BABYLON.serialize()
  48856. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48857. __decorate([
  48858. BABYLON.serialize()
  48859. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48860. __decorate([
  48861. BABYLON.serialize()
  48862. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48863. __decorate([
  48864. BABYLON.serialize()
  48865. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48866. __decorate([
  48867. BABYLON.serialize()
  48868. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48869. __decorate([
  48870. BABYLON.serialize()
  48871. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48872. __decorate([
  48873. BABYLON.serialize()
  48874. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48875. return ArcRotateCameraPointersInput;
  48876. }());
  48877. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48878. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48879. })(BABYLON || (BABYLON = {}));
  48880. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48881. var BABYLON;
  48882. (function (BABYLON) {
  48883. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48884. __extends(ArcRotateCameraInputsManager, _super);
  48885. function ArcRotateCameraInputsManager(camera) {
  48886. return _super.call(this, camera) || this;
  48887. }
  48888. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48889. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48890. return this;
  48891. };
  48892. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48893. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48894. return this;
  48895. };
  48896. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48897. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48898. return this;
  48899. };
  48900. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48901. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48902. return this;
  48903. };
  48904. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48905. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48906. return this;
  48907. };
  48908. return ArcRotateCameraInputsManager;
  48909. }(BABYLON.CameraInputsManager));
  48910. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48911. })(BABYLON || (BABYLON = {}));
  48912. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48913. var BABYLON;
  48914. (function (BABYLON) {
  48915. var ArcRotateCamera = /** @class */ (function (_super) {
  48916. __extends(ArcRotateCamera, _super);
  48917. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48918. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48919. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48920. _this.inertialAlphaOffset = 0;
  48921. _this.inertialBetaOffset = 0;
  48922. _this.inertialRadiusOffset = 0;
  48923. _this.lowerAlphaLimit = null;
  48924. _this.upperAlphaLimit = null;
  48925. _this.lowerBetaLimit = 0.01;
  48926. _this.upperBetaLimit = Math.PI;
  48927. _this.lowerRadiusLimit = null;
  48928. _this.upperRadiusLimit = null;
  48929. _this.inertialPanningX = 0;
  48930. _this.inertialPanningY = 0;
  48931. _this.pinchToPanMaxDistance = 20;
  48932. _this.panningDistanceLimit = null;
  48933. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48934. _this.panningInertia = 0.9;
  48935. //-- end properties for backward compatibility for inputs
  48936. _this.zoomOnFactor = 1;
  48937. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48938. _this.allowUpsideDown = true;
  48939. _this._viewMatrix = new BABYLON.Matrix();
  48940. // Panning
  48941. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48942. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48943. _this.checkCollisions = false;
  48944. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48945. _this._previousPosition = BABYLON.Vector3.Zero();
  48946. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48947. _this._newPosition = BABYLON.Vector3.Zero();
  48948. _this._computationVector = BABYLON.Vector3.Zero();
  48949. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48950. if (collidedMesh === void 0) { collidedMesh = null; }
  48951. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48952. newPosition.multiplyInPlace(_this._collider._radius);
  48953. }
  48954. if (!collidedMesh) {
  48955. _this._previousPosition.copyFrom(_this.position);
  48956. }
  48957. else {
  48958. _this.setPosition(newPosition);
  48959. if (_this.onCollide) {
  48960. _this.onCollide(collidedMesh);
  48961. }
  48962. }
  48963. // Recompute because of constraints
  48964. var cosa = Math.cos(_this.alpha);
  48965. var sina = Math.sin(_this.alpha);
  48966. var cosb = Math.cos(_this.beta);
  48967. var sinb = Math.sin(_this.beta);
  48968. if (sinb === 0) {
  48969. sinb = 0.0001;
  48970. }
  48971. var target = _this._getTargetPosition();
  48972. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48973. target.addToRef(_this._computationVector, _this._newPosition);
  48974. _this.position.copyFrom(_this._newPosition);
  48975. var up = _this.upVector;
  48976. if (_this.allowUpsideDown && _this.beta < 0) {
  48977. up = up.clone();
  48978. up = up.negate();
  48979. }
  48980. _this._computeViewMatrix(_this.position, target, up);
  48981. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48982. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48983. _this._collisionTriggered = false;
  48984. };
  48985. _this._target = BABYLON.Vector3.Zero();
  48986. if (target) {
  48987. _this.setTarget(target);
  48988. }
  48989. _this.alpha = alpha;
  48990. _this.beta = beta;
  48991. _this.radius = radius;
  48992. _this.getViewMatrix();
  48993. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48994. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48995. return _this;
  48996. }
  48997. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48998. get: function () {
  48999. return this._target;
  49000. },
  49001. set: function (value) {
  49002. this.setTarget(value);
  49003. },
  49004. enumerable: true,
  49005. configurable: true
  49006. });
  49007. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  49008. //-- begin properties for backward compatibility for inputs
  49009. get: function () {
  49010. var pointers = this.inputs.attached["pointers"];
  49011. if (pointers)
  49012. return pointers.angularSensibilityX;
  49013. return 0;
  49014. },
  49015. set: function (value) {
  49016. var pointers = this.inputs.attached["pointers"];
  49017. if (pointers) {
  49018. pointers.angularSensibilityX = value;
  49019. }
  49020. },
  49021. enumerable: true,
  49022. configurable: true
  49023. });
  49024. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  49025. get: function () {
  49026. var pointers = this.inputs.attached["pointers"];
  49027. if (pointers)
  49028. return pointers.angularSensibilityY;
  49029. return 0;
  49030. },
  49031. set: function (value) {
  49032. var pointers = this.inputs.attached["pointers"];
  49033. if (pointers) {
  49034. pointers.angularSensibilityY = value;
  49035. }
  49036. },
  49037. enumerable: true,
  49038. configurable: true
  49039. });
  49040. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  49041. get: function () {
  49042. var pointers = this.inputs.attached["pointers"];
  49043. if (pointers)
  49044. return pointers.pinchPrecision;
  49045. return 0;
  49046. },
  49047. set: function (value) {
  49048. var pointers = this.inputs.attached["pointers"];
  49049. if (pointers) {
  49050. pointers.pinchPrecision = value;
  49051. }
  49052. },
  49053. enumerable: true,
  49054. configurable: true
  49055. });
  49056. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  49057. get: function () {
  49058. var pointers = this.inputs.attached["pointers"];
  49059. if (pointers)
  49060. return pointers.pinchDeltaPercentage;
  49061. return 0;
  49062. },
  49063. set: function (value) {
  49064. var pointers = this.inputs.attached["pointers"];
  49065. if (pointers) {
  49066. pointers.pinchDeltaPercentage = value;
  49067. }
  49068. },
  49069. enumerable: true,
  49070. configurable: true
  49071. });
  49072. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  49073. get: function () {
  49074. var pointers = this.inputs.attached["pointers"];
  49075. if (pointers)
  49076. return pointers.panningSensibility;
  49077. return 0;
  49078. },
  49079. set: function (value) {
  49080. var pointers = this.inputs.attached["pointers"];
  49081. if (pointers) {
  49082. pointers.panningSensibility = value;
  49083. }
  49084. },
  49085. enumerable: true,
  49086. configurable: true
  49087. });
  49088. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  49089. get: function () {
  49090. var keyboard = this.inputs.attached["keyboard"];
  49091. if (keyboard)
  49092. return keyboard.keysUp;
  49093. return [];
  49094. },
  49095. set: function (value) {
  49096. var keyboard = this.inputs.attached["keyboard"];
  49097. if (keyboard)
  49098. keyboard.keysUp = value;
  49099. },
  49100. enumerable: true,
  49101. configurable: true
  49102. });
  49103. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  49104. get: function () {
  49105. var keyboard = this.inputs.attached["keyboard"];
  49106. if (keyboard)
  49107. return keyboard.keysDown;
  49108. return [];
  49109. },
  49110. set: function (value) {
  49111. var keyboard = this.inputs.attached["keyboard"];
  49112. if (keyboard)
  49113. keyboard.keysDown = value;
  49114. },
  49115. enumerable: true,
  49116. configurable: true
  49117. });
  49118. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  49119. get: function () {
  49120. var keyboard = this.inputs.attached["keyboard"];
  49121. if (keyboard)
  49122. return keyboard.keysLeft;
  49123. return [];
  49124. },
  49125. set: function (value) {
  49126. var keyboard = this.inputs.attached["keyboard"];
  49127. if (keyboard)
  49128. keyboard.keysLeft = value;
  49129. },
  49130. enumerable: true,
  49131. configurable: true
  49132. });
  49133. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  49134. get: function () {
  49135. var keyboard = this.inputs.attached["keyboard"];
  49136. if (keyboard)
  49137. return keyboard.keysRight;
  49138. return [];
  49139. },
  49140. set: function (value) {
  49141. var keyboard = this.inputs.attached["keyboard"];
  49142. if (keyboard)
  49143. keyboard.keysRight = value;
  49144. },
  49145. enumerable: true,
  49146. configurable: true
  49147. });
  49148. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  49149. get: function () {
  49150. var mousewheel = this.inputs.attached["mousewheel"];
  49151. if (mousewheel)
  49152. return mousewheel.wheelPrecision;
  49153. return 0;
  49154. },
  49155. set: function (value) {
  49156. var mousewheel = this.inputs.attached["mousewheel"];
  49157. if (mousewheel)
  49158. mousewheel.wheelPrecision = value;
  49159. },
  49160. enumerable: true,
  49161. configurable: true
  49162. });
  49163. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  49164. get: function () {
  49165. var mousewheel = this.inputs.attached["mousewheel"];
  49166. if (mousewheel)
  49167. return mousewheel.wheelDeltaPercentage;
  49168. return 0;
  49169. },
  49170. set: function (value) {
  49171. var mousewheel = this.inputs.attached["mousewheel"];
  49172. if (mousewheel)
  49173. mousewheel.wheelDeltaPercentage = value;
  49174. },
  49175. enumerable: true,
  49176. configurable: true
  49177. });
  49178. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  49179. get: function () {
  49180. return this._bouncingBehavior;
  49181. },
  49182. enumerable: true,
  49183. configurable: true
  49184. });
  49185. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  49186. get: function () {
  49187. return this._bouncingBehavior != null;
  49188. },
  49189. set: function (value) {
  49190. if (value === this.useBouncingBehavior) {
  49191. return;
  49192. }
  49193. if (value) {
  49194. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  49195. this.addBehavior(this._bouncingBehavior);
  49196. }
  49197. else if (this._bouncingBehavior) {
  49198. this.removeBehavior(this._bouncingBehavior);
  49199. this._bouncingBehavior = null;
  49200. }
  49201. },
  49202. enumerable: true,
  49203. configurable: true
  49204. });
  49205. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  49206. get: function () {
  49207. return this._framingBehavior;
  49208. },
  49209. enumerable: true,
  49210. configurable: true
  49211. });
  49212. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  49213. get: function () {
  49214. return this._framingBehavior != null;
  49215. },
  49216. set: function (value) {
  49217. if (value === this.useFramingBehavior) {
  49218. return;
  49219. }
  49220. if (value) {
  49221. this._framingBehavior = new BABYLON.FramingBehavior();
  49222. this.addBehavior(this._framingBehavior);
  49223. }
  49224. else if (this._framingBehavior) {
  49225. this.removeBehavior(this._framingBehavior);
  49226. this._framingBehavior = null;
  49227. }
  49228. },
  49229. enumerable: true,
  49230. configurable: true
  49231. });
  49232. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  49233. get: function () {
  49234. return this._autoRotationBehavior;
  49235. },
  49236. enumerable: true,
  49237. configurable: true
  49238. });
  49239. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  49240. get: function () {
  49241. return this._autoRotationBehavior != null;
  49242. },
  49243. set: function (value) {
  49244. if (value === this.useAutoRotationBehavior) {
  49245. return;
  49246. }
  49247. if (value) {
  49248. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  49249. this.addBehavior(this._autoRotationBehavior);
  49250. }
  49251. else if (this._autoRotationBehavior) {
  49252. this.removeBehavior(this._autoRotationBehavior);
  49253. this._autoRotationBehavior = null;
  49254. }
  49255. },
  49256. enumerable: true,
  49257. configurable: true
  49258. });
  49259. // Cache
  49260. ArcRotateCamera.prototype._initCache = function () {
  49261. _super.prototype._initCache.call(this);
  49262. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  49263. this._cache.alpha = undefined;
  49264. this._cache.beta = undefined;
  49265. this._cache.radius = undefined;
  49266. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  49267. };
  49268. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  49269. if (!ignoreParentClass) {
  49270. _super.prototype._updateCache.call(this);
  49271. }
  49272. this._cache._target.copyFrom(this._getTargetPosition());
  49273. this._cache.alpha = this.alpha;
  49274. this._cache.beta = this.beta;
  49275. this._cache.radius = this.radius;
  49276. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  49277. };
  49278. ArcRotateCamera.prototype._getTargetPosition = function () {
  49279. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  49280. var pos = this._targetHost.getAbsolutePosition();
  49281. if (this._targetBoundingCenter) {
  49282. pos.addToRef(this._targetBoundingCenter, this._target);
  49283. }
  49284. else {
  49285. this._target.copyFrom(pos);
  49286. }
  49287. }
  49288. var lockedTargetPosition = this._getLockedTargetPosition();
  49289. if (lockedTargetPosition) {
  49290. return lockedTargetPosition;
  49291. }
  49292. return this._target;
  49293. };
  49294. ArcRotateCamera.prototype.storeState = function () {
  49295. this._storedAlpha = this.alpha;
  49296. this._storedBeta = this.beta;
  49297. this._storedRadius = this.radius;
  49298. this._storedTarget = this._getTargetPosition().clone();
  49299. return _super.prototype.storeState.call(this);
  49300. };
  49301. /**
  49302. * Restored camera state. You must call storeState() first
  49303. */
  49304. ArcRotateCamera.prototype._restoreStateValues = function () {
  49305. if (!_super.prototype._restoreStateValues.call(this)) {
  49306. return false;
  49307. }
  49308. this.alpha = this._storedAlpha;
  49309. this.beta = this._storedBeta;
  49310. this.radius = this._storedRadius;
  49311. this.setTarget(this._storedTarget.clone());
  49312. this.inertialAlphaOffset = 0;
  49313. this.inertialBetaOffset = 0;
  49314. this.inertialRadiusOffset = 0;
  49315. this.inertialPanningX = 0;
  49316. this.inertialPanningY = 0;
  49317. return true;
  49318. };
  49319. // Synchronized
  49320. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  49321. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  49322. return false;
  49323. return this._cache._target.equals(this._getTargetPosition())
  49324. && this._cache.alpha === this.alpha
  49325. && this._cache.beta === this.beta
  49326. && this._cache.radius === this.radius
  49327. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  49328. };
  49329. // Methods
  49330. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  49331. var _this = this;
  49332. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  49333. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  49334. this._useCtrlForPanning = useCtrlForPanning;
  49335. this._panningMouseButton = panningMouseButton;
  49336. this.inputs.attachElement(element, noPreventDefault);
  49337. this._reset = function () {
  49338. _this.inertialAlphaOffset = 0;
  49339. _this.inertialBetaOffset = 0;
  49340. _this.inertialRadiusOffset = 0;
  49341. _this.inertialPanningX = 0;
  49342. _this.inertialPanningY = 0;
  49343. };
  49344. };
  49345. ArcRotateCamera.prototype.detachControl = function (element) {
  49346. this.inputs.detachElement(element);
  49347. if (this._reset) {
  49348. this._reset();
  49349. }
  49350. };
  49351. ArcRotateCamera.prototype._checkInputs = function () {
  49352. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  49353. if (this._collisionTriggered) {
  49354. return;
  49355. }
  49356. this.inputs.checkInputs();
  49357. // Inertia
  49358. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  49359. var inertialAlphaOffset = this.inertialAlphaOffset;
  49360. if (this.beta <= 0)
  49361. inertialAlphaOffset *= -1;
  49362. if (this.getScene().useRightHandedSystem)
  49363. inertialAlphaOffset *= -1;
  49364. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  49365. inertialAlphaOffset *= -1;
  49366. this.alpha += inertialAlphaOffset;
  49367. this.beta += this.inertialBetaOffset;
  49368. this.radius -= this.inertialRadiusOffset;
  49369. this.inertialAlphaOffset *= this.inertia;
  49370. this.inertialBetaOffset *= this.inertia;
  49371. this.inertialRadiusOffset *= this.inertia;
  49372. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  49373. this.inertialAlphaOffset = 0;
  49374. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  49375. this.inertialBetaOffset = 0;
  49376. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  49377. this.inertialRadiusOffset = 0;
  49378. }
  49379. // Panning inertia
  49380. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  49381. if (!this._localDirection) {
  49382. this._localDirection = BABYLON.Vector3.Zero();
  49383. this._transformedDirection = BABYLON.Vector3.Zero();
  49384. }
  49385. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  49386. this._localDirection.multiplyInPlace(this.panningAxis);
  49387. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  49388. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  49389. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  49390. if (!this.panningAxis.y) {
  49391. this._transformedDirection.y = 0;
  49392. }
  49393. if (!this._targetHost) {
  49394. if (this.panningDistanceLimit) {
  49395. this._transformedDirection.addInPlace(this._target);
  49396. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  49397. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  49398. this._target.copyFrom(this._transformedDirection);
  49399. }
  49400. }
  49401. else {
  49402. this._target.addInPlace(this._transformedDirection);
  49403. }
  49404. }
  49405. this.inertialPanningX *= this.panningInertia;
  49406. this.inertialPanningY *= this.panningInertia;
  49407. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  49408. this.inertialPanningX = 0;
  49409. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  49410. this.inertialPanningY = 0;
  49411. }
  49412. // Limits
  49413. this._checkLimits();
  49414. _super.prototype._checkInputs.call(this);
  49415. };
  49416. ArcRotateCamera.prototype._checkLimits = function () {
  49417. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49418. if (this.allowUpsideDown && this.beta > Math.PI) {
  49419. this.beta = this.beta - (2 * Math.PI);
  49420. }
  49421. }
  49422. else {
  49423. if (this.beta < this.lowerBetaLimit) {
  49424. this.beta = this.lowerBetaLimit;
  49425. }
  49426. }
  49427. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49428. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49429. this.beta = this.beta + (2 * Math.PI);
  49430. }
  49431. }
  49432. else {
  49433. if (this.beta > this.upperBetaLimit) {
  49434. this.beta = this.upperBetaLimit;
  49435. }
  49436. }
  49437. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  49438. this.alpha = this.lowerAlphaLimit;
  49439. }
  49440. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  49441. this.alpha = this.upperAlphaLimit;
  49442. }
  49443. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  49444. this.radius = this.lowerRadiusLimit;
  49445. }
  49446. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  49447. this.radius = this.upperRadiusLimit;
  49448. }
  49449. };
  49450. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49451. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49452. this.radius = this._computationVector.length();
  49453. if (this.radius === 0) {
  49454. this.radius = 0.0001; // Just to avoid division by zero
  49455. }
  49456. // Alpha
  49457. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49458. if (this._computationVector.z < 0) {
  49459. this.alpha = 2 * Math.PI - this.alpha;
  49460. }
  49461. // Beta
  49462. this.beta = Math.acos(this._computationVector.y / this.radius);
  49463. this._checkLimits();
  49464. };
  49465. ArcRotateCamera.prototype.setPosition = function (position) {
  49466. if (this.position.equals(position)) {
  49467. return;
  49468. }
  49469. this.position.copyFrom(position);
  49470. this.rebuildAnglesAndRadius();
  49471. };
  49472. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49473. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49474. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49475. if (target.getBoundingInfo) {
  49476. if (toBoundingCenter) {
  49477. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49478. }
  49479. else {
  49480. this._targetBoundingCenter = null;
  49481. }
  49482. this._targetHost = target;
  49483. this._target = this._getTargetPosition();
  49484. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49485. }
  49486. else {
  49487. var newTarget = target;
  49488. var currentTarget = this._getTargetPosition();
  49489. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49490. return;
  49491. }
  49492. this._targetHost = null;
  49493. this._target = newTarget;
  49494. this._targetBoundingCenter = null;
  49495. this.onMeshTargetChangedObservable.notifyObservers(null);
  49496. }
  49497. this.rebuildAnglesAndRadius();
  49498. };
  49499. ArcRotateCamera.prototype._getViewMatrix = function () {
  49500. // Compute
  49501. var cosa = Math.cos(this.alpha);
  49502. var sina = Math.sin(this.alpha);
  49503. var cosb = Math.cos(this.beta);
  49504. var sinb = Math.sin(this.beta);
  49505. if (sinb === 0) {
  49506. sinb = 0.0001;
  49507. }
  49508. var target = this._getTargetPosition();
  49509. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49510. target.addToRef(this._computationVector, this._newPosition);
  49511. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49512. if (!this._collider) {
  49513. this._collider = new BABYLON.Collider();
  49514. }
  49515. this._collider._radius = this.collisionRadius;
  49516. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49517. this._collisionTriggered = true;
  49518. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49519. }
  49520. else {
  49521. this.position.copyFrom(this._newPosition);
  49522. var up = this.upVector;
  49523. if (this.allowUpsideDown && sinb < 0) {
  49524. up = up.clone();
  49525. up = up.negate();
  49526. }
  49527. this._computeViewMatrix(this.position, target, up);
  49528. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49529. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49530. }
  49531. this._currentTarget = target;
  49532. return this._viewMatrix;
  49533. };
  49534. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49535. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49536. meshes = meshes || this.getScene().meshes;
  49537. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49538. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49539. this.radius = distance * this.zoomOnFactor;
  49540. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49541. };
  49542. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49543. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49544. var meshesOrMinMaxVector;
  49545. var distance;
  49546. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49547. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49548. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49549. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49550. }
  49551. else { //minMaxVector and distance
  49552. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49553. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49554. distance = minMaxVectorAndDistance.distance;
  49555. }
  49556. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49557. if (!doNotUpdateMaxZ) {
  49558. this.maxZ = distance * 2;
  49559. }
  49560. };
  49561. /**
  49562. * @override
  49563. * Override Camera.createRigCamera
  49564. */
  49565. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49566. var alphaShift = 0;
  49567. switch (this.cameraRigMode) {
  49568. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49569. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49570. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49571. case BABYLON.Camera.RIG_MODE_VR:
  49572. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49573. break;
  49574. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49575. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49576. break;
  49577. }
  49578. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49579. rigCam._cameraRigParams = {};
  49580. return rigCam;
  49581. };
  49582. /**
  49583. * @override
  49584. * Override Camera._updateRigCameras
  49585. */
  49586. ArcRotateCamera.prototype._updateRigCameras = function () {
  49587. var camLeft = this._rigCameras[0];
  49588. var camRight = this._rigCameras[1];
  49589. camLeft.beta = camRight.beta = this.beta;
  49590. camLeft.radius = camRight.radius = this.radius;
  49591. switch (this.cameraRigMode) {
  49592. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49593. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49594. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49595. case BABYLON.Camera.RIG_MODE_VR:
  49596. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49597. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49598. break;
  49599. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49600. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49601. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49602. break;
  49603. }
  49604. _super.prototype._updateRigCameras.call(this);
  49605. };
  49606. ArcRotateCamera.prototype.dispose = function () {
  49607. this.inputs.clear();
  49608. _super.prototype.dispose.call(this);
  49609. };
  49610. ArcRotateCamera.prototype.getClassName = function () {
  49611. return "ArcRotateCamera";
  49612. };
  49613. __decorate([
  49614. BABYLON.serialize()
  49615. ], ArcRotateCamera.prototype, "alpha", void 0);
  49616. __decorate([
  49617. BABYLON.serialize()
  49618. ], ArcRotateCamera.prototype, "beta", void 0);
  49619. __decorate([
  49620. BABYLON.serialize()
  49621. ], ArcRotateCamera.prototype, "radius", void 0);
  49622. __decorate([
  49623. BABYLON.serializeAsVector3("target")
  49624. ], ArcRotateCamera.prototype, "_target", void 0);
  49625. __decorate([
  49626. BABYLON.serialize()
  49627. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49628. __decorate([
  49629. BABYLON.serialize()
  49630. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49631. __decorate([
  49632. BABYLON.serialize()
  49633. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49634. __decorate([
  49635. BABYLON.serialize()
  49636. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49637. __decorate([
  49638. BABYLON.serialize()
  49639. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49640. __decorate([
  49641. BABYLON.serialize()
  49642. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49643. __decorate([
  49644. BABYLON.serialize()
  49645. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49646. __decorate([
  49647. BABYLON.serialize()
  49648. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49649. __decorate([
  49650. BABYLON.serialize()
  49651. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49652. __decorate([
  49653. BABYLON.serialize()
  49654. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49655. __decorate([
  49656. BABYLON.serialize()
  49657. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49658. __decorate([
  49659. BABYLON.serialize()
  49660. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49661. __decorate([
  49662. BABYLON.serialize()
  49663. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49664. __decorate([
  49665. BABYLON.serializeAsVector3()
  49666. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49667. __decorate([
  49668. BABYLON.serialize()
  49669. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49670. __decorate([
  49671. BABYLON.serialize()
  49672. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49673. __decorate([
  49674. BABYLON.serialize()
  49675. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49676. return ArcRotateCamera;
  49677. }(BABYLON.TargetCamera));
  49678. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49679. })(BABYLON || (BABYLON = {}));
  49680. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49681. var BABYLON;
  49682. (function (BABYLON) {
  49683. /**
  49684. * The HemisphericLight simulates the ambient environment light,
  49685. * so the passed direction is the light reflection direction, not the incoming direction.
  49686. */
  49687. var HemisphericLight = /** @class */ (function (_super) {
  49688. __extends(HemisphericLight, _super);
  49689. /**
  49690. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49691. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49692. * The HemisphericLight can't cast shadows.
  49693. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49694. * @param name The friendly name of the light
  49695. * @param direction The direction of the light reflection
  49696. * @param scene The scene the light belongs to
  49697. */
  49698. function HemisphericLight(name, direction, scene) {
  49699. var _this = _super.call(this, name, scene) || this;
  49700. /**
  49701. * The groundColor is the light in the opposite direction to the one specified during creation.
  49702. * 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.
  49703. */
  49704. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49705. _this.direction = direction || BABYLON.Vector3.Up();
  49706. return _this;
  49707. }
  49708. HemisphericLight.prototype._buildUniformLayout = function () {
  49709. this._uniformBuffer.addUniform("vLightData", 4);
  49710. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49711. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49712. this._uniformBuffer.addUniform("vLightGround", 3);
  49713. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49714. this._uniformBuffer.addUniform("depthValues", 2);
  49715. this._uniformBuffer.create();
  49716. };
  49717. /**
  49718. * Returns the string "HemisphericLight".
  49719. * @return The class name
  49720. */
  49721. HemisphericLight.prototype.getClassName = function () {
  49722. return "HemisphericLight";
  49723. };
  49724. /**
  49725. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49726. * Returns the updated direction.
  49727. * @param target The target the direction should point to
  49728. * @return The computed direction
  49729. */
  49730. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49731. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49732. return this.direction;
  49733. };
  49734. /**
  49735. * Returns the shadow generator associated to the light.
  49736. * @returns Always null for hemispheric lights because it does not support shadows.
  49737. */
  49738. HemisphericLight.prototype.getShadowGenerator = function () {
  49739. return null;
  49740. };
  49741. /**
  49742. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49743. * @param effect The effect to update
  49744. * @param lightIndex The index of the light in the effect to update
  49745. * @returns The hemispheric light
  49746. */
  49747. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49748. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49749. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49750. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49751. return this;
  49752. };
  49753. /**
  49754. * @hidden internal use only.
  49755. */
  49756. HemisphericLight.prototype._getWorldMatrix = function () {
  49757. if (!this._worldMatrix) {
  49758. this._worldMatrix = BABYLON.Matrix.Identity();
  49759. }
  49760. return this._worldMatrix;
  49761. };
  49762. /**
  49763. * Returns the integer 3.
  49764. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49765. */
  49766. HemisphericLight.prototype.getTypeID = function () {
  49767. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49768. };
  49769. __decorate([
  49770. BABYLON.serializeAsColor3()
  49771. ], HemisphericLight.prototype, "groundColor", void 0);
  49772. __decorate([
  49773. BABYLON.serializeAsVector3()
  49774. ], HemisphericLight.prototype, "direction", void 0);
  49775. return HemisphericLight;
  49776. }(BABYLON.Light));
  49777. BABYLON.HemisphericLight = HemisphericLight;
  49778. })(BABYLON || (BABYLON = {}));
  49779. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49780. var BABYLON;
  49781. (function (BABYLON) {
  49782. /**
  49783. * Base implementation IShadowLight
  49784. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49785. */
  49786. var ShadowLight = /** @class */ (function (_super) {
  49787. __extends(ShadowLight, _super);
  49788. function ShadowLight() {
  49789. var _this = _super !== null && _super.apply(this, arguments) || this;
  49790. _this._needProjectionMatrixCompute = true;
  49791. return _this;
  49792. }
  49793. ShadowLight.prototype._setPosition = function (value) {
  49794. this._position = value;
  49795. };
  49796. Object.defineProperty(ShadowLight.prototype, "position", {
  49797. /**
  49798. * Sets the position the shadow will be casted from. Also use as the light position for both
  49799. * point and spot lights.
  49800. */
  49801. get: function () {
  49802. return this._position;
  49803. },
  49804. /**
  49805. * Sets the position the shadow will be casted from. Also use as the light position for both
  49806. * point and spot lights.
  49807. */
  49808. set: function (value) {
  49809. this._setPosition(value);
  49810. },
  49811. enumerable: true,
  49812. configurable: true
  49813. });
  49814. ShadowLight.prototype._setDirection = function (value) {
  49815. this._direction = value;
  49816. };
  49817. Object.defineProperty(ShadowLight.prototype, "direction", {
  49818. /**
  49819. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49820. * Also use as the light direction on spot and directional lights.
  49821. */
  49822. get: function () {
  49823. return this._direction;
  49824. },
  49825. /**
  49826. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49827. * Also use as the light direction on spot and directional lights.
  49828. */
  49829. set: function (value) {
  49830. this._setDirection(value);
  49831. },
  49832. enumerable: true,
  49833. configurable: true
  49834. });
  49835. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49836. /**
  49837. * Gets the shadow projection clipping minimum z value.
  49838. */
  49839. get: function () {
  49840. return this._shadowMinZ;
  49841. },
  49842. /**
  49843. * Sets the shadow projection clipping minimum z value.
  49844. */
  49845. set: function (value) {
  49846. this._shadowMinZ = value;
  49847. this.forceProjectionMatrixCompute();
  49848. },
  49849. enumerable: true,
  49850. configurable: true
  49851. });
  49852. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49853. /**
  49854. * Sets the shadow projection clipping maximum z value.
  49855. */
  49856. get: function () {
  49857. return this._shadowMaxZ;
  49858. },
  49859. /**
  49860. * Gets the shadow projection clipping maximum z value.
  49861. */
  49862. set: function (value) {
  49863. this._shadowMaxZ = value;
  49864. this.forceProjectionMatrixCompute();
  49865. },
  49866. enumerable: true,
  49867. configurable: true
  49868. });
  49869. /**
  49870. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49871. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49872. */
  49873. ShadowLight.prototype.computeTransformedInformation = function () {
  49874. if (this.parent && this.parent.getWorldMatrix) {
  49875. if (!this.transformedPosition) {
  49876. this.transformedPosition = BABYLON.Vector3.Zero();
  49877. }
  49878. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49879. // In case the direction is present.
  49880. if (this.direction) {
  49881. if (!this.transformedDirection) {
  49882. this.transformedDirection = BABYLON.Vector3.Zero();
  49883. }
  49884. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49885. }
  49886. return true;
  49887. }
  49888. return false;
  49889. };
  49890. /**
  49891. * Return the depth scale used for the shadow map.
  49892. * @returns the depth scale.
  49893. */
  49894. ShadowLight.prototype.getDepthScale = function () {
  49895. return 50.0;
  49896. };
  49897. /**
  49898. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49899. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49900. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49901. */
  49902. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49903. return this.transformedDirection ? this.transformedDirection : this.direction;
  49904. };
  49905. /**
  49906. * Returns the ShadowLight absolute position in the World.
  49907. * @returns the position vector in world space
  49908. */
  49909. ShadowLight.prototype.getAbsolutePosition = function () {
  49910. return this.transformedPosition ? this.transformedPosition : this.position;
  49911. };
  49912. /**
  49913. * Sets the ShadowLight direction toward the passed target.
  49914. * @param target The point tot target in local space
  49915. * @returns the updated ShadowLight direction
  49916. */
  49917. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49918. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49919. return this.direction;
  49920. };
  49921. /**
  49922. * Returns the light rotation in euler definition.
  49923. * @returns the x y z rotation in local space.
  49924. */
  49925. ShadowLight.prototype.getRotation = function () {
  49926. this.direction.normalize();
  49927. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49928. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49929. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49930. };
  49931. /**
  49932. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49933. * @returns true if a cube texture needs to be use
  49934. */
  49935. ShadowLight.prototype.needCube = function () {
  49936. return false;
  49937. };
  49938. /**
  49939. * Detects if the projection matrix requires to be recomputed this frame.
  49940. * @returns true if it requires to be recomputed otherwise, false.
  49941. */
  49942. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49943. return this._needProjectionMatrixCompute;
  49944. };
  49945. /**
  49946. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49947. */
  49948. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49949. this._needProjectionMatrixCompute = true;
  49950. };
  49951. /**
  49952. * Get the world matrix of the sahdow lights.
  49953. * @hidden Internal Use Only
  49954. */
  49955. ShadowLight.prototype._getWorldMatrix = function () {
  49956. if (!this._worldMatrix) {
  49957. this._worldMatrix = BABYLON.Matrix.Identity();
  49958. }
  49959. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49960. return this._worldMatrix;
  49961. };
  49962. /**
  49963. * Gets the minZ used for shadow according to both the scene and the light.
  49964. * @param activeCamera The camera we are returning the min for
  49965. * @returns the depth min z
  49966. */
  49967. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49968. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49969. };
  49970. /**
  49971. * Gets the maxZ used for shadow according to both the scene and the light.
  49972. * @param activeCamera The camera we are returning the max for
  49973. * @returns the depth max z
  49974. */
  49975. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49976. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49977. };
  49978. /**
  49979. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49980. * @param matrix The materix to updated with the projection information
  49981. * @param viewMatrix The transform matrix of the light
  49982. * @param renderList The list of mesh to render in the map
  49983. * @returns The current light
  49984. */
  49985. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49986. if (this.customProjectionMatrixBuilder) {
  49987. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49988. }
  49989. else {
  49990. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49991. }
  49992. return this;
  49993. };
  49994. __decorate([
  49995. BABYLON.serializeAsVector3()
  49996. ], ShadowLight.prototype, "position", null);
  49997. __decorate([
  49998. BABYLON.serializeAsVector3()
  49999. ], ShadowLight.prototype, "direction", null);
  50000. __decorate([
  50001. BABYLON.serialize()
  50002. ], ShadowLight.prototype, "shadowMinZ", null);
  50003. __decorate([
  50004. BABYLON.serialize()
  50005. ], ShadowLight.prototype, "shadowMaxZ", null);
  50006. return ShadowLight;
  50007. }(BABYLON.Light));
  50008. BABYLON.ShadowLight = ShadowLight;
  50009. })(BABYLON || (BABYLON = {}));
  50010. //# sourceMappingURL=babylon.shadowLight.js.map
  50011. var BABYLON;
  50012. (function (BABYLON) {
  50013. /**
  50014. * A point light is a light defined by an unique point in world space.
  50015. * The light is emitted in every direction from this point.
  50016. * A good example of a point light is a standard light bulb.
  50017. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50018. */
  50019. var PointLight = /** @class */ (function (_super) {
  50020. __extends(PointLight, _super);
  50021. /**
  50022. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  50023. * A PointLight emits the light in every direction.
  50024. * It can cast shadows.
  50025. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  50026. * ```javascript
  50027. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  50028. * ```
  50029. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50030. * @param name The light friendly name
  50031. * @param position The position of the point light in the scene
  50032. * @param scene The scene the lights belongs to
  50033. */
  50034. function PointLight(name, position, scene) {
  50035. var _this = _super.call(this, name, scene) || this;
  50036. _this._shadowAngle = Math.PI / 2;
  50037. _this.position = position;
  50038. return _this;
  50039. }
  50040. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  50041. /**
  50042. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50043. * This specifies what angle the shadow will use to be created.
  50044. *
  50045. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  50046. */
  50047. get: function () {
  50048. return this._shadowAngle;
  50049. },
  50050. /**
  50051. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50052. * This specifies what angle the shadow will use to be created.
  50053. *
  50054. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  50055. */
  50056. set: function (value) {
  50057. this._shadowAngle = value;
  50058. this.forceProjectionMatrixCompute();
  50059. },
  50060. enumerable: true,
  50061. configurable: true
  50062. });
  50063. Object.defineProperty(PointLight.prototype, "direction", {
  50064. /**
  50065. * Gets the direction if it has been set.
  50066. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50067. */
  50068. get: function () {
  50069. return this._direction;
  50070. },
  50071. /**
  50072. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50073. */
  50074. set: function (value) {
  50075. var previousNeedCube = this.needCube();
  50076. this._direction = value;
  50077. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  50078. this._shadowGenerator.recreateShadowMap();
  50079. }
  50080. },
  50081. enumerable: true,
  50082. configurable: true
  50083. });
  50084. /**
  50085. * Returns the string "PointLight"
  50086. * @returns the class name
  50087. */
  50088. PointLight.prototype.getClassName = function () {
  50089. return "PointLight";
  50090. };
  50091. /**
  50092. * Returns the integer 0.
  50093. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50094. */
  50095. PointLight.prototype.getTypeID = function () {
  50096. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  50097. };
  50098. /**
  50099. * Specifies wether or not the shadowmap should be a cube texture.
  50100. * @returns true if the shadowmap needs to be a cube texture.
  50101. */
  50102. PointLight.prototype.needCube = function () {
  50103. return !this.direction;
  50104. };
  50105. /**
  50106. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  50107. * @param faceIndex The index of the face we are computed the direction to generate shadow
  50108. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  50109. */
  50110. PointLight.prototype.getShadowDirection = function (faceIndex) {
  50111. if (this.direction) {
  50112. return _super.prototype.getShadowDirection.call(this, faceIndex);
  50113. }
  50114. else {
  50115. switch (faceIndex) {
  50116. case 0:
  50117. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  50118. case 1:
  50119. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  50120. case 2:
  50121. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  50122. case 3:
  50123. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  50124. case 4:
  50125. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  50126. case 5:
  50127. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  50128. }
  50129. }
  50130. return BABYLON.Vector3.Zero();
  50131. };
  50132. /**
  50133. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  50134. * - fov = PI / 2
  50135. * - aspect ratio : 1.0
  50136. * - z-near and far equal to the active camera minZ and maxZ.
  50137. * Returns the PointLight.
  50138. */
  50139. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50140. var activeCamera = this.getScene().activeCamera;
  50141. if (!activeCamera) {
  50142. return;
  50143. }
  50144. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50145. };
  50146. PointLight.prototype._buildUniformLayout = function () {
  50147. this._uniformBuffer.addUniform("vLightData", 4);
  50148. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50149. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50150. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50151. this._uniformBuffer.addUniform("depthValues", 2);
  50152. this._uniformBuffer.create();
  50153. };
  50154. /**
  50155. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  50156. * @param effect The effect to update
  50157. * @param lightIndex The index of the light in the effect to update
  50158. * @returns The point light
  50159. */
  50160. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  50161. if (this.computeTransformedInformation()) {
  50162. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  50163. return this;
  50164. }
  50165. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  50166. return this;
  50167. };
  50168. __decorate([
  50169. BABYLON.serialize()
  50170. ], PointLight.prototype, "shadowAngle", null);
  50171. return PointLight;
  50172. }(BABYLON.ShadowLight));
  50173. BABYLON.PointLight = PointLight;
  50174. })(BABYLON || (BABYLON = {}));
  50175. //# sourceMappingURL=babylon.pointLight.js.map
  50176. var BABYLON;
  50177. (function (BABYLON) {
  50178. /**
  50179. * A directional light is defined by a direction (what a surprise!).
  50180. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  50181. * 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.
  50182. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50183. */
  50184. var DirectionalLight = /** @class */ (function (_super) {
  50185. __extends(DirectionalLight, _super);
  50186. /**
  50187. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  50188. * The directional light is emitted from everywhere in the given direction.
  50189. * It can cast shawdows.
  50190. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50191. * @param name The friendly name of the light
  50192. * @param direction The direction of the light
  50193. * @param scene The scene the light belongs to
  50194. */
  50195. function DirectionalLight(name, direction, scene) {
  50196. var _this = _super.call(this, name, scene) || this;
  50197. _this._shadowFrustumSize = 0;
  50198. _this._shadowOrthoScale = 0.1;
  50199. /**
  50200. * Automatically compute the projection matrix to best fit (including all the casters)
  50201. * on each frame.
  50202. */
  50203. _this.autoUpdateExtends = true;
  50204. // Cache
  50205. _this._orthoLeft = Number.MAX_VALUE;
  50206. _this._orthoRight = Number.MIN_VALUE;
  50207. _this._orthoTop = Number.MIN_VALUE;
  50208. _this._orthoBottom = Number.MAX_VALUE;
  50209. _this.position = direction.scale(-1.0);
  50210. _this.direction = direction;
  50211. return _this;
  50212. }
  50213. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  50214. /**
  50215. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  50216. */
  50217. get: function () {
  50218. return this._shadowFrustumSize;
  50219. },
  50220. /**
  50221. * Specifies a fix frustum size for the shadow generation.
  50222. */
  50223. set: function (value) {
  50224. this._shadowFrustumSize = value;
  50225. this.forceProjectionMatrixCompute();
  50226. },
  50227. enumerable: true,
  50228. configurable: true
  50229. });
  50230. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  50231. /**
  50232. * Gets the shadow projection scale against the optimal computed one.
  50233. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50234. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50235. */
  50236. get: function () {
  50237. return this._shadowOrthoScale;
  50238. },
  50239. /**
  50240. * Sets the shadow projection scale against the optimal computed one.
  50241. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50242. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50243. */
  50244. set: function (value) {
  50245. this._shadowOrthoScale = value;
  50246. this.forceProjectionMatrixCompute();
  50247. },
  50248. enumerable: true,
  50249. configurable: true
  50250. });
  50251. /**
  50252. * Returns the string "DirectionalLight".
  50253. * @return The class name
  50254. */
  50255. DirectionalLight.prototype.getClassName = function () {
  50256. return "DirectionalLight";
  50257. };
  50258. /**
  50259. * Returns the integer 1.
  50260. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50261. */
  50262. DirectionalLight.prototype.getTypeID = function () {
  50263. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  50264. };
  50265. /**
  50266. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  50267. * Returns the DirectionalLight Shadow projection matrix.
  50268. */
  50269. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50270. if (this.shadowFrustumSize > 0) {
  50271. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  50272. }
  50273. else {
  50274. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50275. }
  50276. };
  50277. /**
  50278. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  50279. * Returns the DirectionalLight Shadow projection matrix.
  50280. */
  50281. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  50282. var activeCamera = this.getScene().activeCamera;
  50283. if (!activeCamera) {
  50284. return;
  50285. }
  50286. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  50287. };
  50288. /**
  50289. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  50290. * Returns the DirectionalLight Shadow projection matrix.
  50291. */
  50292. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50293. var activeCamera = this.getScene().activeCamera;
  50294. if (!activeCamera) {
  50295. return;
  50296. }
  50297. // Check extends
  50298. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  50299. var tempVector3 = BABYLON.Vector3.Zero();
  50300. this._orthoLeft = Number.MAX_VALUE;
  50301. this._orthoRight = Number.MIN_VALUE;
  50302. this._orthoTop = Number.MIN_VALUE;
  50303. this._orthoBottom = Number.MAX_VALUE;
  50304. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  50305. var mesh = renderList[meshIndex];
  50306. if (!mesh) {
  50307. continue;
  50308. }
  50309. var boundingInfo = mesh.getBoundingInfo();
  50310. var boundingBox = boundingInfo.boundingBox;
  50311. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  50312. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  50313. if (tempVector3.x < this._orthoLeft)
  50314. this._orthoLeft = tempVector3.x;
  50315. if (tempVector3.y < this._orthoBottom)
  50316. this._orthoBottom = tempVector3.y;
  50317. if (tempVector3.x > this._orthoRight)
  50318. this._orthoRight = tempVector3.x;
  50319. if (tempVector3.y > this._orthoTop)
  50320. this._orthoTop = tempVector3.y;
  50321. }
  50322. }
  50323. }
  50324. var xOffset = this._orthoRight - this._orthoLeft;
  50325. var yOffset = this._orthoTop - this._orthoBottom;
  50326. 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);
  50327. };
  50328. DirectionalLight.prototype._buildUniformLayout = function () {
  50329. this._uniformBuffer.addUniform("vLightData", 4);
  50330. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50331. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50332. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50333. this._uniformBuffer.addUniform("depthValues", 2);
  50334. this._uniformBuffer.create();
  50335. };
  50336. /**
  50337. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  50338. * @param effect The effect to update
  50339. * @param lightIndex The index of the light in the effect to update
  50340. * @returns The directional light
  50341. */
  50342. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  50343. if (this.computeTransformedInformation()) {
  50344. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  50345. return this;
  50346. }
  50347. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  50348. return this;
  50349. };
  50350. /**
  50351. * Gets the minZ used for shadow according to both the scene and the light.
  50352. *
  50353. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50354. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50355. * @param activeCamera The camera we are returning the min for
  50356. * @returns the depth min z
  50357. */
  50358. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  50359. return 1;
  50360. };
  50361. /**
  50362. * Gets the maxZ used for shadow according to both the scene and the light.
  50363. *
  50364. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50365. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50366. * @param activeCamera The camera we are returning the max for
  50367. * @returns the depth max z
  50368. */
  50369. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  50370. return 1;
  50371. };
  50372. __decorate([
  50373. BABYLON.serialize()
  50374. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  50375. __decorate([
  50376. BABYLON.serialize()
  50377. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  50378. __decorate([
  50379. BABYLON.serialize()
  50380. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  50381. return DirectionalLight;
  50382. }(BABYLON.ShadowLight));
  50383. BABYLON.DirectionalLight = DirectionalLight;
  50384. })(BABYLON || (BABYLON = {}));
  50385. //# sourceMappingURL=babylon.directionalLight.js.map
  50386. var BABYLON;
  50387. (function (BABYLON) {
  50388. /**
  50389. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50390. * These values define a cone of light starting from the position, emitting toward the direction.
  50391. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50392. * and the exponent defines the speed of the decay of the light with distance (reach).
  50393. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50394. */
  50395. var SpotLight = /** @class */ (function (_super) {
  50396. __extends(SpotLight, _super);
  50397. /**
  50398. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50399. * It can cast shadows.
  50400. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50401. * @param name The light friendly name
  50402. * @param position The position of the spot light in the scene
  50403. * @param direction The direction of the light in the scene
  50404. * @param angle The cone angle of the light in Radians
  50405. * @param exponent The light decay speed with the distance from the emission spot
  50406. * @param scene The scene the lights belongs to
  50407. */
  50408. function SpotLight(name, position, direction, angle, exponent, scene) {
  50409. var _this = _super.call(this, name, scene) || this;
  50410. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50411. _this._projectionTextureLightNear = 1e-6;
  50412. _this._projectionTextureLightFar = 1000.0;
  50413. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50414. _this._projectionTextureViewLightDirty = true;
  50415. _this._projectionTextureProjectionLightDirty = true;
  50416. _this._projectionTextureDirty = true;
  50417. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50418. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50419. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50420. _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);
  50421. _this.position = position;
  50422. _this.direction = direction;
  50423. _this.angle = angle;
  50424. _this.exponent = exponent;
  50425. return _this;
  50426. }
  50427. Object.defineProperty(SpotLight.prototype, "angle", {
  50428. /**
  50429. * Gets the cone angle of the spot light in Radians.
  50430. */
  50431. get: function () {
  50432. return this._angle;
  50433. },
  50434. /**
  50435. * Sets the cone angle of the spot light in Radians.
  50436. */
  50437. set: function (value) {
  50438. this._angle = value;
  50439. this._projectionTextureProjectionLightDirty = true;
  50440. this.forceProjectionMatrixCompute();
  50441. },
  50442. enumerable: true,
  50443. configurable: true
  50444. });
  50445. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50446. /**
  50447. * Allows scaling the angle of the light for shadow generation only.
  50448. */
  50449. get: function () {
  50450. return this._shadowAngleScale;
  50451. },
  50452. /**
  50453. * Allows scaling the angle of the light for shadow generation only.
  50454. */
  50455. set: function (value) {
  50456. this._shadowAngleScale = value;
  50457. this.forceProjectionMatrixCompute();
  50458. },
  50459. enumerable: true,
  50460. configurable: true
  50461. });
  50462. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50463. /**
  50464. * Allows reading the projecton texture
  50465. */
  50466. get: function () {
  50467. return this._projectionTextureMatrix;
  50468. },
  50469. enumerable: true,
  50470. configurable: true
  50471. });
  50472. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50473. /**
  50474. * Gets the near clip of the Spotlight for texture projection.
  50475. */
  50476. get: function () {
  50477. return this._projectionTextureLightNear;
  50478. },
  50479. /**
  50480. * Sets the near clip of the Spotlight for texture projection.
  50481. */
  50482. set: function (value) {
  50483. this._projectionTextureLightNear = value;
  50484. this._projectionTextureProjectionLightDirty = true;
  50485. },
  50486. enumerable: true,
  50487. configurable: true
  50488. });
  50489. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50490. /**
  50491. * Gets the far clip of the Spotlight for texture projection.
  50492. */
  50493. get: function () {
  50494. return this._projectionTextureLightFar;
  50495. },
  50496. /**
  50497. * Sets the far clip of the Spotlight for texture projection.
  50498. */
  50499. set: function (value) {
  50500. this._projectionTextureLightFar = value;
  50501. this._projectionTextureProjectionLightDirty = true;
  50502. },
  50503. enumerable: true,
  50504. configurable: true
  50505. });
  50506. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50507. /**
  50508. * Gets the Up vector of the Spotlight for texture projection.
  50509. */
  50510. get: function () {
  50511. return this._projectionTextureUpDirection;
  50512. },
  50513. /**
  50514. * Sets the Up vector of the Spotlight for texture projection.
  50515. */
  50516. set: function (value) {
  50517. this._projectionTextureUpDirection = value;
  50518. this._projectionTextureProjectionLightDirty = true;
  50519. },
  50520. enumerable: true,
  50521. configurable: true
  50522. });
  50523. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50524. /**
  50525. * Gets the projection texture of the light.
  50526. */
  50527. get: function () {
  50528. return this._projectionTexture;
  50529. },
  50530. /**
  50531. * Sets the projection texture of the light.
  50532. */
  50533. set: function (value) {
  50534. this._projectionTexture = value;
  50535. this._projectionTextureDirty = true;
  50536. },
  50537. enumerable: true,
  50538. configurable: true
  50539. });
  50540. /**
  50541. * Returns the string "SpotLight".
  50542. * @returns the class name
  50543. */
  50544. SpotLight.prototype.getClassName = function () {
  50545. return "SpotLight";
  50546. };
  50547. /**
  50548. * Returns the integer 2.
  50549. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50550. */
  50551. SpotLight.prototype.getTypeID = function () {
  50552. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50553. };
  50554. /**
  50555. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50556. */
  50557. SpotLight.prototype._setDirection = function (value) {
  50558. _super.prototype._setDirection.call(this, value);
  50559. this._projectionTextureViewLightDirty = true;
  50560. };
  50561. /**
  50562. * Overrides the position setter to recompute the projection texture view light Matrix.
  50563. */
  50564. SpotLight.prototype._setPosition = function (value) {
  50565. _super.prototype._setPosition.call(this, value);
  50566. this._projectionTextureViewLightDirty = true;
  50567. };
  50568. /**
  50569. * 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.
  50570. * Returns the SpotLight.
  50571. */
  50572. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50573. var activeCamera = this.getScene().activeCamera;
  50574. if (!activeCamera) {
  50575. return;
  50576. }
  50577. this._shadowAngleScale = this._shadowAngleScale || 1;
  50578. var angle = this._shadowAngleScale * this._angle;
  50579. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50580. };
  50581. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50582. this._projectionTextureViewLightDirty = false;
  50583. this._projectionTextureDirty = true;
  50584. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50585. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50586. };
  50587. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50588. this._projectionTextureProjectionLightDirty = false;
  50589. this._projectionTextureDirty = true;
  50590. var light_far = this.projectionTextureLightFar;
  50591. var light_near = this.projectionTextureLightNear;
  50592. var P = light_far / (light_far - light_near);
  50593. var Q = -P * light_near;
  50594. var S = 1.0 / Math.tan(this._angle / 2.0);
  50595. var A = 1.0;
  50596. 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);
  50597. };
  50598. /**
  50599. * Main function for light texture projection matrix computing.
  50600. */
  50601. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50602. this._projectionTextureDirty = false;
  50603. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50604. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50605. };
  50606. SpotLight.prototype._buildUniformLayout = function () {
  50607. this._uniformBuffer.addUniform("vLightData", 4);
  50608. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50609. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50610. this._uniformBuffer.addUniform("vLightDirection", 3);
  50611. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50612. this._uniformBuffer.addUniform("depthValues", 2);
  50613. this._uniformBuffer.create();
  50614. };
  50615. /**
  50616. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50617. * @param effect The effect to update
  50618. * @param lightIndex The index of the light in the effect to update
  50619. * @returns The spot light
  50620. */
  50621. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50622. var normalizeDirection;
  50623. if (this.computeTransformedInformation()) {
  50624. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50625. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50626. }
  50627. else {
  50628. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50629. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50630. }
  50631. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50632. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50633. if (this._projectionTextureViewLightDirty) {
  50634. this._computeProjectionTextureViewLightMatrix();
  50635. }
  50636. if (this._projectionTextureProjectionLightDirty) {
  50637. this._computeProjectionTextureProjectionLightMatrix();
  50638. }
  50639. if (this._projectionTextureDirty) {
  50640. this._computeProjectionTextureMatrix();
  50641. }
  50642. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50643. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50644. }
  50645. return this;
  50646. };
  50647. /**
  50648. * Disposes the light and the associated resources.
  50649. */
  50650. SpotLight.prototype.dispose = function () {
  50651. _super.prototype.dispose.call(this);
  50652. if (this._projectionTexture) {
  50653. this._projectionTexture.dispose();
  50654. }
  50655. };
  50656. __decorate([
  50657. BABYLON.serialize()
  50658. ], SpotLight.prototype, "angle", null);
  50659. __decorate([
  50660. BABYLON.serialize()
  50661. ], SpotLight.prototype, "shadowAngleScale", null);
  50662. __decorate([
  50663. BABYLON.serialize()
  50664. ], SpotLight.prototype, "exponent", void 0);
  50665. __decorate([
  50666. BABYLON.serialize()
  50667. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50668. __decorate([
  50669. BABYLON.serialize()
  50670. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50671. __decorate([
  50672. BABYLON.serialize()
  50673. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50674. __decorate([
  50675. BABYLON.serializeAsTexture("projectedLightTexture")
  50676. ], SpotLight.prototype, "_projectionTexture", void 0);
  50677. return SpotLight;
  50678. }(BABYLON.ShadowLight));
  50679. BABYLON.SpotLight = SpotLight;
  50680. })(BABYLON || (BABYLON = {}));
  50681. //# sourceMappingURL=babylon.spotLight.js.map
  50682. var BABYLON;
  50683. (function (BABYLON) {
  50684. /**
  50685. * Class used to override all child animations of a given target
  50686. */
  50687. var AnimationPropertiesOverride = /** @class */ (function () {
  50688. function AnimationPropertiesOverride() {
  50689. /**
  50690. * Gets or sets a value indicating if animation blending must be used
  50691. */
  50692. this.enableBlending = false;
  50693. /**
  50694. * Gets or sets the blending speed to use when enableBlending is true
  50695. */
  50696. this.blendingSpeed = 0.01;
  50697. /**
  50698. * Gets or sets the default loop mode to use
  50699. */
  50700. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50701. }
  50702. return AnimationPropertiesOverride;
  50703. }());
  50704. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50705. })(BABYLON || (BABYLON = {}));
  50706. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50707. var BABYLON;
  50708. (function (BABYLON) {
  50709. /**
  50710. * Represents the range of an animation
  50711. */
  50712. var AnimationRange = /** @class */ (function () {
  50713. /**
  50714. * Initializes the range of an animation
  50715. * @param name The name of the animation range
  50716. * @param from The starting frame of the animation
  50717. * @param to The ending frame of the animation
  50718. */
  50719. function AnimationRange(
  50720. /**The name of the animation range**/
  50721. name,
  50722. /**The starting frame of the animation */
  50723. from,
  50724. /**The ending frame of the animation*/
  50725. to) {
  50726. this.name = name;
  50727. this.from = from;
  50728. this.to = to;
  50729. }
  50730. /**
  50731. * Makes a copy of the animation range
  50732. * @returns A copy of the animation range
  50733. */
  50734. AnimationRange.prototype.clone = function () {
  50735. return new AnimationRange(this.name, this.from, this.to);
  50736. };
  50737. return AnimationRange;
  50738. }());
  50739. BABYLON.AnimationRange = AnimationRange;
  50740. /**
  50741. * Composed of a frame, and an action function
  50742. */
  50743. var AnimationEvent = /** @class */ (function () {
  50744. /**
  50745. * Initializes the animation event
  50746. * @param frame The frame for which the event is triggered
  50747. * @param action The event to perform when triggered
  50748. * @param onlyOnce Specifies if the event should be triggered only once
  50749. */
  50750. function AnimationEvent(
  50751. /** The frame for which the event is triggered **/
  50752. frame,
  50753. /** The event to perform when triggered **/
  50754. action,
  50755. /** Specifies if the event should be triggered only once**/
  50756. onlyOnce) {
  50757. this.frame = frame;
  50758. this.action = action;
  50759. this.onlyOnce = onlyOnce;
  50760. /**
  50761. * Specifies if the animation event is done
  50762. */
  50763. this.isDone = false;
  50764. }
  50765. /** @hidden */
  50766. AnimationEvent.prototype._clone = function () {
  50767. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50768. };
  50769. return AnimationEvent;
  50770. }());
  50771. BABYLON.AnimationEvent = AnimationEvent;
  50772. /**
  50773. * A cursor which tracks a point on a path
  50774. */
  50775. var PathCursor = /** @class */ (function () {
  50776. /**
  50777. * Initializes the path cursor
  50778. * @param path The path to track
  50779. */
  50780. function PathCursor(path) {
  50781. this.path = path;
  50782. /**
  50783. * Stores path cursor callbacks for when an onchange event is triggered
  50784. */
  50785. this._onchange = new Array();
  50786. /**
  50787. * The value of the path cursor
  50788. */
  50789. this.value = 0;
  50790. /**
  50791. * The animation array of the path cursor
  50792. */
  50793. this.animations = new Array();
  50794. }
  50795. /**
  50796. * Gets the cursor point on the path
  50797. * @returns A point on the path cursor at the cursor location
  50798. */
  50799. PathCursor.prototype.getPoint = function () {
  50800. var point = this.path.getPointAtLengthPosition(this.value);
  50801. return new BABYLON.Vector3(point.x, 0, point.y);
  50802. };
  50803. /**
  50804. * Moves the cursor ahead by the step amount
  50805. * @param step The amount to move the cursor forward
  50806. * @returns This path cursor
  50807. */
  50808. PathCursor.prototype.moveAhead = function (step) {
  50809. if (step === void 0) { step = 0.002; }
  50810. this.move(step);
  50811. return this;
  50812. };
  50813. /**
  50814. * Moves the cursor behind by the step amount
  50815. * @param step The amount to move the cursor back
  50816. * @returns This path cursor
  50817. */
  50818. PathCursor.prototype.moveBack = function (step) {
  50819. if (step === void 0) { step = 0.002; }
  50820. this.move(-step);
  50821. return this;
  50822. };
  50823. /**
  50824. * Moves the cursor by the step amount
  50825. * If the step amount is greater than one, an exception is thrown
  50826. * @param step The amount to move the cursor
  50827. * @returns This path cursor
  50828. */
  50829. PathCursor.prototype.move = function (step) {
  50830. if (Math.abs(step) > 1) {
  50831. throw "step size should be less than 1.";
  50832. }
  50833. this.value += step;
  50834. this.ensureLimits();
  50835. this.raiseOnChange();
  50836. return this;
  50837. };
  50838. /**
  50839. * Ensures that the value is limited between zero and one
  50840. * @returns This path cursor
  50841. */
  50842. PathCursor.prototype.ensureLimits = function () {
  50843. while (this.value > 1) {
  50844. this.value -= 1;
  50845. }
  50846. while (this.value < 0) {
  50847. this.value += 1;
  50848. }
  50849. return this;
  50850. };
  50851. /**
  50852. * Runs onchange callbacks on change (used by the animation engine)
  50853. * @returns This path cursor
  50854. */
  50855. PathCursor.prototype.raiseOnChange = function () {
  50856. var _this = this;
  50857. this._onchange.forEach(function (f) { return f(_this); });
  50858. return this;
  50859. };
  50860. /**
  50861. * Executes a function on change
  50862. * @param f A path cursor onchange callback
  50863. * @returns This path cursor
  50864. */
  50865. PathCursor.prototype.onchange = function (f) {
  50866. this._onchange.push(f);
  50867. return this;
  50868. };
  50869. return PathCursor;
  50870. }());
  50871. BABYLON.PathCursor = PathCursor;
  50872. /**
  50873. * Enum for the animation key frame interpolation type
  50874. */
  50875. var AnimationKeyInterpolation;
  50876. (function (AnimationKeyInterpolation) {
  50877. /**
  50878. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50879. */
  50880. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50881. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50882. /**
  50883. * Class used to store any kind of animation
  50884. */
  50885. var Animation = /** @class */ (function () {
  50886. /**
  50887. * Initializes the animation
  50888. * @param name Name of the animation
  50889. * @param targetProperty Property to animate
  50890. * @param framePerSecond The frames per second of the animation
  50891. * @param dataType The data type of the animation
  50892. * @param loopMode The loop mode of the animation
  50893. * @param enableBlendings Specifies if blending should be enabled
  50894. */
  50895. function Animation(
  50896. /**Name of the animation */
  50897. name,
  50898. /**Property to animate */
  50899. targetProperty,
  50900. /**The frames per second of the animation */
  50901. framePerSecond,
  50902. /**The data type of the animation */
  50903. dataType,
  50904. /**The loop mode of the animation */
  50905. loopMode,
  50906. /**Specifies if blending should be enabled */
  50907. enableBlending) {
  50908. this.name = name;
  50909. this.targetProperty = targetProperty;
  50910. this.framePerSecond = framePerSecond;
  50911. this.dataType = dataType;
  50912. this.loopMode = loopMode;
  50913. this.enableBlending = enableBlending;
  50914. /**
  50915. * @hidden Internal use only
  50916. */
  50917. this._runtimeAnimations = new Array();
  50918. /**
  50919. * The set of event that will be linked to this animation
  50920. */
  50921. this._events = new Array();
  50922. /**
  50923. * Stores the blending speed of the animation
  50924. */
  50925. this.blendingSpeed = 0.01;
  50926. /**
  50927. * Stores the animation ranges for the animation
  50928. */
  50929. this._ranges = {};
  50930. this.targetPropertyPath = targetProperty.split(".");
  50931. this.dataType = dataType;
  50932. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50933. }
  50934. /**
  50935. * @hidden Internal use
  50936. */
  50937. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50938. var dataType = undefined;
  50939. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50940. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50941. }
  50942. else if (from instanceof BABYLON.Quaternion) {
  50943. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50944. }
  50945. else if (from instanceof BABYLON.Vector3) {
  50946. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50947. }
  50948. else if (from instanceof BABYLON.Vector2) {
  50949. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50950. }
  50951. else if (from instanceof BABYLON.Color3) {
  50952. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50953. }
  50954. else if (from instanceof BABYLON.Size) {
  50955. dataType = Animation.ANIMATIONTYPE_SIZE;
  50956. }
  50957. if (dataType == undefined) {
  50958. return null;
  50959. }
  50960. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50961. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50962. animation.setKeys(keys);
  50963. if (easingFunction !== undefined) {
  50964. animation.setEasingFunction(easingFunction);
  50965. }
  50966. return animation;
  50967. };
  50968. /**
  50969. * Sets up an animation
  50970. * @param property The property to animate
  50971. * @param animationType The animation type to apply
  50972. * @param framePerSecond The frames per second of the animation
  50973. * @param easingFunction The easing function used in the animation
  50974. * @returns The created animation
  50975. */
  50976. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50977. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50978. animation.setEasingFunction(easingFunction);
  50979. return animation;
  50980. };
  50981. /**
  50982. * Create and start an animation on a node
  50983. * @param name defines the name of the global animation that will be run on all nodes
  50984. * @param node defines the root node where the animation will take place
  50985. * @param targetProperty defines property to animate
  50986. * @param framePerSecond defines the number of frame per second yo use
  50987. * @param totalFrame defines the number of frames in total
  50988. * @param from defines the initial value
  50989. * @param to defines the final value
  50990. * @param loopMode defines which loop mode you want to use (off by default)
  50991. * @param easingFunction defines the easing function to use (linear by default)
  50992. * @param onAnimationEnd defines the callback to call when animation end
  50993. * @returns the animatable created for this animation
  50994. */
  50995. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50996. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50997. if (!animation) {
  50998. return null;
  50999. }
  51000. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  51001. };
  51002. /**
  51003. * Create and start an animation on a node and its descendants
  51004. * @param name defines the name of the global animation that will be run on all nodes
  51005. * @param node defines the root node where the animation will take place
  51006. * @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
  51007. * @param targetProperty defines property to animate
  51008. * @param framePerSecond defines the number of frame per second to use
  51009. * @param totalFrame defines the number of frames in total
  51010. * @param from defines the initial value
  51011. * @param to defines the final value
  51012. * @param loopMode defines which loop mode you want to use (off by default)
  51013. * @param easingFunction defines the easing function to use (linear by default)
  51014. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  51015. * @returns the list of animatables created for all nodes
  51016. * @example https://www.babylonjs-playground.com/#MH0VLI
  51017. */
  51018. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  51019. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  51020. if (!animation) {
  51021. return null;
  51022. }
  51023. var scene = node.getScene();
  51024. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  51025. };
  51026. /**
  51027. * Creates a new animation, merges it with the existing animations and starts it
  51028. * @param name Name of the animation
  51029. * @param node Node which contains the scene that begins the animations
  51030. * @param targetProperty Specifies which property to animate
  51031. * @param framePerSecond The frames per second of the animation
  51032. * @param totalFrame The total number of frames
  51033. * @param from The frame at the beginning of the animation
  51034. * @param to The frame at the end of the animation
  51035. * @param loopMode Specifies the loop mode of the animation
  51036. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  51037. * @param onAnimationEnd Callback to run once the animation is complete
  51038. * @returns Nullable animation
  51039. */
  51040. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  51041. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  51042. if (!animation) {
  51043. return null;
  51044. }
  51045. node.animations.push(animation);
  51046. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  51047. };
  51048. /**
  51049. * Transition property of an host to the target Value
  51050. * @param property The property to transition
  51051. * @param targetValue The target Value of the property
  51052. * @param host The object where the property to animate belongs
  51053. * @param scene Scene used to run the animation
  51054. * @param frameRate Framerate (in frame/s) to use
  51055. * @param transition The transition type we want to use
  51056. * @param duration The duration of the animation, in milliseconds
  51057. * @param onAnimationEnd Callback trigger at the end of the animation
  51058. * @returns Nullable animation
  51059. */
  51060. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  51061. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  51062. if (duration <= 0) {
  51063. host[property] = targetValue;
  51064. if (onAnimationEnd) {
  51065. onAnimationEnd();
  51066. }
  51067. return null;
  51068. }
  51069. var endFrame = frameRate * (duration / 1000);
  51070. transition.setKeys([{
  51071. frame: 0,
  51072. value: host[property].clone ? host[property].clone() : host[property]
  51073. },
  51074. {
  51075. frame: endFrame,
  51076. value: targetValue
  51077. }]);
  51078. if (!host.animations) {
  51079. host.animations = [];
  51080. }
  51081. host.animations.push(transition);
  51082. var animation = scene.beginAnimation(host, 0, endFrame, false);
  51083. animation.onAnimationEnd = onAnimationEnd;
  51084. return animation;
  51085. };
  51086. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  51087. /**
  51088. * Return the array of runtime animations currently using this animation
  51089. */
  51090. get: function () {
  51091. return this._runtimeAnimations;
  51092. },
  51093. enumerable: true,
  51094. configurable: true
  51095. });
  51096. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  51097. /**
  51098. * Specifies if any of the runtime animations are currently running
  51099. */
  51100. get: function () {
  51101. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  51102. var runtimeAnimation = _a[_i];
  51103. if (!runtimeAnimation.isStopped) {
  51104. return true;
  51105. }
  51106. }
  51107. return false;
  51108. },
  51109. enumerable: true,
  51110. configurable: true
  51111. });
  51112. // Methods
  51113. /**
  51114. * Converts the animation to a string
  51115. * @param fullDetails support for multiple levels of logging within scene loading
  51116. * @returns String form of the animation
  51117. */
  51118. Animation.prototype.toString = function (fullDetails) {
  51119. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  51120. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  51121. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  51122. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  51123. if (fullDetails) {
  51124. ret += ", Ranges: {";
  51125. var first = true;
  51126. for (var name in this._ranges) {
  51127. if (first) {
  51128. ret += ", ";
  51129. first = false;
  51130. }
  51131. ret += name;
  51132. }
  51133. ret += "}";
  51134. }
  51135. return ret;
  51136. };
  51137. /**
  51138. * Add an event to this animation
  51139. * @param event Event to add
  51140. */
  51141. Animation.prototype.addEvent = function (event) {
  51142. this._events.push(event);
  51143. };
  51144. /**
  51145. * Remove all events found at the given frame
  51146. * @param frame The frame to remove events from
  51147. */
  51148. Animation.prototype.removeEvents = function (frame) {
  51149. for (var index = 0; index < this._events.length; index++) {
  51150. if (this._events[index].frame === frame) {
  51151. this._events.splice(index, 1);
  51152. index--;
  51153. }
  51154. }
  51155. };
  51156. /**
  51157. * Retrieves all the events from the animation
  51158. * @returns Events from the animation
  51159. */
  51160. Animation.prototype.getEvents = function () {
  51161. return this._events;
  51162. };
  51163. /**
  51164. * Creates an animation range
  51165. * @param name Name of the animation range
  51166. * @param from Starting frame of the animation range
  51167. * @param to Ending frame of the animation
  51168. */
  51169. Animation.prototype.createRange = function (name, from, to) {
  51170. // check name not already in use; could happen for bones after serialized
  51171. if (!this._ranges[name]) {
  51172. this._ranges[name] = new AnimationRange(name, from, to);
  51173. }
  51174. };
  51175. /**
  51176. * Deletes an animation range by name
  51177. * @param name Name of the animation range to delete
  51178. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  51179. */
  51180. Animation.prototype.deleteRange = function (name, deleteFrames) {
  51181. if (deleteFrames === void 0) { deleteFrames = true; }
  51182. var range = this._ranges[name];
  51183. if (!range) {
  51184. return;
  51185. }
  51186. if (deleteFrames) {
  51187. var from = range.from;
  51188. var to = range.to;
  51189. // this loop MUST go high to low for multiple splices to work
  51190. for (var key = this._keys.length - 1; key >= 0; key--) {
  51191. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  51192. this._keys.splice(key, 1);
  51193. }
  51194. }
  51195. }
  51196. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  51197. };
  51198. /**
  51199. * Gets the animation range by name, or null if not defined
  51200. * @param name Name of the animation range
  51201. * @returns Nullable animation range
  51202. */
  51203. Animation.prototype.getRange = function (name) {
  51204. return this._ranges[name];
  51205. };
  51206. /**
  51207. * Gets the key frames from the animation
  51208. * @returns The key frames of the animation
  51209. */
  51210. Animation.prototype.getKeys = function () {
  51211. return this._keys;
  51212. };
  51213. /**
  51214. * Gets the highest frame rate of the animation
  51215. * @returns Highest frame rate of the animation
  51216. */
  51217. Animation.prototype.getHighestFrame = function () {
  51218. var ret = 0;
  51219. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  51220. if (ret < this._keys[key].frame) {
  51221. ret = this._keys[key].frame;
  51222. }
  51223. }
  51224. return ret;
  51225. };
  51226. /**
  51227. * Gets the easing function of the animation
  51228. * @returns Easing function of the animation
  51229. */
  51230. Animation.prototype.getEasingFunction = function () {
  51231. return this._easingFunction;
  51232. };
  51233. /**
  51234. * Sets the easing function of the animation
  51235. * @param easingFunction A custom mathematical formula for animation
  51236. */
  51237. Animation.prototype.setEasingFunction = function (easingFunction) {
  51238. this._easingFunction = easingFunction;
  51239. };
  51240. /**
  51241. * Interpolates a scalar linearly
  51242. * @param startValue Start value of the animation curve
  51243. * @param endValue End value of the animation curve
  51244. * @param gradient Scalar amount to interpolate
  51245. * @returns Interpolated scalar value
  51246. */
  51247. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  51248. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  51249. };
  51250. /**
  51251. * Interpolates a scalar cubically
  51252. * @param startValue Start value of the animation curve
  51253. * @param outTangent End tangent of the animation
  51254. * @param endValue End value of the animation curve
  51255. * @param inTangent Start tangent of the animation curve
  51256. * @param gradient Scalar amount to interpolate
  51257. * @returns Interpolated scalar value
  51258. */
  51259. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51260. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51261. };
  51262. /**
  51263. * Interpolates a quaternion using a spherical linear interpolation
  51264. * @param startValue Start value of the animation curve
  51265. * @param endValue End value of the animation curve
  51266. * @param gradient Scalar amount to interpolate
  51267. * @returns Interpolated quaternion value
  51268. */
  51269. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  51270. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  51271. };
  51272. /**
  51273. * Interpolates a quaternion cubically
  51274. * @param startValue Start value of the animation curve
  51275. * @param outTangent End tangent of the animation curve
  51276. * @param endValue End value of the animation curve
  51277. * @param inTangent Start tangent of the animation curve
  51278. * @param gradient Scalar amount to interpolate
  51279. * @returns Interpolated quaternion value
  51280. */
  51281. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51282. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  51283. };
  51284. /**
  51285. * Interpolates a Vector3 linearl
  51286. * @param startValue Start value of the animation curve
  51287. * @param endValue End value of the animation curve
  51288. * @param gradient Scalar amount to interpolate
  51289. * @returns Interpolated scalar value
  51290. */
  51291. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  51292. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  51293. };
  51294. /**
  51295. * Interpolates a Vector3 cubically
  51296. * @param startValue Start value of the animation curve
  51297. * @param outTangent End tangent of the animation
  51298. * @param endValue End value of the animation curve
  51299. * @param inTangent Start tangent of the animation curve
  51300. * @param gradient Scalar amount to interpolate
  51301. * @returns InterpolatedVector3 value
  51302. */
  51303. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51304. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51305. };
  51306. /**
  51307. * Interpolates a Vector2 linearly
  51308. * @param startValue Start value of the animation curve
  51309. * @param endValue End value of the animation curve
  51310. * @param gradient Scalar amount to interpolate
  51311. * @returns Interpolated Vector2 value
  51312. */
  51313. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  51314. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  51315. };
  51316. /**
  51317. * Interpolates a Vector2 cubically
  51318. * @param startValue Start value of the animation curve
  51319. * @param outTangent End tangent of the animation
  51320. * @param endValue End value of the animation curve
  51321. * @param inTangent Start tangent of the animation curve
  51322. * @param gradient Scalar amount to interpolate
  51323. * @returns Interpolated Vector2 value
  51324. */
  51325. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51326. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51327. };
  51328. /**
  51329. * Interpolates a size linearly
  51330. * @param startValue Start value of the animation curve
  51331. * @param endValue End value of the animation curve
  51332. * @param gradient Scalar amount to interpolate
  51333. * @returns Interpolated Size value
  51334. */
  51335. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  51336. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  51337. };
  51338. /**
  51339. * Interpolates a Color3 linearly
  51340. * @param startValue Start value of the animation curve
  51341. * @param endValue End value of the animation curve
  51342. * @param gradient Scalar amount to interpolate
  51343. * @returns Interpolated Color3 value
  51344. */
  51345. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  51346. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  51347. };
  51348. /**
  51349. * @hidden Internal use only
  51350. */
  51351. Animation.prototype._getKeyValue = function (value) {
  51352. if (typeof value === "function") {
  51353. return value();
  51354. }
  51355. return value;
  51356. };
  51357. /**
  51358. * @hidden Internal use only
  51359. */
  51360. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  51361. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  51362. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  51363. }
  51364. var keys = this.getKeys();
  51365. // Try to get a hash to find the right key
  51366. 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));
  51367. if (keys[startKeyIndex].frame >= currentFrame) {
  51368. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  51369. startKeyIndex--;
  51370. }
  51371. }
  51372. for (var key = startKeyIndex; key < keys.length; key++) {
  51373. var endKey = keys[key + 1];
  51374. if (endKey.frame >= currentFrame) {
  51375. var startKey = keys[key];
  51376. var startValue = this._getKeyValue(startKey.value);
  51377. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51378. return startValue;
  51379. }
  51380. var endValue = this._getKeyValue(endKey.value);
  51381. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51382. var frameDelta = endKey.frame - startKey.frame;
  51383. // gradient : percent of currentFrame between the frame inf and the frame sup
  51384. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51385. // check for easingFunction and correction of gradient
  51386. var easingFunction = this.getEasingFunction();
  51387. if (easingFunction != null) {
  51388. gradient = easingFunction.ease(gradient);
  51389. }
  51390. switch (this.dataType) {
  51391. // Float
  51392. case Animation.ANIMATIONTYPE_FLOAT:
  51393. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51394. switch (loopMode) {
  51395. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51396. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51397. return floatValue;
  51398. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51399. return offsetValue * repeatCount + floatValue;
  51400. }
  51401. break;
  51402. // Quaternion
  51403. case Animation.ANIMATIONTYPE_QUATERNION:
  51404. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51405. switch (loopMode) {
  51406. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51407. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51408. return quatValue;
  51409. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51410. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51411. }
  51412. return quatValue;
  51413. // Vector3
  51414. case Animation.ANIMATIONTYPE_VECTOR3:
  51415. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51416. switch (loopMode) {
  51417. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51418. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51419. return vec3Value;
  51420. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51421. return vec3Value.add(offsetValue.scale(repeatCount));
  51422. }
  51423. // Vector2
  51424. case Animation.ANIMATIONTYPE_VECTOR2:
  51425. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51426. switch (loopMode) {
  51427. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51428. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51429. return vec2Value;
  51430. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51431. return vec2Value.add(offsetValue.scale(repeatCount));
  51432. }
  51433. // Size
  51434. case Animation.ANIMATIONTYPE_SIZE:
  51435. switch (loopMode) {
  51436. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51437. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51438. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51439. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51440. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51441. }
  51442. // Color3
  51443. case Animation.ANIMATIONTYPE_COLOR3:
  51444. switch (loopMode) {
  51445. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51446. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51447. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51448. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51449. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51450. }
  51451. // Matrix
  51452. case Animation.ANIMATIONTYPE_MATRIX:
  51453. switch (loopMode) {
  51454. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51455. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51456. if (Animation.AllowMatricesInterpolation) {
  51457. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51458. }
  51459. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51460. return startValue;
  51461. }
  51462. default:
  51463. break;
  51464. }
  51465. break;
  51466. }
  51467. }
  51468. return this._getKeyValue(keys[keys.length - 1].value);
  51469. };
  51470. /**
  51471. * Defines the function to use to interpolate matrices
  51472. * @param startValue defines the start matrix
  51473. * @param endValue defines the end matrix
  51474. * @param gradient defines the gradient between both matrices
  51475. * @param result defines an optional target matrix where to store the interpolation
  51476. * @returns the interpolated matrix
  51477. */
  51478. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51479. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51480. if (result) {
  51481. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51482. return result;
  51483. }
  51484. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51485. }
  51486. if (result) {
  51487. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51488. return result;
  51489. }
  51490. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51491. };
  51492. /**
  51493. * Makes a copy of the animation
  51494. * @returns Cloned animation
  51495. */
  51496. Animation.prototype.clone = function () {
  51497. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51498. clone.enableBlending = this.enableBlending;
  51499. clone.blendingSpeed = this.blendingSpeed;
  51500. if (this._keys) {
  51501. clone.setKeys(this._keys);
  51502. }
  51503. if (this._ranges) {
  51504. clone._ranges = {};
  51505. for (var name in this._ranges) {
  51506. var range = this._ranges[name];
  51507. if (!range) {
  51508. continue;
  51509. }
  51510. clone._ranges[name] = range.clone();
  51511. }
  51512. }
  51513. return clone;
  51514. };
  51515. /**
  51516. * Sets the key frames of the animation
  51517. * @param values The animation key frames to set
  51518. */
  51519. Animation.prototype.setKeys = function (values) {
  51520. this._keys = values.slice(0);
  51521. };
  51522. /**
  51523. * Serializes the animation to an object
  51524. * @returns Serialized object
  51525. */
  51526. Animation.prototype.serialize = function () {
  51527. var serializationObject = {};
  51528. serializationObject.name = this.name;
  51529. serializationObject.property = this.targetProperty;
  51530. serializationObject.framePerSecond = this.framePerSecond;
  51531. serializationObject.dataType = this.dataType;
  51532. serializationObject.loopBehavior = this.loopMode;
  51533. serializationObject.enableBlending = this.enableBlending;
  51534. serializationObject.blendingSpeed = this.blendingSpeed;
  51535. var dataType = this.dataType;
  51536. serializationObject.keys = [];
  51537. var keys = this.getKeys();
  51538. for (var index = 0; index < keys.length; index++) {
  51539. var animationKey = keys[index];
  51540. var key = {};
  51541. key.frame = animationKey.frame;
  51542. switch (dataType) {
  51543. case Animation.ANIMATIONTYPE_FLOAT:
  51544. key.values = [animationKey.value];
  51545. break;
  51546. case Animation.ANIMATIONTYPE_QUATERNION:
  51547. case Animation.ANIMATIONTYPE_MATRIX:
  51548. case Animation.ANIMATIONTYPE_VECTOR3:
  51549. case Animation.ANIMATIONTYPE_COLOR3:
  51550. key.values = animationKey.value.asArray();
  51551. break;
  51552. }
  51553. serializationObject.keys.push(key);
  51554. }
  51555. serializationObject.ranges = [];
  51556. for (var name in this._ranges) {
  51557. var source = this._ranges[name];
  51558. if (!source) {
  51559. continue;
  51560. }
  51561. var range = {};
  51562. range.name = name;
  51563. range.from = source.from;
  51564. range.to = source.to;
  51565. serializationObject.ranges.push(range);
  51566. }
  51567. return serializationObject;
  51568. };
  51569. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51570. /**
  51571. * Get the float animation type
  51572. */
  51573. get: function () {
  51574. return Animation._ANIMATIONTYPE_FLOAT;
  51575. },
  51576. enumerable: true,
  51577. configurable: true
  51578. });
  51579. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51580. /**
  51581. * Get the Vector3 animation type
  51582. */
  51583. get: function () {
  51584. return Animation._ANIMATIONTYPE_VECTOR3;
  51585. },
  51586. enumerable: true,
  51587. configurable: true
  51588. });
  51589. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51590. /**
  51591. * Get the Vectpr2 animation type
  51592. */
  51593. get: function () {
  51594. return Animation._ANIMATIONTYPE_VECTOR2;
  51595. },
  51596. enumerable: true,
  51597. configurable: true
  51598. });
  51599. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51600. /**
  51601. * Get the Size animation type
  51602. */
  51603. get: function () {
  51604. return Animation._ANIMATIONTYPE_SIZE;
  51605. },
  51606. enumerable: true,
  51607. configurable: true
  51608. });
  51609. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51610. /**
  51611. * Get the Quaternion animation type
  51612. */
  51613. get: function () {
  51614. return Animation._ANIMATIONTYPE_QUATERNION;
  51615. },
  51616. enumerable: true,
  51617. configurable: true
  51618. });
  51619. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51620. /**
  51621. * Get the Matrix animation type
  51622. */
  51623. get: function () {
  51624. return Animation._ANIMATIONTYPE_MATRIX;
  51625. },
  51626. enumerable: true,
  51627. configurable: true
  51628. });
  51629. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51630. /**
  51631. * Get the Color3 animation type
  51632. */
  51633. get: function () {
  51634. return Animation._ANIMATIONTYPE_COLOR3;
  51635. },
  51636. enumerable: true,
  51637. configurable: true
  51638. });
  51639. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51640. /**
  51641. * Get the Relative Loop Mode
  51642. */
  51643. get: function () {
  51644. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51645. },
  51646. enumerable: true,
  51647. configurable: true
  51648. });
  51649. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51650. /**
  51651. * Get the Cycle Loop Mode
  51652. */
  51653. get: function () {
  51654. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51655. },
  51656. enumerable: true,
  51657. configurable: true
  51658. });
  51659. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51660. /**
  51661. * Get the Constant Loop Mode
  51662. */
  51663. get: function () {
  51664. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51665. },
  51666. enumerable: true,
  51667. configurable: true
  51668. });
  51669. /** @hidden */
  51670. Animation._UniversalLerp = function (left, right, amount) {
  51671. var constructor = left.constructor;
  51672. if (constructor.Lerp) { // Lerp supported
  51673. return constructor.Lerp(left, right, amount);
  51674. }
  51675. else if (constructor.Slerp) { // Slerp supported
  51676. return constructor.Slerp(left, right, amount);
  51677. }
  51678. else if (left.toFixed) { // Number
  51679. return left * (1.0 - amount) + amount * right;
  51680. }
  51681. else { // Blending not supported
  51682. return right;
  51683. }
  51684. };
  51685. /**
  51686. * Parses an animation object and creates an animation
  51687. * @param parsedAnimation Parsed animation object
  51688. * @returns Animation object
  51689. */
  51690. Animation.Parse = function (parsedAnimation) {
  51691. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51692. var dataType = parsedAnimation.dataType;
  51693. var keys = [];
  51694. var data;
  51695. var index;
  51696. if (parsedAnimation.enableBlending) {
  51697. animation.enableBlending = parsedAnimation.enableBlending;
  51698. }
  51699. if (parsedAnimation.blendingSpeed) {
  51700. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51701. }
  51702. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51703. var key = parsedAnimation.keys[index];
  51704. var inTangent;
  51705. var outTangent;
  51706. switch (dataType) {
  51707. case Animation.ANIMATIONTYPE_FLOAT:
  51708. data = key.values[0];
  51709. if (key.values.length >= 1) {
  51710. inTangent = key.values[1];
  51711. }
  51712. if (key.values.length >= 2) {
  51713. outTangent = key.values[2];
  51714. }
  51715. break;
  51716. case Animation.ANIMATIONTYPE_QUATERNION:
  51717. data = BABYLON.Quaternion.FromArray(key.values);
  51718. if (key.values.length >= 8) {
  51719. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51720. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51721. inTangent = _inTangent;
  51722. }
  51723. }
  51724. if (key.values.length >= 12) {
  51725. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51726. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51727. outTangent = _outTangent;
  51728. }
  51729. }
  51730. break;
  51731. case Animation.ANIMATIONTYPE_MATRIX:
  51732. data = BABYLON.Matrix.FromArray(key.values);
  51733. break;
  51734. case Animation.ANIMATIONTYPE_COLOR3:
  51735. data = BABYLON.Color3.FromArray(key.values);
  51736. break;
  51737. case Animation.ANIMATIONTYPE_VECTOR3:
  51738. default:
  51739. data = BABYLON.Vector3.FromArray(key.values);
  51740. break;
  51741. }
  51742. var keyData = {};
  51743. keyData.frame = key.frame;
  51744. keyData.value = data;
  51745. if (inTangent != undefined) {
  51746. keyData.inTangent = inTangent;
  51747. }
  51748. if (outTangent != undefined) {
  51749. keyData.outTangent = outTangent;
  51750. }
  51751. keys.push(keyData);
  51752. }
  51753. animation.setKeys(keys);
  51754. if (parsedAnimation.ranges) {
  51755. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51756. data = parsedAnimation.ranges[index];
  51757. animation.createRange(data.name, data.from, data.to);
  51758. }
  51759. }
  51760. return animation;
  51761. };
  51762. /**
  51763. * Appends the serialized animations from the source animations
  51764. * @param source Source containing the animations
  51765. * @param destination Target to store the animations
  51766. */
  51767. Animation.AppendSerializedAnimations = function (source, destination) {
  51768. if (source.animations) {
  51769. destination.animations = [];
  51770. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51771. var animation = source.animations[animationIndex];
  51772. destination.animations.push(animation.serialize());
  51773. }
  51774. }
  51775. };
  51776. /**
  51777. * Use matrix interpolation instead of using direct key value when animating matrices
  51778. */
  51779. Animation.AllowMatricesInterpolation = false;
  51780. /**
  51781. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51782. */
  51783. Animation.AllowMatrixDecomposeForInterpolation = true;
  51784. // Statics
  51785. /**
  51786. * Float animation type
  51787. */
  51788. Animation._ANIMATIONTYPE_FLOAT = 0;
  51789. /**
  51790. * Vector3 animation type
  51791. */
  51792. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51793. /**
  51794. * Quaternion animation type
  51795. */
  51796. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51797. /**
  51798. * Matrix animation type
  51799. */
  51800. Animation._ANIMATIONTYPE_MATRIX = 3;
  51801. /**
  51802. * Color3 animation type
  51803. */
  51804. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51805. /**
  51806. * Vector2 animation type
  51807. */
  51808. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51809. /**
  51810. * Size animation type
  51811. */
  51812. Animation._ANIMATIONTYPE_SIZE = 6;
  51813. /**
  51814. * Relative Loop Mode
  51815. */
  51816. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51817. /**
  51818. * Cycle Loop Mode
  51819. */
  51820. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51821. /**
  51822. * Constant Loop Mode
  51823. */
  51824. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51825. return Animation;
  51826. }());
  51827. BABYLON.Animation = Animation;
  51828. })(BABYLON || (BABYLON = {}));
  51829. //# sourceMappingURL=babylon.animation.js.map
  51830. var BABYLON;
  51831. (function (BABYLON) {
  51832. /**
  51833. * This class defines the direct association between an animation and a target
  51834. */
  51835. var TargetedAnimation = /** @class */ (function () {
  51836. function TargetedAnimation() {
  51837. }
  51838. return TargetedAnimation;
  51839. }());
  51840. BABYLON.TargetedAnimation = TargetedAnimation;
  51841. /**
  51842. * Use this class to create coordinated animations on multiple targets
  51843. */
  51844. var AnimationGroup = /** @class */ (function () {
  51845. function AnimationGroup(name, scene) {
  51846. if (scene === void 0) { scene = null; }
  51847. this.name = name;
  51848. this._targetedAnimations = new Array();
  51849. this._animatables = new Array();
  51850. this._from = Number.MAX_VALUE;
  51851. this._to = -Number.MAX_VALUE;
  51852. this._speedRatio = 1;
  51853. this.onAnimationEndObservable = new BABYLON.Observable();
  51854. /**
  51855. * This observable will notify when all animations have ended.
  51856. */
  51857. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  51858. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51859. this._scene.animationGroups.push(this);
  51860. }
  51861. Object.defineProperty(AnimationGroup.prototype, "from", {
  51862. /**
  51863. * Gets the first frame
  51864. */
  51865. get: function () {
  51866. return this._from;
  51867. },
  51868. enumerable: true,
  51869. configurable: true
  51870. });
  51871. Object.defineProperty(AnimationGroup.prototype, "to", {
  51872. /**
  51873. * Gets the last frame
  51874. */
  51875. get: function () {
  51876. return this._to;
  51877. },
  51878. enumerable: true,
  51879. configurable: true
  51880. });
  51881. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51882. /**
  51883. * Define if the animations are started
  51884. */
  51885. get: function () {
  51886. return this._isStarted;
  51887. },
  51888. enumerable: true,
  51889. configurable: true
  51890. });
  51891. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51892. /**
  51893. * Gets or sets the speed ratio to use for all animations
  51894. */
  51895. get: function () {
  51896. return this._speedRatio;
  51897. },
  51898. /**
  51899. * Gets or sets the speed ratio to use for all animations
  51900. */
  51901. set: function (value) {
  51902. if (this._speedRatio === value) {
  51903. return;
  51904. }
  51905. this._speedRatio = value;
  51906. for (var index = 0; index < this._animatables.length; index++) {
  51907. var animatable = this._animatables[index];
  51908. animatable.speedRatio = this._speedRatio;
  51909. }
  51910. },
  51911. enumerable: true,
  51912. configurable: true
  51913. });
  51914. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51915. /**
  51916. * Gets the targeted animations for this animation group
  51917. */
  51918. get: function () {
  51919. return this._targetedAnimations;
  51920. },
  51921. enumerable: true,
  51922. configurable: true
  51923. });
  51924. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51925. /**
  51926. * returning the list of animatables controlled by this animation group.
  51927. */
  51928. get: function () {
  51929. return this._animatables;
  51930. },
  51931. enumerable: true,
  51932. configurable: true
  51933. });
  51934. /**
  51935. * Add an animation (with its target) in the group
  51936. * @param animation defines the animation we want to add
  51937. * @param target defines the target of the animation
  51938. * @returns the {BABYLON.TargetedAnimation} object
  51939. */
  51940. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51941. var targetedAnimation = {
  51942. animation: animation,
  51943. target: target
  51944. };
  51945. var keys = animation.getKeys();
  51946. if (this._from > keys[0].frame) {
  51947. this._from = keys[0].frame;
  51948. }
  51949. if (this._to < keys[keys.length - 1].frame) {
  51950. this._to = keys[keys.length - 1].frame;
  51951. }
  51952. this._targetedAnimations.push(targetedAnimation);
  51953. return targetedAnimation;
  51954. };
  51955. /**
  51956. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51957. * It can add constant keys at begin or end
  51958. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51959. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51960. */
  51961. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51962. if (beginFrame === void 0) { beginFrame = null; }
  51963. if (endFrame === void 0) { endFrame = null; }
  51964. if (beginFrame == null)
  51965. beginFrame = this._from;
  51966. if (endFrame == null)
  51967. endFrame = this._to;
  51968. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51969. var targetedAnimation = this._targetedAnimations[index];
  51970. var keys = targetedAnimation.animation.getKeys();
  51971. var startKey = keys[0];
  51972. var endKey = keys[keys.length - 1];
  51973. if (startKey.frame > beginFrame) {
  51974. var newKey = {
  51975. frame: beginFrame,
  51976. value: startKey.value,
  51977. inTangent: startKey.inTangent,
  51978. outTangent: startKey.outTangent,
  51979. interpolation: startKey.interpolation
  51980. };
  51981. keys.splice(0, 0, newKey);
  51982. }
  51983. if (endKey.frame < endFrame) {
  51984. var newKey = {
  51985. frame: endFrame,
  51986. value: endKey.value,
  51987. inTangent: endKey.outTangent,
  51988. outTangent: endKey.outTangent,
  51989. interpolation: endKey.interpolation
  51990. };
  51991. keys.push(newKey);
  51992. }
  51993. }
  51994. this._from = beginFrame;
  51995. this._to = endFrame;
  51996. return this;
  51997. };
  51998. /**
  51999. * Start all animations on given targets
  52000. * @param loop defines if animations must loop
  52001. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  52002. * @param from defines the from key (optional)
  52003. * @param to defines the to key (optional)
  52004. * @returns the current animation group
  52005. */
  52006. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  52007. var _this = this;
  52008. if (loop === void 0) { loop = false; }
  52009. if (speedRatio === void 0) { speedRatio = 1; }
  52010. if (this._isStarted || this._targetedAnimations.length === 0) {
  52011. return this;
  52012. }
  52013. var _loop_1 = function (targetedAnimation) {
  52014. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  52015. animatable.onAnimationEnd = function () {
  52016. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  52017. _this._checkAnimationGroupEnded(animatable);
  52018. };
  52019. this_1._animatables.push(animatable);
  52020. };
  52021. var this_1 = this;
  52022. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  52023. var targetedAnimation = _a[_i];
  52024. _loop_1(targetedAnimation);
  52025. }
  52026. this._speedRatio = speedRatio;
  52027. this._isStarted = true;
  52028. return this;
  52029. };
  52030. /**
  52031. * Pause all animations
  52032. */
  52033. AnimationGroup.prototype.pause = function () {
  52034. if (!this._isStarted) {
  52035. return this;
  52036. }
  52037. for (var index = 0; index < this._animatables.length; index++) {
  52038. var animatable = this._animatables[index];
  52039. animatable.pause();
  52040. }
  52041. return this;
  52042. };
  52043. /**
  52044. * Play all animations to initial state
  52045. * This function will start() the animations if they were not started or will restart() them if they were paused
  52046. * @param loop defines if animations must loop
  52047. */
  52048. AnimationGroup.prototype.play = function (loop) {
  52049. // only if all animatables are ready and exist
  52050. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  52051. if (loop !== undefined) {
  52052. for (var index = 0; index < this._animatables.length; index++) {
  52053. var animatable = this._animatables[index];
  52054. animatable.loopAnimation = loop;
  52055. }
  52056. }
  52057. this.restart();
  52058. }
  52059. else {
  52060. this.stop();
  52061. this.start(loop, this._speedRatio);
  52062. }
  52063. return this;
  52064. };
  52065. /**
  52066. * Reset all animations to initial state
  52067. */
  52068. AnimationGroup.prototype.reset = function () {
  52069. if (!this._isStarted) {
  52070. return this;
  52071. }
  52072. for (var index = 0; index < this._animatables.length; index++) {
  52073. var animatable = this._animatables[index];
  52074. animatable.reset();
  52075. }
  52076. return this;
  52077. };
  52078. /**
  52079. * Restart animations from key 0
  52080. */
  52081. AnimationGroup.prototype.restart = function () {
  52082. if (!this._isStarted) {
  52083. return this;
  52084. }
  52085. for (var index = 0; index < this._animatables.length; index++) {
  52086. var animatable = this._animatables[index];
  52087. animatable.restart();
  52088. }
  52089. return this;
  52090. };
  52091. /**
  52092. * Stop all animations
  52093. */
  52094. AnimationGroup.prototype.stop = function () {
  52095. if (!this._isStarted) {
  52096. return this;
  52097. }
  52098. for (var index = 0; index < this._animatables.length; index++) {
  52099. var animatable = this._animatables[index];
  52100. animatable.stop();
  52101. }
  52102. this._isStarted = false;
  52103. return this;
  52104. };
  52105. /**
  52106. * Set animation weight for all animatables
  52107. * @param weight defines the weight to use
  52108. * @return the animationGroup
  52109. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52110. */
  52111. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  52112. for (var index = 0; index < this._animatables.length; index++) {
  52113. var animatable = this._animatables[index];
  52114. animatable.weight = weight;
  52115. }
  52116. return this;
  52117. };
  52118. /**
  52119. * Synchronize and normalize all animatables with a source animatable
  52120. * @param root defines the root animatable to synchronize with
  52121. * @return the animationGroup
  52122. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52123. */
  52124. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  52125. for (var index = 0; index < this._animatables.length; index++) {
  52126. var animatable = this._animatables[index];
  52127. animatable.syncWith(root);
  52128. }
  52129. return this;
  52130. };
  52131. /**
  52132. * Goes to a specific frame in this animation group
  52133. * @param frame the frame number to go to
  52134. * @return the animationGroup
  52135. */
  52136. AnimationGroup.prototype.goToFrame = function (frame) {
  52137. if (!this._isStarted) {
  52138. return this;
  52139. }
  52140. for (var index = 0; index < this._animatables.length; index++) {
  52141. var animatable = this._animatables[index];
  52142. animatable.goToFrame(frame);
  52143. }
  52144. return this;
  52145. };
  52146. /**
  52147. * Dispose all associated resources
  52148. */
  52149. AnimationGroup.prototype.dispose = function () {
  52150. this._targetedAnimations = [];
  52151. this._animatables = [];
  52152. var index = this._scene.animationGroups.indexOf(this);
  52153. if (index > -1) {
  52154. this._scene.animationGroups.splice(index, 1);
  52155. }
  52156. };
  52157. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  52158. // animatable should be taken out of the array
  52159. var idx = this._animatables.indexOf(animatable);
  52160. if (idx > -1) {
  52161. this._animatables.splice(idx, 1);
  52162. }
  52163. // all animatables were removed? animation group ended!
  52164. if (this._animatables.length === 0) {
  52165. this._isStarted = false;
  52166. this.onAnimationGroupEndObservable.notifyObservers(this);
  52167. }
  52168. };
  52169. return AnimationGroup;
  52170. }());
  52171. BABYLON.AnimationGroup = AnimationGroup;
  52172. })(BABYLON || (BABYLON = {}));
  52173. //# sourceMappingURL=babylon.animationGroup.js.map
  52174. var BABYLON;
  52175. (function (BABYLON) {
  52176. /**
  52177. * Defines a runtime animation
  52178. */
  52179. var RuntimeAnimation = /** @class */ (function () {
  52180. /**
  52181. * Create a new RuntimeAnimation object
  52182. * @param target defines the target of the animation
  52183. * @param animation defines the source animation object
  52184. * @param scene defines the hosting scene
  52185. * @param host defines the initiating Animatable
  52186. */
  52187. function RuntimeAnimation(target, animation, scene, host) {
  52188. var _this = this;
  52189. this._events = new Array();
  52190. /**
  52191. * The current frame of the runtime animation
  52192. */
  52193. this._currentFrame = 0;
  52194. /**
  52195. * The original value of the runtime animation
  52196. */
  52197. this._originalValue = new Array();
  52198. /**
  52199. * The offsets cache of the runtime animation
  52200. */
  52201. this._offsetsCache = {};
  52202. /**
  52203. * The high limits cache of the runtime animation
  52204. */
  52205. this._highLimitsCache = {};
  52206. /**
  52207. * Specifies if the runtime animation has been stopped
  52208. */
  52209. this._stopped = false;
  52210. /**
  52211. * The blending factor of the runtime animation
  52212. */
  52213. this._blendingFactor = 0;
  52214. /**
  52215. * The target path of the runtime animation
  52216. */
  52217. this._targetPath = "";
  52218. /**
  52219. * The weight of the runtime animation
  52220. */
  52221. this._weight = 1.0;
  52222. /**
  52223. * The ratio offset of the runtime animation
  52224. */
  52225. this._ratioOffset = 0;
  52226. /**
  52227. * The previous delay of the runtime animation
  52228. */
  52229. this._previousDelay = 0;
  52230. /**
  52231. * The previous ratio of the runtime animation
  52232. */
  52233. this._previousRatio = 0;
  52234. this._animation = animation;
  52235. this._target = target;
  52236. this._scene = scene;
  52237. this._host = host;
  52238. animation._runtimeAnimations.push(this);
  52239. // Cloning events locally
  52240. var events = animation.getEvents();
  52241. if (events && events.length > 0) {
  52242. events.forEach(function (e) {
  52243. _this._events.push(e._clone());
  52244. });
  52245. }
  52246. }
  52247. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  52248. /**
  52249. * Gets the current frame of the runtime animation
  52250. */
  52251. get: function () {
  52252. return this._currentFrame;
  52253. },
  52254. enumerable: true,
  52255. configurable: true
  52256. });
  52257. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  52258. /**
  52259. * Gets the weight of the runtime animation
  52260. */
  52261. get: function () {
  52262. return this._weight;
  52263. },
  52264. enumerable: true,
  52265. configurable: true
  52266. });
  52267. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  52268. /**
  52269. * Gets the current value of the runtime animation
  52270. */
  52271. get: function () {
  52272. return this._currentValue;
  52273. },
  52274. enumerable: true,
  52275. configurable: true
  52276. });
  52277. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  52278. /**
  52279. * Gets the target path of the runtime animation
  52280. */
  52281. get: function () {
  52282. return this._targetPath;
  52283. },
  52284. enumerable: true,
  52285. configurable: true
  52286. });
  52287. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  52288. /**
  52289. * Gets the actual target of the runtime animation
  52290. */
  52291. get: function () {
  52292. return this._activeTarget;
  52293. },
  52294. enumerable: true,
  52295. configurable: true
  52296. });
  52297. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  52298. /**
  52299. * Gets the animation from the runtime animation
  52300. */
  52301. get: function () {
  52302. return this._animation;
  52303. },
  52304. enumerable: true,
  52305. configurable: true
  52306. });
  52307. /**
  52308. * Resets the runtime animation to the beginning
  52309. * @param restoreOriginal defines whether to restore the target property to the original value
  52310. */
  52311. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  52312. if (restoreOriginal === void 0) { restoreOriginal = false; }
  52313. if (restoreOriginal) {
  52314. if (this._target instanceof Array) {
  52315. var index = 0;
  52316. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52317. var target = _a[_i];
  52318. if (this._originalValue[index] !== undefined) {
  52319. this._setValue(target, this._originalValue[index], -1);
  52320. }
  52321. index++;
  52322. }
  52323. }
  52324. else {
  52325. if (this._originalValue[0] !== undefined) {
  52326. this._setValue(this._target, this._originalValue[0], -1);
  52327. }
  52328. }
  52329. }
  52330. this._offsetsCache = {};
  52331. this._highLimitsCache = {};
  52332. this._currentFrame = 0;
  52333. this._blendingFactor = 0;
  52334. this._originalValue = new Array();
  52335. // Events
  52336. for (var index = 0; index < this._events.length; index++) {
  52337. this._events[index].isDone = false;
  52338. }
  52339. };
  52340. /**
  52341. * Specifies if the runtime animation is stopped
  52342. * @returns Boolean specifying if the runtime animation is stopped
  52343. */
  52344. RuntimeAnimation.prototype.isStopped = function () {
  52345. return this._stopped;
  52346. };
  52347. /**
  52348. * Disposes of the runtime animation
  52349. */
  52350. RuntimeAnimation.prototype.dispose = function () {
  52351. var index = this._animation.runtimeAnimations.indexOf(this);
  52352. if (index > -1) {
  52353. this._animation.runtimeAnimations.splice(index, 1);
  52354. }
  52355. };
  52356. /**
  52357. * Interpolates the animation from the current frame
  52358. * @param currentFrame The frame to interpolate the animation to
  52359. * @param repeatCount The number of times that the animation should loop
  52360. * @param loopMode The type of looping mode to use
  52361. * @param offsetValue Animation offset value
  52362. * @param highLimitValue The high limit value
  52363. * @returns The interpolated value
  52364. */
  52365. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  52366. this._currentFrame = currentFrame;
  52367. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  52368. this._workValue = BABYLON.Matrix.Zero();
  52369. }
  52370. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  52371. };
  52372. /**
  52373. * Apply the interpolated value to the target
  52374. * @param currentValue defines the value computed by the animation
  52375. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  52376. */
  52377. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  52378. if (weight === void 0) { weight = 1.0; }
  52379. if (this._target instanceof Array) {
  52380. var index = 0;
  52381. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52382. var target = _a[_i];
  52383. this._setValue(target, currentValue, weight, index);
  52384. index++;
  52385. }
  52386. }
  52387. else {
  52388. this._setValue(this._target, currentValue, weight);
  52389. }
  52390. };
  52391. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  52392. if (targetIndex === void 0) { targetIndex = 0; }
  52393. // Set value
  52394. var path;
  52395. var destination;
  52396. var targetPropertyPath = this._animation.targetPropertyPath;
  52397. if (targetPropertyPath.length > 1) {
  52398. var property = target[targetPropertyPath[0]];
  52399. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  52400. property = property[targetPropertyPath[index]];
  52401. }
  52402. path = targetPropertyPath[targetPropertyPath.length - 1];
  52403. destination = property;
  52404. }
  52405. else {
  52406. path = targetPropertyPath[0];
  52407. destination = target;
  52408. }
  52409. this._targetPath = path;
  52410. this._activeTarget = destination;
  52411. this._weight = weight;
  52412. if (this._originalValue[targetIndex] === undefined) {
  52413. var originalValue = void 0;
  52414. if (destination.getRestPose && path === "_matrix") { // For bones
  52415. originalValue = destination.getRestPose();
  52416. }
  52417. else {
  52418. originalValue = destination[path];
  52419. }
  52420. if (originalValue && originalValue.clone) {
  52421. this._originalValue[targetIndex] = originalValue.clone();
  52422. }
  52423. else {
  52424. this._originalValue[targetIndex] = originalValue;
  52425. }
  52426. }
  52427. // Blending
  52428. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52429. if (enableBlending && this._blendingFactor <= 1.0) {
  52430. if (!this._originalBlendValue) {
  52431. var originalValue = destination[path];
  52432. if (originalValue.clone) {
  52433. this._originalBlendValue = originalValue.clone();
  52434. }
  52435. else {
  52436. this._originalBlendValue = originalValue;
  52437. }
  52438. }
  52439. if (this._originalBlendValue.m) { // Matrix
  52440. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52441. if (this._currentValue) {
  52442. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52443. }
  52444. else {
  52445. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52446. }
  52447. }
  52448. else {
  52449. if (this._currentValue) {
  52450. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52451. }
  52452. else {
  52453. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52454. }
  52455. }
  52456. }
  52457. else {
  52458. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52459. }
  52460. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52461. this._blendingFactor += blendingSpeed;
  52462. }
  52463. else {
  52464. this._currentValue = currentValue;
  52465. }
  52466. if (weight !== -1.0) {
  52467. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52468. }
  52469. else {
  52470. destination[path] = this._currentValue;
  52471. }
  52472. if (target.markAsDirty) {
  52473. target.markAsDirty(this._animation.targetProperty);
  52474. }
  52475. };
  52476. /**
  52477. * Gets the loop pmode of the runtime animation
  52478. * @returns Loop Mode
  52479. */
  52480. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52481. if (this._target && this._target.animationPropertiesOverride) {
  52482. return this._target.animationPropertiesOverride.loopMode;
  52483. }
  52484. return this._animation.loopMode;
  52485. };
  52486. /**
  52487. * Move the current animation to a given frame
  52488. * @param frame defines the frame to move to
  52489. */
  52490. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52491. var keys = this._animation.getKeys();
  52492. if (frame < keys[0].frame) {
  52493. frame = keys[0].frame;
  52494. }
  52495. else if (frame > keys[keys.length - 1].frame) {
  52496. frame = keys[keys.length - 1].frame;
  52497. }
  52498. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52499. this.setValue(currentValue, -1);
  52500. };
  52501. /**
  52502. * @hidden Internal use only
  52503. */
  52504. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52505. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52506. this._ratioOffset = this._previousRatio - newRatio;
  52507. };
  52508. /**
  52509. * Execute the current animation
  52510. * @param delay defines the delay to add to the current frame
  52511. * @param from defines the lower bound of the animation range
  52512. * @param to defines the upper bound of the animation range
  52513. * @param loop defines if the current animation must loop
  52514. * @param speedRatio defines the current speed ratio
  52515. * @param weight defines the weight of the animation (default is -1 so no weight)
  52516. * @returns a boolean indicating if the animation has ended
  52517. */
  52518. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52519. if (weight === void 0) { weight = -1.0; }
  52520. var targetPropertyPath = this._animation.targetPropertyPath;
  52521. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52522. this._stopped = true;
  52523. return false;
  52524. }
  52525. var returnValue = true;
  52526. var keys = this._animation.getKeys();
  52527. // Adding a start key at frame 0 if missing
  52528. if (keys[0].frame !== 0) {
  52529. var newKey = { frame: 0, value: keys[0].value };
  52530. keys.splice(0, 0, newKey);
  52531. }
  52532. // Check limits
  52533. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52534. from = keys[0].frame;
  52535. }
  52536. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52537. to = keys[keys.length - 1].frame;
  52538. }
  52539. //to and from cannot be the same key
  52540. if (from === to) {
  52541. if (from > keys[0].frame) {
  52542. from--;
  52543. }
  52544. else if (to < keys[keys.length - 1].frame) {
  52545. to++;
  52546. }
  52547. }
  52548. // Compute ratio
  52549. var range = to - from;
  52550. var offsetValue;
  52551. // ratio represents the frame delta between from and to
  52552. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52553. var highLimitValue = 0;
  52554. this._previousDelay = delay;
  52555. this._previousRatio = ratio;
  52556. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  52557. returnValue = false;
  52558. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52559. }
  52560. else {
  52561. // Get max value if required
  52562. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52563. var keyOffset = to.toString() + from.toString();
  52564. if (!this._offsetsCache[keyOffset]) {
  52565. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52566. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52567. switch (this._animation.dataType) {
  52568. // Float
  52569. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52570. this._offsetsCache[keyOffset] = toValue - fromValue;
  52571. break;
  52572. // Quaternion
  52573. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52574. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52575. break;
  52576. // Vector3
  52577. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52578. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52579. // Vector2
  52580. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52581. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52582. // Size
  52583. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52584. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52585. // Color3
  52586. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52587. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52588. default:
  52589. break;
  52590. }
  52591. this._highLimitsCache[keyOffset] = toValue;
  52592. }
  52593. highLimitValue = this._highLimitsCache[keyOffset];
  52594. offsetValue = this._offsetsCache[keyOffset];
  52595. }
  52596. }
  52597. if (offsetValue === undefined) {
  52598. switch (this._animation.dataType) {
  52599. // Float
  52600. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52601. offsetValue = 0;
  52602. break;
  52603. // Quaternion
  52604. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52605. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  52606. break;
  52607. // Vector3
  52608. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52609. offsetValue = BABYLON.Vector3.Zero();
  52610. break;
  52611. // Vector2
  52612. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52613. offsetValue = BABYLON.Vector2.Zero();
  52614. break;
  52615. // Size
  52616. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52617. offsetValue = BABYLON.Size.Zero();
  52618. break;
  52619. // Color3
  52620. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52621. offsetValue = BABYLON.Color3.Black();
  52622. }
  52623. }
  52624. // Compute value
  52625. var repeatCount = (ratio / range) >> 0;
  52626. var currentFrame = returnValue ? from + ratio % range : to;
  52627. // Need to normalize?
  52628. if (this._host && this._host.syncRoot) {
  52629. var syncRoot = this._host.syncRoot;
  52630. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52631. currentFrame = from + (to - from) * hostNormalizedFrame;
  52632. }
  52633. // Reset events if looping
  52634. var events = this._events;
  52635. if (range > 0 && this.currentFrame > currentFrame ||
  52636. range < 0 && this.currentFrame < currentFrame) {
  52637. // Need to reset animation events
  52638. for (var index = 0; index < events.length; index++) {
  52639. if (!events[index].onlyOnce) {
  52640. // reset event, the animation is looping
  52641. events[index].isDone = false;
  52642. }
  52643. }
  52644. }
  52645. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52646. // Set value
  52647. this.setValue(currentValue, weight);
  52648. // Check events
  52649. for (var index = 0; index < events.length; index++) {
  52650. // Make sure current frame has passed event frame and that event frame is within the current range
  52651. // Also, handle both forward and reverse animations
  52652. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52653. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52654. var event = events[index];
  52655. if (!event.isDone) {
  52656. // If event should be done only once, remove it.
  52657. if (event.onlyOnce) {
  52658. events.splice(index, 1);
  52659. index--;
  52660. }
  52661. event.isDone = true;
  52662. event.action();
  52663. } // Don't do anything if the event has already be done.
  52664. }
  52665. }
  52666. if (!returnValue) {
  52667. this._stopped = true;
  52668. }
  52669. return returnValue;
  52670. };
  52671. return RuntimeAnimation;
  52672. }());
  52673. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52674. })(BABYLON || (BABYLON = {}));
  52675. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52676. var BABYLON;
  52677. (function (BABYLON) {
  52678. var Animatable = /** @class */ (function () {
  52679. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52680. if (fromFrame === void 0) { fromFrame = 0; }
  52681. if (toFrame === void 0) { toFrame = 100; }
  52682. if (loopAnimation === void 0) { loopAnimation = false; }
  52683. if (speedRatio === void 0) { speedRatio = 1.0; }
  52684. this.target = target;
  52685. this.fromFrame = fromFrame;
  52686. this.toFrame = toFrame;
  52687. this.loopAnimation = loopAnimation;
  52688. this.onAnimationEnd = onAnimationEnd;
  52689. this._localDelayOffset = null;
  52690. this._pausedDelay = null;
  52691. this._runtimeAnimations = new Array();
  52692. this._paused = false;
  52693. this._speedRatio = 1;
  52694. this._weight = -1.0;
  52695. this.animationStarted = false;
  52696. /**
  52697. * Observer raised when the animation ends
  52698. */
  52699. this.onAnimationEndObservable = new BABYLON.Observable();
  52700. this._scene = scene;
  52701. if (animations) {
  52702. this.appendAnimations(target, animations);
  52703. }
  52704. this._speedRatio = speedRatio;
  52705. scene._activeAnimatables.push(this);
  52706. }
  52707. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52708. /**
  52709. * Gets the root Animatable used to synchronize and normalize animations
  52710. */
  52711. get: function () {
  52712. return this._syncRoot;
  52713. },
  52714. enumerable: true,
  52715. configurable: true
  52716. });
  52717. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52718. /**
  52719. * Gets the current frame of the first RuntimeAnimation
  52720. * Used to synchronize Animatables
  52721. */
  52722. get: function () {
  52723. if (this._runtimeAnimations.length === 0) {
  52724. return 0;
  52725. }
  52726. return this._runtimeAnimations[0].currentFrame;
  52727. },
  52728. enumerable: true,
  52729. configurable: true
  52730. });
  52731. Object.defineProperty(Animatable.prototype, "weight", {
  52732. /**
  52733. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52734. */
  52735. get: function () {
  52736. return this._weight;
  52737. },
  52738. set: function (value) {
  52739. if (value === -1) { // -1 is ok and means no weight
  52740. this._weight = -1;
  52741. return;
  52742. }
  52743. // Else weight must be in [0, 1] range
  52744. this._weight = Math.min(Math.max(value, 0), 1.0);
  52745. },
  52746. enumerable: true,
  52747. configurable: true
  52748. });
  52749. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52750. /**
  52751. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52752. */
  52753. get: function () {
  52754. return this._speedRatio;
  52755. },
  52756. set: function (value) {
  52757. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52758. var animation = this._runtimeAnimations[index];
  52759. animation._prepareForSpeedRatioChange(value);
  52760. }
  52761. this._speedRatio = value;
  52762. },
  52763. enumerable: true,
  52764. configurable: true
  52765. });
  52766. // Methods
  52767. /**
  52768. * Synchronize and normalize current Animatable with a source Animatable
  52769. * This is useful when using animation weights and when animations are not of the same length
  52770. * @param root defines the root Animatable to synchronize with
  52771. * @returns the current Animatable
  52772. */
  52773. Animatable.prototype.syncWith = function (root) {
  52774. this._syncRoot = root;
  52775. if (root) {
  52776. // Make sure this animatable will animate after the root
  52777. var index = this._scene._activeAnimatables.indexOf(this);
  52778. if (index > -1) {
  52779. this._scene._activeAnimatables.splice(index, 1);
  52780. this._scene._activeAnimatables.push(this);
  52781. }
  52782. }
  52783. return this;
  52784. };
  52785. Animatable.prototype.getAnimations = function () {
  52786. return this._runtimeAnimations;
  52787. };
  52788. Animatable.prototype.appendAnimations = function (target, animations) {
  52789. for (var index = 0; index < animations.length; index++) {
  52790. var animation = animations[index];
  52791. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52792. }
  52793. };
  52794. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52795. var runtimeAnimations = this._runtimeAnimations;
  52796. for (var index = 0; index < runtimeAnimations.length; index++) {
  52797. if (runtimeAnimations[index].animation.targetProperty === property) {
  52798. return runtimeAnimations[index].animation;
  52799. }
  52800. }
  52801. return null;
  52802. };
  52803. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52804. var runtimeAnimations = this._runtimeAnimations;
  52805. for (var index = 0; index < runtimeAnimations.length; index++) {
  52806. if (runtimeAnimations[index].animation.targetProperty === property) {
  52807. return runtimeAnimations[index];
  52808. }
  52809. }
  52810. return null;
  52811. };
  52812. Animatable.prototype.reset = function () {
  52813. var runtimeAnimations = this._runtimeAnimations;
  52814. for (var index = 0; index < runtimeAnimations.length; index++) {
  52815. runtimeAnimations[index].reset(true);
  52816. }
  52817. this._localDelayOffset = null;
  52818. this._pausedDelay = null;
  52819. };
  52820. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52821. var runtimeAnimations = this._runtimeAnimations;
  52822. for (var index = 0; index < runtimeAnimations.length; index++) {
  52823. runtimeAnimations[index].animation.enableBlending = true;
  52824. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52825. }
  52826. };
  52827. Animatable.prototype.disableBlending = function () {
  52828. var runtimeAnimations = this._runtimeAnimations;
  52829. for (var index = 0; index < runtimeAnimations.length; index++) {
  52830. runtimeAnimations[index].animation.enableBlending = false;
  52831. }
  52832. };
  52833. Animatable.prototype.goToFrame = function (frame) {
  52834. var runtimeAnimations = this._runtimeAnimations;
  52835. if (runtimeAnimations[0]) {
  52836. var fps = runtimeAnimations[0].animation.framePerSecond;
  52837. var currentFrame = runtimeAnimations[0].currentFrame;
  52838. var adjustTime = frame - currentFrame;
  52839. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52840. if (this._localDelayOffset === null) {
  52841. this._localDelayOffset = 0;
  52842. }
  52843. this._localDelayOffset -= delay;
  52844. }
  52845. for (var index = 0; index < runtimeAnimations.length; index++) {
  52846. runtimeAnimations[index].goToFrame(frame);
  52847. }
  52848. };
  52849. Animatable.prototype.pause = function () {
  52850. if (this._paused) {
  52851. return;
  52852. }
  52853. this._paused = true;
  52854. };
  52855. Animatable.prototype.restart = function () {
  52856. this._paused = false;
  52857. };
  52858. Animatable.prototype._raiseOnAnimationEnd = function () {
  52859. if (this.onAnimationEnd) {
  52860. this.onAnimationEnd();
  52861. }
  52862. this.onAnimationEndObservable.notifyObservers(this);
  52863. };
  52864. Animatable.prototype.stop = function (animationName) {
  52865. if (animationName) {
  52866. var idx = this._scene._activeAnimatables.indexOf(this);
  52867. if (idx > -1) {
  52868. var runtimeAnimations = this._runtimeAnimations;
  52869. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52870. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52871. continue;
  52872. }
  52873. runtimeAnimations[index].dispose();
  52874. runtimeAnimations.splice(index, 1);
  52875. }
  52876. if (runtimeAnimations.length == 0) {
  52877. this._scene._activeAnimatables.splice(idx, 1);
  52878. this._raiseOnAnimationEnd();
  52879. }
  52880. }
  52881. }
  52882. else {
  52883. var index = this._scene._activeAnimatables.indexOf(this);
  52884. if (index > -1) {
  52885. this._scene._activeAnimatables.splice(index, 1);
  52886. var runtimeAnimations = this._runtimeAnimations;
  52887. for (var index = 0; index < runtimeAnimations.length; index++) {
  52888. runtimeAnimations[index].dispose();
  52889. }
  52890. this._raiseOnAnimationEnd();
  52891. }
  52892. }
  52893. };
  52894. /**
  52895. * Wait asynchronously for the animation to end
  52896. * @returns a promise which will be fullfilled when the animation ends
  52897. */
  52898. Animatable.prototype.waitAsync = function () {
  52899. var _this = this;
  52900. return new Promise(function (resolve, reject) {
  52901. _this.onAnimationEndObservable.add(function () {
  52902. resolve(_this);
  52903. }, undefined, undefined, _this, true);
  52904. });
  52905. };
  52906. /** @hidden */
  52907. Animatable.prototype._animate = function (delay) {
  52908. if (this._paused) {
  52909. this.animationStarted = false;
  52910. if (this._pausedDelay === null) {
  52911. this._pausedDelay = delay;
  52912. }
  52913. return true;
  52914. }
  52915. if (this._localDelayOffset === null) {
  52916. this._localDelayOffset = delay;
  52917. this._pausedDelay = null;
  52918. }
  52919. else if (this._pausedDelay !== null) {
  52920. this._localDelayOffset += delay - this._pausedDelay;
  52921. this._pausedDelay = null;
  52922. }
  52923. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52924. return true;
  52925. }
  52926. // Animating
  52927. var running = false;
  52928. var runtimeAnimations = this._runtimeAnimations;
  52929. var index;
  52930. for (index = 0; index < runtimeAnimations.length; index++) {
  52931. var animation = runtimeAnimations[index];
  52932. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52933. running = running || isRunning;
  52934. }
  52935. this.animationStarted = running;
  52936. if (!running) {
  52937. // Remove from active animatables
  52938. index = this._scene._activeAnimatables.indexOf(this);
  52939. this._scene._activeAnimatables.splice(index, 1);
  52940. // Dispose all runtime animations
  52941. for (index = 0; index < runtimeAnimations.length; index++) {
  52942. runtimeAnimations[index].dispose();
  52943. }
  52944. this._raiseOnAnimationEnd();
  52945. this.onAnimationEnd = null;
  52946. this.onAnimationEndObservable.clear();
  52947. }
  52948. return running;
  52949. };
  52950. return Animatable;
  52951. }());
  52952. BABYLON.Animatable = Animatable;
  52953. })(BABYLON || (BABYLON = {}));
  52954. //# sourceMappingURL=babylon.animatable.js.map
  52955. var BABYLON;
  52956. (function (BABYLON) {
  52957. var EasingFunction = /** @class */ (function () {
  52958. function EasingFunction() {
  52959. // Properties
  52960. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52961. }
  52962. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52963. get: function () {
  52964. return EasingFunction._EASINGMODE_EASEIN;
  52965. },
  52966. enumerable: true,
  52967. configurable: true
  52968. });
  52969. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52970. get: function () {
  52971. return EasingFunction._EASINGMODE_EASEOUT;
  52972. },
  52973. enumerable: true,
  52974. configurable: true
  52975. });
  52976. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52977. get: function () {
  52978. return EasingFunction._EASINGMODE_EASEINOUT;
  52979. },
  52980. enumerable: true,
  52981. configurable: true
  52982. });
  52983. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52984. var n = Math.min(Math.max(easingMode, 0), 2);
  52985. this._easingMode = n;
  52986. };
  52987. EasingFunction.prototype.getEasingMode = function () {
  52988. return this._easingMode;
  52989. };
  52990. EasingFunction.prototype.easeInCore = function (gradient) {
  52991. throw new Error('You must implement this method');
  52992. };
  52993. EasingFunction.prototype.ease = function (gradient) {
  52994. switch (this._easingMode) {
  52995. case EasingFunction.EASINGMODE_EASEIN:
  52996. return this.easeInCore(gradient);
  52997. case EasingFunction.EASINGMODE_EASEOUT:
  52998. return (1 - this.easeInCore(1 - gradient));
  52999. }
  53000. if (gradient >= 0.5) {
  53001. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  53002. }
  53003. return (this.easeInCore(gradient * 2) * 0.5);
  53004. };
  53005. //Statics
  53006. EasingFunction._EASINGMODE_EASEIN = 0;
  53007. EasingFunction._EASINGMODE_EASEOUT = 1;
  53008. EasingFunction._EASINGMODE_EASEINOUT = 2;
  53009. return EasingFunction;
  53010. }());
  53011. BABYLON.EasingFunction = EasingFunction;
  53012. var CircleEase = /** @class */ (function (_super) {
  53013. __extends(CircleEase, _super);
  53014. function CircleEase() {
  53015. return _super !== null && _super.apply(this, arguments) || this;
  53016. }
  53017. CircleEase.prototype.easeInCore = function (gradient) {
  53018. gradient = Math.max(0, Math.min(1, gradient));
  53019. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  53020. };
  53021. return CircleEase;
  53022. }(EasingFunction));
  53023. BABYLON.CircleEase = CircleEase;
  53024. var BackEase = /** @class */ (function (_super) {
  53025. __extends(BackEase, _super);
  53026. function BackEase(amplitude) {
  53027. if (amplitude === void 0) { amplitude = 1; }
  53028. var _this = _super.call(this) || this;
  53029. _this.amplitude = amplitude;
  53030. return _this;
  53031. }
  53032. BackEase.prototype.easeInCore = function (gradient) {
  53033. var num = Math.max(0, this.amplitude);
  53034. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  53035. };
  53036. return BackEase;
  53037. }(EasingFunction));
  53038. BABYLON.BackEase = BackEase;
  53039. var BounceEase = /** @class */ (function (_super) {
  53040. __extends(BounceEase, _super);
  53041. function BounceEase(bounces, bounciness) {
  53042. if (bounces === void 0) { bounces = 3; }
  53043. if (bounciness === void 0) { bounciness = 2; }
  53044. var _this = _super.call(this) || this;
  53045. _this.bounces = bounces;
  53046. _this.bounciness = bounciness;
  53047. return _this;
  53048. }
  53049. BounceEase.prototype.easeInCore = function (gradient) {
  53050. var y = Math.max(0.0, this.bounces);
  53051. var bounciness = this.bounciness;
  53052. if (bounciness <= 1.0) {
  53053. bounciness = 1.001;
  53054. }
  53055. var num9 = Math.pow(bounciness, y);
  53056. var num5 = 1.0 - bounciness;
  53057. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  53058. var num15 = gradient * num4;
  53059. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  53060. var num3 = Math.floor(num65);
  53061. var num13 = num3 + 1.0;
  53062. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  53063. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  53064. var num7 = (num8 + num12) * 0.5;
  53065. var num6 = gradient - num7;
  53066. var num2 = num7 - num8;
  53067. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  53068. };
  53069. return BounceEase;
  53070. }(EasingFunction));
  53071. BABYLON.BounceEase = BounceEase;
  53072. var CubicEase = /** @class */ (function (_super) {
  53073. __extends(CubicEase, _super);
  53074. function CubicEase() {
  53075. return _super !== null && _super.apply(this, arguments) || this;
  53076. }
  53077. CubicEase.prototype.easeInCore = function (gradient) {
  53078. return (gradient * gradient * gradient);
  53079. };
  53080. return CubicEase;
  53081. }(EasingFunction));
  53082. BABYLON.CubicEase = CubicEase;
  53083. var ElasticEase = /** @class */ (function (_super) {
  53084. __extends(ElasticEase, _super);
  53085. function ElasticEase(oscillations, springiness) {
  53086. if (oscillations === void 0) { oscillations = 3; }
  53087. if (springiness === void 0) { springiness = 3; }
  53088. var _this = _super.call(this) || this;
  53089. _this.oscillations = oscillations;
  53090. _this.springiness = springiness;
  53091. return _this;
  53092. }
  53093. ElasticEase.prototype.easeInCore = function (gradient) {
  53094. var num2;
  53095. var num3 = Math.max(0.0, this.oscillations);
  53096. var num = Math.max(0.0, this.springiness);
  53097. if (num == 0) {
  53098. num2 = gradient;
  53099. }
  53100. else {
  53101. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  53102. }
  53103. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  53104. };
  53105. return ElasticEase;
  53106. }(EasingFunction));
  53107. BABYLON.ElasticEase = ElasticEase;
  53108. var ExponentialEase = /** @class */ (function (_super) {
  53109. __extends(ExponentialEase, _super);
  53110. function ExponentialEase(exponent) {
  53111. if (exponent === void 0) { exponent = 2; }
  53112. var _this = _super.call(this) || this;
  53113. _this.exponent = exponent;
  53114. return _this;
  53115. }
  53116. ExponentialEase.prototype.easeInCore = function (gradient) {
  53117. if (this.exponent <= 0) {
  53118. return gradient;
  53119. }
  53120. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  53121. };
  53122. return ExponentialEase;
  53123. }(EasingFunction));
  53124. BABYLON.ExponentialEase = ExponentialEase;
  53125. var PowerEase = /** @class */ (function (_super) {
  53126. __extends(PowerEase, _super);
  53127. function PowerEase(power) {
  53128. if (power === void 0) { power = 2; }
  53129. var _this = _super.call(this) || this;
  53130. _this.power = power;
  53131. return _this;
  53132. }
  53133. PowerEase.prototype.easeInCore = function (gradient) {
  53134. var y = Math.max(0.0, this.power);
  53135. return Math.pow(gradient, y);
  53136. };
  53137. return PowerEase;
  53138. }(EasingFunction));
  53139. BABYLON.PowerEase = PowerEase;
  53140. var QuadraticEase = /** @class */ (function (_super) {
  53141. __extends(QuadraticEase, _super);
  53142. function QuadraticEase() {
  53143. return _super !== null && _super.apply(this, arguments) || this;
  53144. }
  53145. QuadraticEase.prototype.easeInCore = function (gradient) {
  53146. return (gradient * gradient);
  53147. };
  53148. return QuadraticEase;
  53149. }(EasingFunction));
  53150. BABYLON.QuadraticEase = QuadraticEase;
  53151. var QuarticEase = /** @class */ (function (_super) {
  53152. __extends(QuarticEase, _super);
  53153. function QuarticEase() {
  53154. return _super !== null && _super.apply(this, arguments) || this;
  53155. }
  53156. QuarticEase.prototype.easeInCore = function (gradient) {
  53157. return (gradient * gradient * gradient * gradient);
  53158. };
  53159. return QuarticEase;
  53160. }(EasingFunction));
  53161. BABYLON.QuarticEase = QuarticEase;
  53162. var QuinticEase = /** @class */ (function (_super) {
  53163. __extends(QuinticEase, _super);
  53164. function QuinticEase() {
  53165. return _super !== null && _super.apply(this, arguments) || this;
  53166. }
  53167. QuinticEase.prototype.easeInCore = function (gradient) {
  53168. return (gradient * gradient * gradient * gradient * gradient);
  53169. };
  53170. return QuinticEase;
  53171. }(EasingFunction));
  53172. BABYLON.QuinticEase = QuinticEase;
  53173. var SineEase = /** @class */ (function (_super) {
  53174. __extends(SineEase, _super);
  53175. function SineEase() {
  53176. return _super !== null && _super.apply(this, arguments) || this;
  53177. }
  53178. SineEase.prototype.easeInCore = function (gradient) {
  53179. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  53180. };
  53181. return SineEase;
  53182. }(EasingFunction));
  53183. BABYLON.SineEase = SineEase;
  53184. var BezierCurveEase = /** @class */ (function (_super) {
  53185. __extends(BezierCurveEase, _super);
  53186. function BezierCurveEase(x1, y1, x2, y2) {
  53187. if (x1 === void 0) { x1 = 0; }
  53188. if (y1 === void 0) { y1 = 0; }
  53189. if (x2 === void 0) { x2 = 1; }
  53190. if (y2 === void 0) { y2 = 1; }
  53191. var _this = _super.call(this) || this;
  53192. _this.x1 = x1;
  53193. _this.y1 = y1;
  53194. _this.x2 = x2;
  53195. _this.y2 = y2;
  53196. return _this;
  53197. }
  53198. BezierCurveEase.prototype.easeInCore = function (gradient) {
  53199. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  53200. };
  53201. return BezierCurveEase;
  53202. }(EasingFunction));
  53203. BABYLON.BezierCurveEase = BezierCurveEase;
  53204. })(BABYLON || (BABYLON = {}));
  53205. //# sourceMappingURL=babylon.easing.js.map
  53206. var BABYLON;
  53207. (function (BABYLON) {
  53208. /**
  53209. * A Condition applied to an Action
  53210. */
  53211. var Condition = /** @class */ (function () {
  53212. /**
  53213. * Creates a new Condition
  53214. * @param actionManager the manager of the action the condition is applied to
  53215. */
  53216. function Condition(actionManager) {
  53217. this._actionManager = actionManager;
  53218. }
  53219. /**
  53220. * Check if the current condition is valid
  53221. * @returns a boolean
  53222. */
  53223. Condition.prototype.isValid = function () {
  53224. return true;
  53225. };
  53226. /**
  53227. * Internal only
  53228. * @hidden
  53229. */
  53230. Condition.prototype._getProperty = function (propertyPath) {
  53231. return this._actionManager._getProperty(propertyPath);
  53232. };
  53233. /**
  53234. * Internal only
  53235. * @hidden
  53236. */
  53237. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  53238. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53239. };
  53240. /**
  53241. * Serialize placeholder for child classes
  53242. * @returns the serialized object
  53243. */
  53244. Condition.prototype.serialize = function () {
  53245. };
  53246. /**
  53247. * Internal only
  53248. * @hidden
  53249. */
  53250. Condition.prototype._serialize = function (serializedCondition) {
  53251. return {
  53252. type: 2,
  53253. children: [],
  53254. name: serializedCondition.name,
  53255. properties: serializedCondition.properties
  53256. };
  53257. };
  53258. return Condition;
  53259. }());
  53260. BABYLON.Condition = Condition;
  53261. /**
  53262. * Defines specific conditional operators as extensions of Condition
  53263. */
  53264. var ValueCondition = /** @class */ (function (_super) {
  53265. __extends(ValueCondition, _super);
  53266. /**
  53267. * Creates a new ValueCondition
  53268. * @param actionManager manager for the action the condition applies to
  53269. * @param target for the action
  53270. * @param propertyPath path to specify the property of the target the conditional operator uses
  53271. * @param value the value compared by the conditional operator against the current value of the property
  53272. * @param operator the conditional operator, default ValueCondition.IsEqual
  53273. */
  53274. function ValueCondition(actionManager, target,
  53275. /** path to specify the property of the target the conditional operator uses */
  53276. propertyPath,
  53277. /** the value compared by the conditional operator against the current value of the property */
  53278. value,
  53279. /** the conditional operator, default ValueCondition.IsEqual */
  53280. operator) {
  53281. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  53282. var _this = _super.call(this, actionManager) || this;
  53283. _this.propertyPath = propertyPath;
  53284. _this.value = value;
  53285. _this.operator = operator;
  53286. _this._target = target;
  53287. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  53288. _this._property = _this._getProperty(_this.propertyPath);
  53289. return _this;
  53290. }
  53291. Object.defineProperty(ValueCondition, "IsEqual", {
  53292. /**
  53293. * returns the number for IsEqual
  53294. */
  53295. get: function () {
  53296. return ValueCondition._IsEqual;
  53297. },
  53298. enumerable: true,
  53299. configurable: true
  53300. });
  53301. Object.defineProperty(ValueCondition, "IsDifferent", {
  53302. /**
  53303. * Returns the number for IsDifferent
  53304. */
  53305. get: function () {
  53306. return ValueCondition._IsDifferent;
  53307. },
  53308. enumerable: true,
  53309. configurable: true
  53310. });
  53311. Object.defineProperty(ValueCondition, "IsGreater", {
  53312. /**
  53313. * Returns the number for IsGreater
  53314. */
  53315. get: function () {
  53316. return ValueCondition._IsGreater;
  53317. },
  53318. enumerable: true,
  53319. configurable: true
  53320. });
  53321. Object.defineProperty(ValueCondition, "IsLesser", {
  53322. /**
  53323. * Returns the number for IsLesser
  53324. */
  53325. get: function () {
  53326. return ValueCondition._IsLesser;
  53327. },
  53328. enumerable: true,
  53329. configurable: true
  53330. });
  53331. /**
  53332. * Compares the given value with the property value for the specified conditional operator
  53333. * @returns the result of the comparison
  53334. */
  53335. ValueCondition.prototype.isValid = function () {
  53336. switch (this.operator) {
  53337. case ValueCondition.IsGreater:
  53338. return this._effectiveTarget[this._property] > this.value;
  53339. case ValueCondition.IsLesser:
  53340. return this._effectiveTarget[this._property] < this.value;
  53341. case ValueCondition.IsEqual:
  53342. case ValueCondition.IsDifferent:
  53343. var check;
  53344. if (this.value.equals) {
  53345. check = this.value.equals(this._effectiveTarget[this._property]);
  53346. }
  53347. else {
  53348. check = this.value === this._effectiveTarget[this._property];
  53349. }
  53350. return this.operator === ValueCondition.IsEqual ? check : !check;
  53351. }
  53352. return false;
  53353. };
  53354. /**
  53355. * Serialize the ValueCondition into a JSON compatible object
  53356. * @returns serialization object
  53357. */
  53358. ValueCondition.prototype.serialize = function () {
  53359. return this._serialize({
  53360. name: "ValueCondition",
  53361. properties: [
  53362. BABYLON.Action._GetTargetProperty(this._target),
  53363. { name: "propertyPath", value: this.propertyPath },
  53364. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53365. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  53366. ]
  53367. });
  53368. };
  53369. /**
  53370. * Gets the name of the conditional operator for the ValueCondition
  53371. * @param operator the conditional operator
  53372. * @returns the name
  53373. */
  53374. ValueCondition.GetOperatorName = function (operator) {
  53375. switch (operator) {
  53376. case ValueCondition._IsEqual: return "IsEqual";
  53377. case ValueCondition._IsDifferent: return "IsDifferent";
  53378. case ValueCondition._IsGreater: return "IsGreater";
  53379. case ValueCondition._IsLesser: return "IsLesser";
  53380. default: return "";
  53381. }
  53382. };
  53383. /**
  53384. * Internal only
  53385. * @hidden
  53386. */
  53387. ValueCondition._IsEqual = 0;
  53388. /**
  53389. * Internal only
  53390. * @hidden
  53391. */
  53392. ValueCondition._IsDifferent = 1;
  53393. /**
  53394. * Internal only
  53395. * @hidden
  53396. */
  53397. ValueCondition._IsGreater = 2;
  53398. /**
  53399. * Internal only
  53400. * @hidden
  53401. */
  53402. ValueCondition._IsLesser = 3;
  53403. return ValueCondition;
  53404. }(Condition));
  53405. BABYLON.ValueCondition = ValueCondition;
  53406. /**
  53407. * Defines a predicate condition as an extension of Condition
  53408. */
  53409. var PredicateCondition = /** @class */ (function (_super) {
  53410. __extends(PredicateCondition, _super);
  53411. /**
  53412. * Creates a new PredicateCondition
  53413. * @param actionManager manager for the action the condition applies to
  53414. * @param predicate defines the predicate function used to validate the condition
  53415. */
  53416. function PredicateCondition(actionManager,
  53417. /** defines the predicate function used to validate the condition */
  53418. predicate) {
  53419. var _this = _super.call(this, actionManager) || this;
  53420. _this.predicate = predicate;
  53421. return _this;
  53422. }
  53423. /**
  53424. * @returns the validity of the predicate condition
  53425. */
  53426. PredicateCondition.prototype.isValid = function () {
  53427. return this.predicate();
  53428. };
  53429. return PredicateCondition;
  53430. }(Condition));
  53431. BABYLON.PredicateCondition = PredicateCondition;
  53432. /**
  53433. * Defines a state condition as an extension of Condition
  53434. */
  53435. var StateCondition = /** @class */ (function (_super) {
  53436. __extends(StateCondition, _super);
  53437. /**
  53438. * Creates a new StateCondition
  53439. * @param actionManager manager for the action the condition applies to
  53440. * @param target of the condition
  53441. * @param value to compare with target state
  53442. */
  53443. function StateCondition(actionManager, target, value) {
  53444. var _this = _super.call(this, actionManager) || this;
  53445. _this.value = value;
  53446. _this._target = target;
  53447. return _this;
  53448. }
  53449. /**
  53450. * @returns the validity of the state
  53451. */
  53452. StateCondition.prototype.isValid = function () {
  53453. return this._target.state === this.value;
  53454. };
  53455. /**
  53456. * Serialize the StateCondition into a JSON compatible object
  53457. * @returns serialization object
  53458. */
  53459. StateCondition.prototype.serialize = function () {
  53460. return this._serialize({
  53461. name: "StateCondition",
  53462. properties: [
  53463. BABYLON.Action._GetTargetProperty(this._target),
  53464. { name: "value", value: this.value }
  53465. ]
  53466. });
  53467. };
  53468. return StateCondition;
  53469. }(Condition));
  53470. BABYLON.StateCondition = StateCondition;
  53471. })(BABYLON || (BABYLON = {}));
  53472. //# sourceMappingURL=babylon.condition.js.map
  53473. var BABYLON;
  53474. (function (BABYLON) {
  53475. /**
  53476. * The action to be carried out following a trigger
  53477. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53478. */
  53479. var Action = /** @class */ (function () {
  53480. /**
  53481. * Creates a new Action
  53482. * @param triggerOptions the trigger, with or without parameters, for the action
  53483. * @param condition an optional determinant of action
  53484. */
  53485. function Action(
  53486. /** the trigger, with or without parameters, for the action */
  53487. triggerOptions, condition) {
  53488. this.triggerOptions = triggerOptions;
  53489. /**
  53490. * An event triggered prior to action being executed.
  53491. */
  53492. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53493. if (triggerOptions.parameter) {
  53494. this.trigger = triggerOptions.trigger;
  53495. this._triggerParameter = triggerOptions.parameter;
  53496. }
  53497. else {
  53498. this.trigger = triggerOptions;
  53499. }
  53500. this._nextActiveAction = this;
  53501. this._condition = condition;
  53502. }
  53503. /**
  53504. * Internal only
  53505. * @hidden
  53506. */
  53507. Action.prototype._prepare = function () {
  53508. };
  53509. /**
  53510. * Gets the trigger parameters
  53511. * @returns the trigger parameters
  53512. */
  53513. Action.prototype.getTriggerParameter = function () {
  53514. return this._triggerParameter;
  53515. };
  53516. /**
  53517. * Internal only - executes current action event
  53518. * @hidden
  53519. */
  53520. Action.prototype._executeCurrent = function (evt) {
  53521. if (this._nextActiveAction._condition) {
  53522. var condition = this._nextActiveAction._condition;
  53523. var currentRenderId = this._actionManager.getScene().getRenderId();
  53524. // We cache the current evaluation for the current frame
  53525. if (condition._evaluationId === currentRenderId) {
  53526. if (!condition._currentResult) {
  53527. return;
  53528. }
  53529. }
  53530. else {
  53531. condition._evaluationId = currentRenderId;
  53532. if (!condition.isValid()) {
  53533. condition._currentResult = false;
  53534. return;
  53535. }
  53536. condition._currentResult = true;
  53537. }
  53538. }
  53539. this.onBeforeExecuteObservable.notifyObservers(this);
  53540. this._nextActiveAction.execute(evt);
  53541. this.skipToNextActiveAction();
  53542. };
  53543. /**
  53544. * Execute placeholder for child classes
  53545. * @param evt optional action event
  53546. */
  53547. Action.prototype.execute = function (evt) {
  53548. };
  53549. /**
  53550. * Skips to next active action
  53551. */
  53552. Action.prototype.skipToNextActiveAction = function () {
  53553. if (this._nextActiveAction._child) {
  53554. if (!this._nextActiveAction._child._actionManager) {
  53555. this._nextActiveAction._child._actionManager = this._actionManager;
  53556. }
  53557. this._nextActiveAction = this._nextActiveAction._child;
  53558. }
  53559. else {
  53560. this._nextActiveAction = this;
  53561. }
  53562. };
  53563. /**
  53564. * Adds action to chain of actions, may be a DoNothingAction
  53565. * @param action defines the next action to execute
  53566. * @returns The action passed in
  53567. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53568. */
  53569. Action.prototype.then = function (action) {
  53570. this._child = action;
  53571. action._actionManager = this._actionManager;
  53572. action._prepare();
  53573. return action;
  53574. };
  53575. /**
  53576. * Internal only
  53577. * @hidden
  53578. */
  53579. Action.prototype._getProperty = function (propertyPath) {
  53580. return this._actionManager._getProperty(propertyPath);
  53581. };
  53582. /**
  53583. * Internal only
  53584. * @hidden
  53585. */
  53586. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53587. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53588. };
  53589. /**
  53590. * Serialize placeholder for child classes
  53591. * @param parent of child
  53592. * @returns the serialized object
  53593. */
  53594. Action.prototype.serialize = function (parent) {
  53595. };
  53596. /**
  53597. * Internal only called by serialize
  53598. * @hidden
  53599. */
  53600. Action.prototype._serialize = function (serializedAction, parent) {
  53601. var serializationObject = {
  53602. type: 1,
  53603. children: [],
  53604. name: serializedAction.name,
  53605. properties: serializedAction.properties || []
  53606. };
  53607. // Serialize child
  53608. if (this._child) {
  53609. this._child.serialize(serializationObject);
  53610. }
  53611. // Check if "this" has a condition
  53612. if (this._condition) {
  53613. var serializedCondition = this._condition.serialize();
  53614. serializedCondition.children.push(serializationObject);
  53615. if (parent) {
  53616. parent.children.push(serializedCondition);
  53617. }
  53618. return serializedCondition;
  53619. }
  53620. if (parent) {
  53621. parent.children.push(serializationObject);
  53622. }
  53623. return serializationObject;
  53624. };
  53625. /**
  53626. * Internal only
  53627. * @hidden
  53628. */
  53629. Action._SerializeValueAsString = function (value) {
  53630. if (typeof value === "number") {
  53631. return value.toString();
  53632. }
  53633. if (typeof value === "boolean") {
  53634. return value ? "true" : "false";
  53635. }
  53636. if (value instanceof BABYLON.Vector2) {
  53637. return value.x + ", " + value.y;
  53638. }
  53639. if (value instanceof BABYLON.Vector3) {
  53640. return value.x + ", " + value.y + ", " + value.z;
  53641. }
  53642. if (value instanceof BABYLON.Color3) {
  53643. return value.r + ", " + value.g + ", " + value.b;
  53644. }
  53645. if (value instanceof BABYLON.Color4) {
  53646. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53647. }
  53648. return value; // string
  53649. };
  53650. /**
  53651. * Internal only
  53652. * @hidden
  53653. */
  53654. Action._GetTargetProperty = function (target) {
  53655. return {
  53656. name: "target",
  53657. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53658. : target instanceof BABYLON.Light ? "LightProperties"
  53659. : target instanceof BABYLON.Camera ? "CameraProperties"
  53660. : "SceneProperties",
  53661. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53662. };
  53663. };
  53664. return Action;
  53665. }());
  53666. BABYLON.Action = Action;
  53667. })(BABYLON || (BABYLON = {}));
  53668. //# sourceMappingURL=babylon.action.js.map
  53669. var BABYLON;
  53670. (function (BABYLON) {
  53671. /**
  53672. * ActionEvent is the event being sent when an action is triggered.
  53673. */
  53674. var ActionEvent = /** @class */ (function () {
  53675. /**
  53676. * Creates a new ActionEvent
  53677. * @param source The mesh or sprite that triggered the action
  53678. * @param pointerX The X mouse cursor position at the time of the event
  53679. * @param pointerY The Y mouse cursor position at the time of the event
  53680. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53681. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53682. * @param additionalData additional data for the event
  53683. */
  53684. function ActionEvent(
  53685. /** The mesh or sprite that triggered the action */
  53686. source,
  53687. /** The X mouse cursor position at the time of the event */
  53688. pointerX,
  53689. /** The Y mouse cursor position at the time of the event */
  53690. pointerY,
  53691. /** The mesh that is currently pointed at (can be null) */
  53692. meshUnderPointer,
  53693. /** the original (browser) event that triggered the ActionEvent */
  53694. sourceEvent,
  53695. /** additional data for the event */
  53696. additionalData) {
  53697. this.source = source;
  53698. this.pointerX = pointerX;
  53699. this.pointerY = pointerY;
  53700. this.meshUnderPointer = meshUnderPointer;
  53701. this.sourceEvent = sourceEvent;
  53702. this.additionalData = additionalData;
  53703. }
  53704. /**
  53705. * Helper function to auto-create an ActionEvent from a source mesh.
  53706. * @param source The source mesh that triggered the event
  53707. * @param evt The original (browser) event
  53708. * @param additionalData additional data for the event
  53709. * @returns the new ActionEvent
  53710. */
  53711. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53712. var scene = source.getScene();
  53713. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53714. };
  53715. /**
  53716. * Helper function to auto-create an ActionEvent from a source sprite
  53717. * @param source The source sprite that triggered the event
  53718. * @param scene Scene associated with the sprite
  53719. * @param evt The original (browser) event
  53720. * @param additionalData additional data for the event
  53721. * @returns the new ActionEvent
  53722. */
  53723. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53724. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53725. };
  53726. /**
  53727. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53728. * @param scene the scene where the event occurred
  53729. * @param evt The original (browser) event
  53730. * @returns the new ActionEvent
  53731. */
  53732. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53733. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53734. };
  53735. /**
  53736. * Helper function to auto-create an ActionEvent from a primitive
  53737. * @param prim defines the target primitive
  53738. * @param pointerPos defines the pointer position
  53739. * @param evt The original (browser) event
  53740. * @param additionalData additional data for the event
  53741. * @returns the new ActionEvent
  53742. */
  53743. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53744. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53745. };
  53746. return ActionEvent;
  53747. }());
  53748. BABYLON.ActionEvent = ActionEvent;
  53749. /**
  53750. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53751. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53752. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53753. */
  53754. var ActionManager = /** @class */ (function () {
  53755. /**
  53756. * Creates a new action manager
  53757. * @param scene defines the hosting scene
  53758. */
  53759. function ActionManager(scene) {
  53760. // Members
  53761. /** Gets the list of actions */
  53762. this.actions = new Array();
  53763. /** Gets the cursor to use when hovering items */
  53764. this.hoverCursor = '';
  53765. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53766. scene._actionManagers.push(this);
  53767. }
  53768. Object.defineProperty(ActionManager, "NothingTrigger", {
  53769. /**
  53770. * Nothing
  53771. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53772. */
  53773. get: function () {
  53774. return ActionManager._NothingTrigger;
  53775. },
  53776. enumerable: true,
  53777. configurable: true
  53778. });
  53779. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53780. /**
  53781. * On pick
  53782. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53783. */
  53784. get: function () {
  53785. return ActionManager._OnPickTrigger;
  53786. },
  53787. enumerable: true,
  53788. configurable: true
  53789. });
  53790. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53791. /**
  53792. * On left pick
  53793. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53794. */
  53795. get: function () {
  53796. return ActionManager._OnLeftPickTrigger;
  53797. },
  53798. enumerable: true,
  53799. configurable: true
  53800. });
  53801. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53802. /**
  53803. * On right pick
  53804. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53805. */
  53806. get: function () {
  53807. return ActionManager._OnRightPickTrigger;
  53808. },
  53809. enumerable: true,
  53810. configurable: true
  53811. });
  53812. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53813. /**
  53814. * On center pick
  53815. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53816. */
  53817. get: function () {
  53818. return ActionManager._OnCenterPickTrigger;
  53819. },
  53820. enumerable: true,
  53821. configurable: true
  53822. });
  53823. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53824. /**
  53825. * On pick down
  53826. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53827. */
  53828. get: function () {
  53829. return ActionManager._OnPickDownTrigger;
  53830. },
  53831. enumerable: true,
  53832. configurable: true
  53833. });
  53834. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53835. /**
  53836. * On double pick
  53837. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53838. */
  53839. get: function () {
  53840. return ActionManager._OnDoublePickTrigger;
  53841. },
  53842. enumerable: true,
  53843. configurable: true
  53844. });
  53845. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53846. /**
  53847. * On pick up
  53848. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53849. */
  53850. get: function () {
  53851. return ActionManager._OnPickUpTrigger;
  53852. },
  53853. enumerable: true,
  53854. configurable: true
  53855. });
  53856. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53857. /**
  53858. * On pick out.
  53859. * This trigger will only be raised if you also declared a OnPickDown
  53860. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53861. */
  53862. get: function () {
  53863. return ActionManager._OnPickOutTrigger;
  53864. },
  53865. enumerable: true,
  53866. configurable: true
  53867. });
  53868. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53869. /**
  53870. * On long press
  53871. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53872. */
  53873. get: function () {
  53874. return ActionManager._OnLongPressTrigger;
  53875. },
  53876. enumerable: true,
  53877. configurable: true
  53878. });
  53879. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53880. /**
  53881. * On pointer over
  53882. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53883. */
  53884. get: function () {
  53885. return ActionManager._OnPointerOverTrigger;
  53886. },
  53887. enumerable: true,
  53888. configurable: true
  53889. });
  53890. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53891. /**
  53892. * On pointer out
  53893. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53894. */
  53895. get: function () {
  53896. return ActionManager._OnPointerOutTrigger;
  53897. },
  53898. enumerable: true,
  53899. configurable: true
  53900. });
  53901. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53902. /**
  53903. * On every frame
  53904. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53905. */
  53906. get: function () {
  53907. return ActionManager._OnEveryFrameTrigger;
  53908. },
  53909. enumerable: true,
  53910. configurable: true
  53911. });
  53912. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53913. /**
  53914. * On intersection enter
  53915. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53916. */
  53917. get: function () {
  53918. return ActionManager._OnIntersectionEnterTrigger;
  53919. },
  53920. enumerable: true,
  53921. configurable: true
  53922. });
  53923. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53924. /**
  53925. * On intersection exit
  53926. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53927. */
  53928. get: function () {
  53929. return ActionManager._OnIntersectionExitTrigger;
  53930. },
  53931. enumerable: true,
  53932. configurable: true
  53933. });
  53934. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53935. /**
  53936. * On key down
  53937. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53938. */
  53939. get: function () {
  53940. return ActionManager._OnKeyDownTrigger;
  53941. },
  53942. enumerable: true,
  53943. configurable: true
  53944. });
  53945. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53946. /**
  53947. * On key up
  53948. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53949. */
  53950. get: function () {
  53951. return ActionManager._OnKeyUpTrigger;
  53952. },
  53953. enumerable: true,
  53954. configurable: true
  53955. });
  53956. // Methods
  53957. /**
  53958. * Releases all associated resources
  53959. */
  53960. ActionManager.prototype.dispose = function () {
  53961. var index = this._scene._actionManagers.indexOf(this);
  53962. for (var i = 0; i < this.actions.length; i++) {
  53963. var action = this.actions[i];
  53964. ActionManager.Triggers[action.trigger]--;
  53965. if (ActionManager.Triggers[action.trigger] === 0) {
  53966. delete ActionManager.Triggers[action.trigger];
  53967. }
  53968. }
  53969. if (index > -1) {
  53970. this._scene._actionManagers.splice(index, 1);
  53971. }
  53972. };
  53973. /**
  53974. * Gets hosting scene
  53975. * @returns the hosting scene
  53976. */
  53977. ActionManager.prototype.getScene = function () {
  53978. return this._scene;
  53979. };
  53980. /**
  53981. * Does this action manager handles actions of any of the given triggers
  53982. * @param triggers defines the triggers to be tested
  53983. * @return a boolean indicating whether one (or more) of the triggers is handled
  53984. */
  53985. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53986. for (var index = 0; index < this.actions.length; index++) {
  53987. var action = this.actions[index];
  53988. if (triggers.indexOf(action.trigger) > -1) {
  53989. return true;
  53990. }
  53991. }
  53992. return false;
  53993. };
  53994. /**
  53995. * Does this action manager handles actions of a given trigger
  53996. * @param trigger defines the trigger to be tested
  53997. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53998. * @return whether the trigger is handled
  53999. */
  54000. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  54001. for (var index = 0; index < this.actions.length; index++) {
  54002. var action = this.actions[index];
  54003. if (action.trigger === trigger) {
  54004. if (parameterPredicate) {
  54005. if (parameterPredicate(action.getTriggerParameter())) {
  54006. return true;
  54007. }
  54008. }
  54009. else {
  54010. return true;
  54011. }
  54012. }
  54013. }
  54014. return false;
  54015. };
  54016. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  54017. /**
  54018. * Does this action manager has pointer triggers
  54019. */
  54020. get: function () {
  54021. for (var index = 0; index < this.actions.length; index++) {
  54022. var action = this.actions[index];
  54023. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  54024. return true;
  54025. }
  54026. }
  54027. return false;
  54028. },
  54029. enumerable: true,
  54030. configurable: true
  54031. });
  54032. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  54033. /**
  54034. * Does this action manager has pick triggers
  54035. */
  54036. get: function () {
  54037. for (var index = 0; index < this.actions.length; index++) {
  54038. var action = this.actions[index];
  54039. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  54040. return true;
  54041. }
  54042. }
  54043. return false;
  54044. },
  54045. enumerable: true,
  54046. configurable: true
  54047. });
  54048. Object.defineProperty(ActionManager, "HasTriggers", {
  54049. /**
  54050. * Does exist one action manager with at least one trigger
  54051. **/
  54052. get: function () {
  54053. for (var t in ActionManager.Triggers) {
  54054. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54055. return true;
  54056. }
  54057. }
  54058. return false;
  54059. },
  54060. enumerable: true,
  54061. configurable: true
  54062. });
  54063. Object.defineProperty(ActionManager, "HasPickTriggers", {
  54064. /**
  54065. * Does exist one action manager with at least one pick trigger
  54066. **/
  54067. get: function () {
  54068. for (var t in ActionManager.Triggers) {
  54069. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54070. var t_int = parseInt(t);
  54071. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  54072. return true;
  54073. }
  54074. }
  54075. }
  54076. return false;
  54077. },
  54078. enumerable: true,
  54079. configurable: true
  54080. });
  54081. /**
  54082. * Does exist one action manager that handles actions of a given trigger
  54083. * @param trigger defines the trigger to be tested
  54084. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  54085. **/
  54086. ActionManager.HasSpecificTrigger = function (trigger) {
  54087. for (var t in ActionManager.Triggers) {
  54088. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54089. var t_int = parseInt(t);
  54090. if (t_int === trigger) {
  54091. return true;
  54092. }
  54093. }
  54094. }
  54095. return false;
  54096. };
  54097. /**
  54098. * Registers an action to this action manager
  54099. * @param action defines the action to be registered
  54100. * @return the action amended (prepared) after registration
  54101. */
  54102. ActionManager.prototype.registerAction = function (action) {
  54103. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  54104. if (this.getScene().actionManager !== this) {
  54105. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  54106. return null;
  54107. }
  54108. }
  54109. this.actions.push(action);
  54110. if (ActionManager.Triggers[action.trigger]) {
  54111. ActionManager.Triggers[action.trigger]++;
  54112. }
  54113. else {
  54114. ActionManager.Triggers[action.trigger] = 1;
  54115. }
  54116. action._actionManager = this;
  54117. action._prepare();
  54118. return action;
  54119. };
  54120. /**
  54121. * Unregisters an action to this action manager
  54122. * @param action defines the action to be unregistered
  54123. * @return a boolean indicating whether the action has been unregistered
  54124. */
  54125. ActionManager.prototype.unregisterAction = function (action) {
  54126. var index = this.actions.indexOf(action);
  54127. if (index !== -1) {
  54128. this.actions.splice(index, 1);
  54129. ActionManager.Triggers[action.trigger] -= 1;
  54130. if (ActionManager.Triggers[action.trigger] === 0) {
  54131. delete ActionManager.Triggers[action.trigger];
  54132. }
  54133. delete action._actionManager;
  54134. return true;
  54135. }
  54136. return false;
  54137. };
  54138. /**
  54139. * Process a specific trigger
  54140. * @param trigger defines the trigger to process
  54141. * @param evt defines the event details to be processed
  54142. */
  54143. ActionManager.prototype.processTrigger = function (trigger, evt) {
  54144. for (var index = 0; index < this.actions.length; index++) {
  54145. var action = this.actions[index];
  54146. if (action.trigger === trigger) {
  54147. if (evt) {
  54148. if (trigger === ActionManager.OnKeyUpTrigger
  54149. || trigger === ActionManager.OnKeyDownTrigger) {
  54150. var parameter = action.getTriggerParameter();
  54151. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  54152. if (!parameter.toLowerCase) {
  54153. continue;
  54154. }
  54155. var lowerCase = parameter.toLowerCase();
  54156. if (lowerCase !== evt.sourceEvent.key) {
  54157. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  54158. var actualkey = String.fromCharCode(unicode).toLowerCase();
  54159. if (actualkey !== lowerCase) {
  54160. continue;
  54161. }
  54162. }
  54163. }
  54164. }
  54165. }
  54166. action._executeCurrent(evt);
  54167. }
  54168. }
  54169. };
  54170. /** @hidden */
  54171. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  54172. var properties = propertyPath.split(".");
  54173. for (var index = 0; index < properties.length - 1; index++) {
  54174. target = target[properties[index]];
  54175. }
  54176. return target;
  54177. };
  54178. /** @hidden */
  54179. ActionManager.prototype._getProperty = function (propertyPath) {
  54180. var properties = propertyPath.split(".");
  54181. return properties[properties.length - 1];
  54182. };
  54183. /**
  54184. * Serialize this manager to a JSON object
  54185. * @param name defines the property name to store this manager
  54186. * @returns a JSON representation of this manager
  54187. */
  54188. ActionManager.prototype.serialize = function (name) {
  54189. var root = {
  54190. children: new Array(),
  54191. name: name,
  54192. type: 3,
  54193. properties: new Array() // Empty for root but required
  54194. };
  54195. for (var i = 0; i < this.actions.length; i++) {
  54196. var triggerObject = {
  54197. type: 0,
  54198. children: new Array(),
  54199. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  54200. properties: new Array()
  54201. };
  54202. var triggerOptions = this.actions[i].triggerOptions;
  54203. if (triggerOptions && typeof triggerOptions !== "number") {
  54204. if (triggerOptions.parameter instanceof BABYLON.Node) {
  54205. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  54206. }
  54207. else {
  54208. var parameter = {};
  54209. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  54210. if (triggerOptions.parameter.mesh) {
  54211. parameter._meshId = triggerOptions.parameter.mesh.id;
  54212. }
  54213. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  54214. }
  54215. }
  54216. // Serialize child action, recursively
  54217. this.actions[i].serialize(triggerObject);
  54218. // Add serialized trigger
  54219. root.children.push(triggerObject);
  54220. }
  54221. return root;
  54222. };
  54223. /**
  54224. * Creates a new ActionManager from a JSON data
  54225. * @param parsedActions defines the JSON data to read from
  54226. * @param object defines the hosting mesh
  54227. * @param scene defines the hosting scene
  54228. */
  54229. ActionManager.Parse = function (parsedActions, object, scene) {
  54230. var actionManager = new ActionManager(scene);
  54231. if (object === null)
  54232. scene.actionManager = actionManager;
  54233. else
  54234. object.actionManager = actionManager;
  54235. // instanciate a new object
  54236. var instanciate = function (name, params) {
  54237. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  54238. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  54239. newInstance.constructor.apply(newInstance, params);
  54240. return newInstance;
  54241. };
  54242. var parseParameter = function (name, value, target, propertyPath) {
  54243. if (propertyPath === null) {
  54244. // String, boolean or float
  54245. var floatValue = parseFloat(value);
  54246. if (value === "true" || value === "false")
  54247. return value === "true";
  54248. else
  54249. return isNaN(floatValue) ? value : floatValue;
  54250. }
  54251. var effectiveTarget = propertyPath.split(".");
  54252. var values = value.split(",");
  54253. // Get effective Target
  54254. for (var i = 0; i < effectiveTarget.length; i++) {
  54255. target = target[effectiveTarget[i]];
  54256. }
  54257. // Return appropriate value with its type
  54258. if (typeof (target) === "boolean")
  54259. return values[0] === "true";
  54260. if (typeof (target) === "string")
  54261. return values[0];
  54262. // Parameters with multiple values such as Vector3 etc.
  54263. var split = new Array();
  54264. for (var i = 0; i < values.length; i++)
  54265. split.push(parseFloat(values[i]));
  54266. if (target instanceof BABYLON.Vector3)
  54267. return BABYLON.Vector3.FromArray(split);
  54268. if (target instanceof BABYLON.Vector4)
  54269. return BABYLON.Vector4.FromArray(split);
  54270. if (target instanceof BABYLON.Color3)
  54271. return BABYLON.Color3.FromArray(split);
  54272. if (target instanceof BABYLON.Color4)
  54273. return BABYLON.Color4.FromArray(split);
  54274. return parseFloat(values[0]);
  54275. };
  54276. // traverse graph per trigger
  54277. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  54278. if (combineArray === void 0) { combineArray = null; }
  54279. if (parsedAction.detached)
  54280. return;
  54281. var parameters = new Array();
  54282. var target = null;
  54283. var propertyPath = null;
  54284. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  54285. // Parameters
  54286. if (parsedAction.type === 2)
  54287. parameters.push(actionManager);
  54288. else
  54289. parameters.push(trigger);
  54290. if (combine) {
  54291. var actions = new Array();
  54292. for (var j = 0; j < parsedAction.combine.length; j++) {
  54293. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  54294. }
  54295. parameters.push(actions);
  54296. }
  54297. else {
  54298. for (var i = 0; i < parsedAction.properties.length; i++) {
  54299. var value = parsedAction.properties[i].value;
  54300. var name = parsedAction.properties[i].name;
  54301. var targetType = parsedAction.properties[i].targetType;
  54302. if (name === "target")
  54303. if (targetType !== null && targetType === "SceneProperties")
  54304. value = target = scene;
  54305. else
  54306. value = target = scene.getNodeByName(value);
  54307. else if (name === "parent")
  54308. value = scene.getNodeByName(value);
  54309. else if (name === "sound")
  54310. value = scene.getSoundByName(value);
  54311. else if (name !== "propertyPath") {
  54312. if (parsedAction.type === 2 && name === "operator")
  54313. value = BABYLON.ValueCondition[value];
  54314. else
  54315. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  54316. }
  54317. else {
  54318. propertyPath = value;
  54319. }
  54320. parameters.push(value);
  54321. }
  54322. }
  54323. if (combineArray === null) {
  54324. parameters.push(condition);
  54325. }
  54326. else {
  54327. parameters.push(null);
  54328. }
  54329. // If interpolate value action
  54330. if (parsedAction.name === "InterpolateValueAction") {
  54331. var param = parameters[parameters.length - 2];
  54332. parameters[parameters.length - 1] = param;
  54333. parameters[parameters.length - 2] = condition;
  54334. }
  54335. // Action or condition(s) and not CombineAction
  54336. var newAction = instanciate(parsedAction.name, parameters);
  54337. if (newAction instanceof BABYLON.Condition && condition !== null) {
  54338. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  54339. if (action)
  54340. action.then(nothing);
  54341. else
  54342. actionManager.registerAction(nothing);
  54343. action = nothing;
  54344. }
  54345. if (combineArray === null) {
  54346. if (newAction instanceof BABYLON.Condition) {
  54347. condition = newAction;
  54348. newAction = action;
  54349. }
  54350. else {
  54351. condition = null;
  54352. if (action)
  54353. action.then(newAction);
  54354. else
  54355. actionManager.registerAction(newAction);
  54356. }
  54357. }
  54358. else {
  54359. combineArray.push(newAction);
  54360. }
  54361. for (var i = 0; i < parsedAction.children.length; i++)
  54362. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  54363. };
  54364. // triggers
  54365. for (var i = 0; i < parsedActions.children.length; i++) {
  54366. var triggerParams;
  54367. var trigger = parsedActions.children[i];
  54368. if (trigger.properties.length > 0) {
  54369. var param = trigger.properties[0].value;
  54370. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  54371. if (value._meshId) {
  54372. value.mesh = scene.getMeshByID(value._meshId);
  54373. }
  54374. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  54375. }
  54376. else
  54377. triggerParams = ActionManager[trigger.name];
  54378. for (var j = 0; j < trigger.children.length; j++) {
  54379. if (!trigger.detached)
  54380. traverse(trigger.children[j], triggerParams, null, null);
  54381. }
  54382. }
  54383. };
  54384. /**
  54385. * Get a trigger name by index
  54386. * @param trigger defines the trigger index
  54387. * @returns a trigger name
  54388. */
  54389. ActionManager.GetTriggerName = function (trigger) {
  54390. switch (trigger) {
  54391. case 0: return "NothingTrigger";
  54392. case 1: return "OnPickTrigger";
  54393. case 2: return "OnLeftPickTrigger";
  54394. case 3: return "OnRightPickTrigger";
  54395. case 4: return "OnCenterPickTrigger";
  54396. case 5: return "OnPickDownTrigger";
  54397. case 6: return "OnPickUpTrigger";
  54398. case 7: return "OnLongPressTrigger";
  54399. case 8: return "OnPointerOverTrigger";
  54400. case 9: return "OnPointerOutTrigger";
  54401. case 10: return "OnEveryFrameTrigger";
  54402. case 11: return "OnIntersectionEnterTrigger";
  54403. case 12: return "OnIntersectionExitTrigger";
  54404. case 13: return "OnKeyDownTrigger";
  54405. case 14: return "OnKeyUpTrigger";
  54406. case 15: return "OnPickOutTrigger";
  54407. default: return "";
  54408. }
  54409. };
  54410. // Statics
  54411. ActionManager._NothingTrigger = 0;
  54412. ActionManager._OnPickTrigger = 1;
  54413. ActionManager._OnLeftPickTrigger = 2;
  54414. ActionManager._OnRightPickTrigger = 3;
  54415. ActionManager._OnCenterPickTrigger = 4;
  54416. ActionManager._OnPickDownTrigger = 5;
  54417. ActionManager._OnDoublePickTrigger = 6;
  54418. ActionManager._OnPickUpTrigger = 7;
  54419. ActionManager._OnLongPressTrigger = 8;
  54420. ActionManager._OnPointerOverTrigger = 9;
  54421. ActionManager._OnPointerOutTrigger = 10;
  54422. ActionManager._OnEveryFrameTrigger = 11;
  54423. ActionManager._OnIntersectionEnterTrigger = 12;
  54424. ActionManager._OnIntersectionExitTrigger = 13;
  54425. ActionManager._OnKeyDownTrigger = 14;
  54426. ActionManager._OnKeyUpTrigger = 15;
  54427. ActionManager._OnPickOutTrigger = 16;
  54428. /** Gets the list of active triggers */
  54429. ActionManager.Triggers = {};
  54430. return ActionManager;
  54431. }());
  54432. BABYLON.ActionManager = ActionManager;
  54433. })(BABYLON || (BABYLON = {}));
  54434. //# sourceMappingURL=babylon.actionManager.js.map
  54435. var BABYLON;
  54436. (function (BABYLON) {
  54437. var InterpolateValueAction = /** @class */ (function (_super) {
  54438. __extends(InterpolateValueAction, _super);
  54439. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54440. if (duration === void 0) { duration = 1000; }
  54441. var _this = _super.call(this, triggerOptions, condition) || this;
  54442. _this.propertyPath = propertyPath;
  54443. _this.value = value;
  54444. _this.duration = duration;
  54445. _this.stopOtherAnimations = stopOtherAnimations;
  54446. _this.onInterpolationDone = onInterpolationDone;
  54447. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54448. _this._target = _this._effectiveTarget = target;
  54449. return _this;
  54450. }
  54451. InterpolateValueAction.prototype._prepare = function () {
  54452. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54453. this._property = this._getProperty(this.propertyPath);
  54454. };
  54455. InterpolateValueAction.prototype.execute = function () {
  54456. var _this = this;
  54457. var scene = this._actionManager.getScene();
  54458. var keys = [
  54459. {
  54460. frame: 0,
  54461. value: this._effectiveTarget[this._property]
  54462. }, {
  54463. frame: 100,
  54464. value: this.value
  54465. }
  54466. ];
  54467. var dataType;
  54468. if (typeof this.value === "number") {
  54469. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54470. }
  54471. else if (this.value instanceof BABYLON.Color3) {
  54472. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54473. }
  54474. else if (this.value instanceof BABYLON.Vector3) {
  54475. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54476. }
  54477. else if (this.value instanceof BABYLON.Matrix) {
  54478. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54479. }
  54480. else if (this.value instanceof BABYLON.Quaternion) {
  54481. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54482. }
  54483. else {
  54484. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54485. return;
  54486. }
  54487. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54488. animation.setKeys(keys);
  54489. if (this.stopOtherAnimations) {
  54490. scene.stopAnimation(this._effectiveTarget);
  54491. }
  54492. var wrapper = function () {
  54493. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54494. if (_this.onInterpolationDone) {
  54495. _this.onInterpolationDone();
  54496. }
  54497. };
  54498. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54499. };
  54500. InterpolateValueAction.prototype.serialize = function (parent) {
  54501. return _super.prototype._serialize.call(this, {
  54502. name: "InterpolateValueAction",
  54503. properties: [
  54504. BABYLON.Action._GetTargetProperty(this._target),
  54505. { name: "propertyPath", value: this.propertyPath },
  54506. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54507. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54508. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54509. ]
  54510. }, parent);
  54511. };
  54512. return InterpolateValueAction;
  54513. }(BABYLON.Action));
  54514. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54515. })(BABYLON || (BABYLON = {}));
  54516. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54517. var BABYLON;
  54518. (function (BABYLON) {
  54519. var SwitchBooleanAction = /** @class */ (function (_super) {
  54520. __extends(SwitchBooleanAction, _super);
  54521. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54522. var _this = _super.call(this, triggerOptions, condition) || this;
  54523. _this.propertyPath = propertyPath;
  54524. _this._target = _this._effectiveTarget = target;
  54525. return _this;
  54526. }
  54527. SwitchBooleanAction.prototype._prepare = function () {
  54528. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54529. this._property = this._getProperty(this.propertyPath);
  54530. };
  54531. SwitchBooleanAction.prototype.execute = function () {
  54532. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54533. };
  54534. SwitchBooleanAction.prototype.serialize = function (parent) {
  54535. return _super.prototype._serialize.call(this, {
  54536. name: "SwitchBooleanAction",
  54537. properties: [
  54538. BABYLON.Action._GetTargetProperty(this._target),
  54539. { name: "propertyPath", value: this.propertyPath }
  54540. ]
  54541. }, parent);
  54542. };
  54543. return SwitchBooleanAction;
  54544. }(BABYLON.Action));
  54545. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54546. var SetStateAction = /** @class */ (function (_super) {
  54547. __extends(SetStateAction, _super);
  54548. function SetStateAction(triggerOptions, target, value, condition) {
  54549. var _this = _super.call(this, triggerOptions, condition) || this;
  54550. _this.value = value;
  54551. _this._target = target;
  54552. return _this;
  54553. }
  54554. SetStateAction.prototype.execute = function () {
  54555. this._target.state = this.value;
  54556. };
  54557. SetStateAction.prototype.serialize = function (parent) {
  54558. return _super.prototype._serialize.call(this, {
  54559. name: "SetStateAction",
  54560. properties: [
  54561. BABYLON.Action._GetTargetProperty(this._target),
  54562. { name: "value", value: this.value }
  54563. ]
  54564. }, parent);
  54565. };
  54566. return SetStateAction;
  54567. }(BABYLON.Action));
  54568. BABYLON.SetStateAction = SetStateAction;
  54569. var SetValueAction = /** @class */ (function (_super) {
  54570. __extends(SetValueAction, _super);
  54571. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54572. var _this = _super.call(this, triggerOptions, condition) || this;
  54573. _this.propertyPath = propertyPath;
  54574. _this.value = value;
  54575. _this._target = _this._effectiveTarget = target;
  54576. return _this;
  54577. }
  54578. SetValueAction.prototype._prepare = function () {
  54579. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54580. this._property = this._getProperty(this.propertyPath);
  54581. };
  54582. SetValueAction.prototype.execute = function () {
  54583. this._effectiveTarget[this._property] = this.value;
  54584. if (this._target.markAsDirty) {
  54585. this._target.markAsDirty(this._property);
  54586. }
  54587. };
  54588. SetValueAction.prototype.serialize = function (parent) {
  54589. return _super.prototype._serialize.call(this, {
  54590. name: "SetValueAction",
  54591. properties: [
  54592. BABYLON.Action._GetTargetProperty(this._target),
  54593. { name: "propertyPath", value: this.propertyPath },
  54594. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54595. ]
  54596. }, parent);
  54597. };
  54598. return SetValueAction;
  54599. }(BABYLON.Action));
  54600. BABYLON.SetValueAction = SetValueAction;
  54601. var IncrementValueAction = /** @class */ (function (_super) {
  54602. __extends(IncrementValueAction, _super);
  54603. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54604. var _this = _super.call(this, triggerOptions, condition) || this;
  54605. _this.propertyPath = propertyPath;
  54606. _this.value = value;
  54607. _this._target = _this._effectiveTarget = target;
  54608. return _this;
  54609. }
  54610. IncrementValueAction.prototype._prepare = function () {
  54611. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54612. this._property = this._getProperty(this.propertyPath);
  54613. if (typeof this._effectiveTarget[this._property] !== "number") {
  54614. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54615. }
  54616. };
  54617. IncrementValueAction.prototype.execute = function () {
  54618. this._effectiveTarget[this._property] += this.value;
  54619. if (this._target.markAsDirty) {
  54620. this._target.markAsDirty(this._property);
  54621. }
  54622. };
  54623. IncrementValueAction.prototype.serialize = function (parent) {
  54624. return _super.prototype._serialize.call(this, {
  54625. name: "IncrementValueAction",
  54626. properties: [
  54627. BABYLON.Action._GetTargetProperty(this._target),
  54628. { name: "propertyPath", value: this.propertyPath },
  54629. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54630. ]
  54631. }, parent);
  54632. };
  54633. return IncrementValueAction;
  54634. }(BABYLON.Action));
  54635. BABYLON.IncrementValueAction = IncrementValueAction;
  54636. var PlayAnimationAction = /** @class */ (function (_super) {
  54637. __extends(PlayAnimationAction, _super);
  54638. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54639. var _this = _super.call(this, triggerOptions, condition) || this;
  54640. _this.from = from;
  54641. _this.to = to;
  54642. _this.loop = loop;
  54643. _this._target = target;
  54644. return _this;
  54645. }
  54646. PlayAnimationAction.prototype._prepare = function () {
  54647. };
  54648. PlayAnimationAction.prototype.execute = function () {
  54649. var scene = this._actionManager.getScene();
  54650. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54651. };
  54652. PlayAnimationAction.prototype.serialize = function (parent) {
  54653. return _super.prototype._serialize.call(this, {
  54654. name: "PlayAnimationAction",
  54655. properties: [
  54656. BABYLON.Action._GetTargetProperty(this._target),
  54657. { name: "from", value: String(this.from) },
  54658. { name: "to", value: String(this.to) },
  54659. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54660. ]
  54661. }, parent);
  54662. };
  54663. return PlayAnimationAction;
  54664. }(BABYLON.Action));
  54665. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54666. var StopAnimationAction = /** @class */ (function (_super) {
  54667. __extends(StopAnimationAction, _super);
  54668. function StopAnimationAction(triggerOptions, target, condition) {
  54669. var _this = _super.call(this, triggerOptions, condition) || this;
  54670. _this._target = target;
  54671. return _this;
  54672. }
  54673. StopAnimationAction.prototype._prepare = function () {
  54674. };
  54675. StopAnimationAction.prototype.execute = function () {
  54676. var scene = this._actionManager.getScene();
  54677. scene.stopAnimation(this._target);
  54678. };
  54679. StopAnimationAction.prototype.serialize = function (parent) {
  54680. return _super.prototype._serialize.call(this, {
  54681. name: "StopAnimationAction",
  54682. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54683. }, parent);
  54684. };
  54685. return StopAnimationAction;
  54686. }(BABYLON.Action));
  54687. BABYLON.StopAnimationAction = StopAnimationAction;
  54688. var DoNothingAction = /** @class */ (function (_super) {
  54689. __extends(DoNothingAction, _super);
  54690. function DoNothingAction(triggerOptions, condition) {
  54691. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54692. return _super.call(this, triggerOptions, condition) || this;
  54693. }
  54694. DoNothingAction.prototype.execute = function () {
  54695. };
  54696. DoNothingAction.prototype.serialize = function (parent) {
  54697. return _super.prototype._serialize.call(this, {
  54698. name: "DoNothingAction",
  54699. properties: []
  54700. }, parent);
  54701. };
  54702. return DoNothingAction;
  54703. }(BABYLON.Action));
  54704. BABYLON.DoNothingAction = DoNothingAction;
  54705. var CombineAction = /** @class */ (function (_super) {
  54706. __extends(CombineAction, _super);
  54707. function CombineAction(triggerOptions, children, condition) {
  54708. var _this = _super.call(this, triggerOptions, condition) || this;
  54709. _this.children = children;
  54710. return _this;
  54711. }
  54712. CombineAction.prototype._prepare = function () {
  54713. for (var index = 0; index < this.children.length; index++) {
  54714. this.children[index]._actionManager = this._actionManager;
  54715. this.children[index]._prepare();
  54716. }
  54717. };
  54718. CombineAction.prototype.execute = function (evt) {
  54719. for (var index = 0; index < this.children.length; index++) {
  54720. this.children[index].execute(evt);
  54721. }
  54722. };
  54723. CombineAction.prototype.serialize = function (parent) {
  54724. var serializationObject = _super.prototype._serialize.call(this, {
  54725. name: "CombineAction",
  54726. properties: [],
  54727. combine: []
  54728. }, parent);
  54729. for (var i = 0; i < this.children.length; i++) {
  54730. serializationObject.combine.push(this.children[i].serialize(null));
  54731. }
  54732. return serializationObject;
  54733. };
  54734. return CombineAction;
  54735. }(BABYLON.Action));
  54736. BABYLON.CombineAction = CombineAction;
  54737. var ExecuteCodeAction = /** @class */ (function (_super) {
  54738. __extends(ExecuteCodeAction, _super);
  54739. function ExecuteCodeAction(triggerOptions, func, condition) {
  54740. var _this = _super.call(this, triggerOptions, condition) || this;
  54741. _this.func = func;
  54742. return _this;
  54743. }
  54744. ExecuteCodeAction.prototype.execute = function (evt) {
  54745. this.func(evt);
  54746. };
  54747. return ExecuteCodeAction;
  54748. }(BABYLON.Action));
  54749. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54750. var SetParentAction = /** @class */ (function (_super) {
  54751. __extends(SetParentAction, _super);
  54752. function SetParentAction(triggerOptions, target, parent, condition) {
  54753. var _this = _super.call(this, triggerOptions, condition) || this;
  54754. _this._target = target;
  54755. _this._parent = parent;
  54756. return _this;
  54757. }
  54758. SetParentAction.prototype._prepare = function () {
  54759. };
  54760. SetParentAction.prototype.execute = function () {
  54761. if (this._target.parent === this._parent) {
  54762. return;
  54763. }
  54764. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54765. invertParentWorldMatrix.invert();
  54766. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54767. this._target.parent = this._parent;
  54768. };
  54769. SetParentAction.prototype.serialize = function (parent) {
  54770. return _super.prototype._serialize.call(this, {
  54771. name: "SetParentAction",
  54772. properties: [
  54773. BABYLON.Action._GetTargetProperty(this._target),
  54774. BABYLON.Action._GetTargetProperty(this._parent),
  54775. ]
  54776. }, parent);
  54777. };
  54778. return SetParentAction;
  54779. }(BABYLON.Action));
  54780. BABYLON.SetParentAction = SetParentAction;
  54781. var PlaySoundAction = /** @class */ (function (_super) {
  54782. __extends(PlaySoundAction, _super);
  54783. function PlaySoundAction(triggerOptions, sound, condition) {
  54784. var _this = _super.call(this, triggerOptions, condition) || this;
  54785. _this._sound = sound;
  54786. return _this;
  54787. }
  54788. PlaySoundAction.prototype._prepare = function () {
  54789. };
  54790. PlaySoundAction.prototype.execute = function () {
  54791. if (this._sound !== undefined)
  54792. this._sound.play();
  54793. };
  54794. PlaySoundAction.prototype.serialize = function (parent) {
  54795. return _super.prototype._serialize.call(this, {
  54796. name: "PlaySoundAction",
  54797. properties: [{ name: "sound", value: this._sound.name }]
  54798. }, parent);
  54799. };
  54800. return PlaySoundAction;
  54801. }(BABYLON.Action));
  54802. BABYLON.PlaySoundAction = PlaySoundAction;
  54803. var StopSoundAction = /** @class */ (function (_super) {
  54804. __extends(StopSoundAction, _super);
  54805. function StopSoundAction(triggerOptions, sound, condition) {
  54806. var _this = _super.call(this, triggerOptions, condition) || this;
  54807. _this._sound = sound;
  54808. return _this;
  54809. }
  54810. StopSoundAction.prototype._prepare = function () {
  54811. };
  54812. StopSoundAction.prototype.execute = function () {
  54813. if (this._sound !== undefined)
  54814. this._sound.stop();
  54815. };
  54816. StopSoundAction.prototype.serialize = function (parent) {
  54817. return _super.prototype._serialize.call(this, {
  54818. name: "StopSoundAction",
  54819. properties: [{ name: "sound", value: this._sound.name }]
  54820. }, parent);
  54821. };
  54822. return StopSoundAction;
  54823. }(BABYLON.Action));
  54824. BABYLON.StopSoundAction = StopSoundAction;
  54825. })(BABYLON || (BABYLON = {}));
  54826. //# sourceMappingURL=babylon.directActions.js.map
  54827. var BABYLON;
  54828. (function (BABYLON) {
  54829. var SpriteManager = /** @class */ (function () {
  54830. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54831. if (epsilon === void 0) { epsilon = 0.01; }
  54832. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54833. this.name = name;
  54834. this.sprites = new Array();
  54835. this.renderingGroupId = 0;
  54836. this.layerMask = 0x0FFFFFFF;
  54837. this.fogEnabled = true;
  54838. this.isPickable = false;
  54839. /**
  54840. * An event triggered when the manager is disposed.
  54841. */
  54842. this.onDisposeObservable = new BABYLON.Observable();
  54843. this._vertexBuffers = {};
  54844. this._capacity = capacity;
  54845. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54846. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54847. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54848. if (cellSize.width && cellSize.height) {
  54849. this.cellWidth = cellSize.width;
  54850. this.cellHeight = cellSize.height;
  54851. }
  54852. else if (cellSize !== undefined) {
  54853. this.cellWidth = cellSize;
  54854. this.cellHeight = cellSize;
  54855. }
  54856. else {
  54857. return;
  54858. }
  54859. this._epsilon = epsilon;
  54860. this._scene = scene;
  54861. this._scene.spriteManagers.push(this);
  54862. var indices = [];
  54863. var index = 0;
  54864. for (var count = 0; count < capacity; count++) {
  54865. indices.push(index);
  54866. indices.push(index + 1);
  54867. indices.push(index + 2);
  54868. indices.push(index);
  54869. indices.push(index + 2);
  54870. indices.push(index + 3);
  54871. index += 4;
  54872. }
  54873. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54874. // VBO
  54875. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54876. this._vertexData = new Float32Array(capacity * 16 * 4);
  54877. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54878. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54879. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54880. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54881. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54882. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54883. this._vertexBuffers["options"] = options;
  54884. this._vertexBuffers["cellInfo"] = cellInfo;
  54885. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54886. // Effects
  54887. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54888. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54889. }
  54890. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54891. set: function (callback) {
  54892. if (this._onDisposeObserver) {
  54893. this.onDisposeObservable.remove(this._onDisposeObserver);
  54894. }
  54895. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54896. },
  54897. enumerable: true,
  54898. configurable: true
  54899. });
  54900. Object.defineProperty(SpriteManager.prototype, "texture", {
  54901. get: function () {
  54902. return this._spriteTexture;
  54903. },
  54904. set: function (value) {
  54905. this._spriteTexture = value;
  54906. },
  54907. enumerable: true,
  54908. configurable: true
  54909. });
  54910. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54911. var arrayOffset = index * 16;
  54912. if (offsetX === 0)
  54913. offsetX = this._epsilon;
  54914. else if (offsetX === 1)
  54915. offsetX = 1 - this._epsilon;
  54916. if (offsetY === 0)
  54917. offsetY = this._epsilon;
  54918. else if (offsetY === 1)
  54919. offsetY = 1 - this._epsilon;
  54920. this._vertexData[arrayOffset] = sprite.position.x;
  54921. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54922. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54923. this._vertexData[arrayOffset + 3] = sprite.angle;
  54924. this._vertexData[arrayOffset + 4] = sprite.width;
  54925. this._vertexData[arrayOffset + 5] = sprite.height;
  54926. this._vertexData[arrayOffset + 6] = offsetX;
  54927. this._vertexData[arrayOffset + 7] = offsetY;
  54928. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54929. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54930. var offset = (sprite.cellIndex / rowSize) >> 0;
  54931. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54932. this._vertexData[arrayOffset + 11] = offset;
  54933. // Color
  54934. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54935. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54936. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54937. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54938. };
  54939. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54940. var count = Math.min(this._capacity, this.sprites.length);
  54941. var min = BABYLON.Vector3.Zero();
  54942. var max = BABYLON.Vector3.Zero();
  54943. var distance = Number.MAX_VALUE;
  54944. var currentSprite = null;
  54945. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54946. var cameraView = camera.getViewMatrix();
  54947. for (var index = 0; index < count; index++) {
  54948. var sprite = this.sprites[index];
  54949. if (!sprite) {
  54950. continue;
  54951. }
  54952. if (predicate) {
  54953. if (!predicate(sprite)) {
  54954. continue;
  54955. }
  54956. }
  54957. else if (!sprite.isPickable) {
  54958. continue;
  54959. }
  54960. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54961. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54962. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54963. if (ray.intersectsBoxMinMax(min, max)) {
  54964. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54965. if (distance > currentDistance) {
  54966. distance = currentDistance;
  54967. currentSprite = sprite;
  54968. if (fastCheck) {
  54969. break;
  54970. }
  54971. }
  54972. }
  54973. }
  54974. if (currentSprite) {
  54975. var result = new BABYLON.PickingInfo();
  54976. result.hit = true;
  54977. result.pickedSprite = currentSprite;
  54978. result.distance = distance;
  54979. return result;
  54980. }
  54981. return null;
  54982. };
  54983. SpriteManager.prototype.render = function () {
  54984. // Check
  54985. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54986. return;
  54987. var engine = this._scene.getEngine();
  54988. var baseSize = this._spriteTexture.getBaseSize();
  54989. // Sprites
  54990. var deltaTime = engine.getDeltaTime();
  54991. var max = Math.min(this._capacity, this.sprites.length);
  54992. var rowSize = baseSize.width / this.cellWidth;
  54993. var offset = 0;
  54994. for (var index = 0; index < max; index++) {
  54995. var sprite = this.sprites[index];
  54996. if (!sprite) {
  54997. continue;
  54998. }
  54999. sprite._animate(deltaTime);
  55000. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  55001. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  55002. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  55003. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  55004. }
  55005. this._buffer.update(this._vertexData);
  55006. // Render
  55007. var effect = this._effectBase;
  55008. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  55009. effect = this._effectFog;
  55010. }
  55011. engine.enableEffect(effect);
  55012. var viewMatrix = this._scene.getViewMatrix();
  55013. effect.setTexture("diffuseSampler", this._spriteTexture);
  55014. effect.setMatrix("view", viewMatrix);
  55015. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55016. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  55017. // Fog
  55018. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  55019. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  55020. effect.setColor3("vFogColor", this._scene.fogColor);
  55021. }
  55022. // VBOs
  55023. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55024. // Draw order
  55025. engine.setDepthFunctionToLessOrEqual();
  55026. effect.setBool("alphaTest", true);
  55027. engine.setColorWrite(false);
  55028. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  55029. engine.setColorWrite(true);
  55030. effect.setBool("alphaTest", false);
  55031. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55032. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  55033. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55034. };
  55035. SpriteManager.prototype.dispose = function () {
  55036. if (this._buffer) {
  55037. this._buffer.dispose();
  55038. this._buffer = null;
  55039. }
  55040. if (this._indexBuffer) {
  55041. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55042. this._indexBuffer = null;
  55043. }
  55044. if (this._spriteTexture) {
  55045. this._spriteTexture.dispose();
  55046. this._spriteTexture = null;
  55047. }
  55048. // Remove from scene
  55049. var index = this._scene.spriteManagers.indexOf(this);
  55050. this._scene.spriteManagers.splice(index, 1);
  55051. // Callback
  55052. this.onDisposeObservable.notifyObservers(this);
  55053. this.onDisposeObservable.clear();
  55054. };
  55055. return SpriteManager;
  55056. }());
  55057. BABYLON.SpriteManager = SpriteManager;
  55058. })(BABYLON || (BABYLON = {}));
  55059. //# sourceMappingURL=babylon.spriteManager.js.map
  55060. var BABYLON;
  55061. (function (BABYLON) {
  55062. var Sprite = /** @class */ (function () {
  55063. function Sprite(name, manager) {
  55064. this.name = name;
  55065. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55066. this.width = 1.0;
  55067. this.height = 1.0;
  55068. this.angle = 0;
  55069. this.cellIndex = 0;
  55070. this.invertU = 0;
  55071. this.invertV = 0;
  55072. this.animations = new Array();
  55073. this.isPickable = false;
  55074. this._animationStarted = false;
  55075. this._loopAnimation = false;
  55076. this._fromIndex = 0;
  55077. this._toIndex = 0;
  55078. this._delay = 0;
  55079. this._direction = 1;
  55080. this._time = 0;
  55081. this._manager = manager;
  55082. this._manager.sprites.push(this);
  55083. this.position = BABYLON.Vector3.Zero();
  55084. }
  55085. Object.defineProperty(Sprite.prototype, "size", {
  55086. get: function () {
  55087. return this.width;
  55088. },
  55089. set: function (value) {
  55090. this.width = value;
  55091. this.height = value;
  55092. },
  55093. enumerable: true,
  55094. configurable: true
  55095. });
  55096. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  55097. this._fromIndex = from;
  55098. this._toIndex = to;
  55099. this._loopAnimation = loop;
  55100. this._delay = delay;
  55101. this._animationStarted = true;
  55102. this._direction = from < to ? 1 : -1;
  55103. this.cellIndex = from;
  55104. this._time = 0;
  55105. this._onAnimationEnd = onAnimationEnd;
  55106. };
  55107. Sprite.prototype.stopAnimation = function () {
  55108. this._animationStarted = false;
  55109. };
  55110. Sprite.prototype._animate = function (deltaTime) {
  55111. if (!this._animationStarted)
  55112. return;
  55113. this._time += deltaTime;
  55114. if (this._time > this._delay) {
  55115. this._time = this._time % this._delay;
  55116. this.cellIndex += this._direction;
  55117. if (this.cellIndex > this._toIndex) {
  55118. if (this._loopAnimation) {
  55119. this.cellIndex = this._fromIndex;
  55120. }
  55121. else {
  55122. this.cellIndex = this._toIndex;
  55123. this._animationStarted = false;
  55124. if (this._onAnimationEnd) {
  55125. this._onAnimationEnd();
  55126. }
  55127. if (this.disposeWhenFinishedAnimating) {
  55128. this.dispose();
  55129. }
  55130. }
  55131. }
  55132. }
  55133. };
  55134. Sprite.prototype.dispose = function () {
  55135. for (var i = 0; i < this._manager.sprites.length; i++) {
  55136. if (this._manager.sprites[i] == this) {
  55137. this._manager.sprites.splice(i, 1);
  55138. }
  55139. }
  55140. };
  55141. return Sprite;
  55142. }());
  55143. BABYLON.Sprite = Sprite;
  55144. })(BABYLON || (BABYLON = {}));
  55145. //# sourceMappingURL=babylon.sprite.js.map
  55146. var BABYLON;
  55147. (function (BABYLON) {
  55148. var IntersectionInfo = /** @class */ (function () {
  55149. function IntersectionInfo(bu, bv, distance) {
  55150. this.bu = bu;
  55151. this.bv = bv;
  55152. this.distance = distance;
  55153. this.faceId = 0;
  55154. this.subMeshId = 0;
  55155. }
  55156. return IntersectionInfo;
  55157. }());
  55158. BABYLON.IntersectionInfo = IntersectionInfo;
  55159. /**
  55160. * Information about the result of picking within a scene
  55161. * See https://doc.babylonjs.com/babylon101/picking_collisions
  55162. */
  55163. var PickingInfo = /** @class */ (function () {
  55164. function PickingInfo() {
  55165. /**
  55166. * If the pick collided with an object
  55167. */
  55168. this.hit = false;
  55169. /**
  55170. * Distance away where the pick collided
  55171. */
  55172. this.distance = 0;
  55173. /**
  55174. * The location of pick collision
  55175. */
  55176. this.pickedPoint = null;
  55177. /**
  55178. * The mesh corrisponding the the pick collision
  55179. */
  55180. this.pickedMesh = null;
  55181. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  55182. this.bu = 0;
  55183. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  55184. this.bv = 0;
  55185. /** The id of the face on the mesh that was picked */
  55186. this.faceId = -1;
  55187. /** Id of the the submesh that was picked */
  55188. this.subMeshId = 0;
  55189. /** If a sprite was picked, this will be the sprite the pick collided with */
  55190. this.pickedSprite = null;
  55191. /**
  55192. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  55193. */
  55194. this.originMesh = null;
  55195. /**
  55196. * The ray that was used to perform the picking.
  55197. */
  55198. this.ray = null;
  55199. }
  55200. /**
  55201. * Gets the normal corrispodning to the face the pick collided with
  55202. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  55203. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  55204. * @returns The normal corrispodning to the face the pick collided with
  55205. */
  55206. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  55207. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  55208. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  55209. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  55210. return null;
  55211. }
  55212. var indices = this.pickedMesh.getIndices();
  55213. if (!indices) {
  55214. return null;
  55215. }
  55216. var result;
  55217. if (useVerticesNormals) {
  55218. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55219. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  55220. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  55221. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  55222. normal0 = normal0.scale(this.bu);
  55223. normal1 = normal1.scale(this.bv);
  55224. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  55225. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  55226. }
  55227. else {
  55228. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55229. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  55230. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  55231. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  55232. var p1p2 = vertex1.subtract(vertex2);
  55233. var p3p2 = vertex3.subtract(vertex2);
  55234. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  55235. }
  55236. if (useWorldCoordinates) {
  55237. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  55238. }
  55239. return BABYLON.Vector3.Normalize(result);
  55240. };
  55241. /**
  55242. * Gets the texture coordinates of where the pick occured
  55243. * @returns the vector containing the coordnates of the texture
  55244. */
  55245. PickingInfo.prototype.getTextureCoordinates = function () {
  55246. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55247. return null;
  55248. }
  55249. var indices = this.pickedMesh.getIndices();
  55250. if (!indices) {
  55251. return null;
  55252. }
  55253. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55254. if (!uvs) {
  55255. return null;
  55256. }
  55257. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  55258. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  55259. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  55260. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  55261. uv1 = uv1.scale(this.bu);
  55262. uv2 = uv2.scale(this.bv);
  55263. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  55264. };
  55265. return PickingInfo;
  55266. }());
  55267. BABYLON.PickingInfo = PickingInfo;
  55268. })(BABYLON || (BABYLON = {}));
  55269. //# sourceMappingURL=babylon.pickingInfo.js.map
  55270. var BABYLON;
  55271. (function (BABYLON) {
  55272. var Ray = /** @class */ (function () {
  55273. function Ray(origin, direction, length) {
  55274. if (length === void 0) { length = Number.MAX_VALUE; }
  55275. this.origin = origin;
  55276. this.direction = direction;
  55277. this.length = length;
  55278. }
  55279. // Methods
  55280. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  55281. var d = 0.0;
  55282. var maxValue = Number.MAX_VALUE;
  55283. var inv;
  55284. var min;
  55285. var max;
  55286. var temp;
  55287. if (Math.abs(this.direction.x) < 0.0000001) {
  55288. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  55289. return false;
  55290. }
  55291. }
  55292. else {
  55293. inv = 1.0 / this.direction.x;
  55294. min = (minimum.x - this.origin.x) * inv;
  55295. max = (maximum.x - this.origin.x) * inv;
  55296. if (max === -Infinity) {
  55297. max = Infinity;
  55298. }
  55299. if (min > max) {
  55300. temp = min;
  55301. min = max;
  55302. max = temp;
  55303. }
  55304. d = Math.max(min, d);
  55305. maxValue = Math.min(max, maxValue);
  55306. if (d > maxValue) {
  55307. return false;
  55308. }
  55309. }
  55310. if (Math.abs(this.direction.y) < 0.0000001) {
  55311. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  55312. return false;
  55313. }
  55314. }
  55315. else {
  55316. inv = 1.0 / this.direction.y;
  55317. min = (minimum.y - this.origin.y) * inv;
  55318. max = (maximum.y - this.origin.y) * inv;
  55319. if (max === -Infinity) {
  55320. max = Infinity;
  55321. }
  55322. if (min > max) {
  55323. temp = min;
  55324. min = max;
  55325. max = temp;
  55326. }
  55327. d = Math.max(min, d);
  55328. maxValue = Math.min(max, maxValue);
  55329. if (d > maxValue) {
  55330. return false;
  55331. }
  55332. }
  55333. if (Math.abs(this.direction.z) < 0.0000001) {
  55334. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  55335. return false;
  55336. }
  55337. }
  55338. else {
  55339. inv = 1.0 / this.direction.z;
  55340. min = (minimum.z - this.origin.z) * inv;
  55341. max = (maximum.z - this.origin.z) * inv;
  55342. if (max === -Infinity) {
  55343. max = Infinity;
  55344. }
  55345. if (min > max) {
  55346. temp = min;
  55347. min = max;
  55348. max = temp;
  55349. }
  55350. d = Math.max(min, d);
  55351. maxValue = Math.min(max, maxValue);
  55352. if (d > maxValue) {
  55353. return false;
  55354. }
  55355. }
  55356. return true;
  55357. };
  55358. Ray.prototype.intersectsBox = function (box) {
  55359. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  55360. };
  55361. Ray.prototype.intersectsSphere = function (sphere) {
  55362. var x = sphere.center.x - this.origin.x;
  55363. var y = sphere.center.y - this.origin.y;
  55364. var z = sphere.center.z - this.origin.z;
  55365. var pyth = (x * x) + (y * y) + (z * z);
  55366. var rr = sphere.radius * sphere.radius;
  55367. if (pyth <= rr) {
  55368. return true;
  55369. }
  55370. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  55371. if (dot < 0.0) {
  55372. return false;
  55373. }
  55374. var temp = pyth - (dot * dot);
  55375. return temp <= rr;
  55376. };
  55377. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  55378. if (!this._edge1) {
  55379. this._edge1 = BABYLON.Vector3.Zero();
  55380. this._edge2 = BABYLON.Vector3.Zero();
  55381. this._pvec = BABYLON.Vector3.Zero();
  55382. this._tvec = BABYLON.Vector3.Zero();
  55383. this._qvec = BABYLON.Vector3.Zero();
  55384. }
  55385. vertex1.subtractToRef(vertex0, this._edge1);
  55386. vertex2.subtractToRef(vertex0, this._edge2);
  55387. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  55388. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  55389. if (det === 0) {
  55390. return null;
  55391. }
  55392. var invdet = 1 / det;
  55393. this.origin.subtractToRef(vertex0, this._tvec);
  55394. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  55395. if (bu < 0 || bu > 1.0) {
  55396. return null;
  55397. }
  55398. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  55399. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  55400. if (bv < 0 || bu + bv > 1.0) {
  55401. return null;
  55402. }
  55403. //check if the distance is longer than the predefined length.
  55404. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  55405. if (distance > this.length) {
  55406. return null;
  55407. }
  55408. return new BABYLON.IntersectionInfo(bu, bv, distance);
  55409. };
  55410. Ray.prototype.intersectsPlane = function (plane) {
  55411. var distance;
  55412. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  55413. if (Math.abs(result1) < 9.99999997475243E-07) {
  55414. return null;
  55415. }
  55416. else {
  55417. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  55418. distance = (-plane.d - result2) / result1;
  55419. if (distance < 0.0) {
  55420. if (distance < -9.99999997475243E-07) {
  55421. return null;
  55422. }
  55423. else {
  55424. return 0;
  55425. }
  55426. }
  55427. return distance;
  55428. }
  55429. };
  55430. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55431. var tm = BABYLON.Tmp.Matrix[0];
  55432. mesh.getWorldMatrix().invertToRef(tm);
  55433. if (this._tmpRay) {
  55434. Ray.TransformToRef(this, tm, this._tmpRay);
  55435. }
  55436. else {
  55437. this._tmpRay = Ray.Transform(this, tm);
  55438. }
  55439. return mesh.intersects(this._tmpRay, fastCheck);
  55440. };
  55441. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55442. if (results) {
  55443. results.length = 0;
  55444. }
  55445. else {
  55446. results = [];
  55447. }
  55448. for (var i = 0; i < meshes.length; i++) {
  55449. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55450. if (pickInfo.hit) {
  55451. results.push(pickInfo);
  55452. }
  55453. }
  55454. results.sort(this._comparePickingInfo);
  55455. return results;
  55456. };
  55457. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55458. if (pickingInfoA.distance < pickingInfoB.distance) {
  55459. return -1;
  55460. }
  55461. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55462. return 1;
  55463. }
  55464. else {
  55465. return 0;
  55466. }
  55467. };
  55468. /**
  55469. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55470. * @param sega the first point of the segment to test the intersection against
  55471. * @param segb the second point of the segment to test the intersection against
  55472. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55473. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55474. */
  55475. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55476. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55477. var u = segb.subtract(sega);
  55478. var v = rsegb.subtract(this.origin);
  55479. var w = sega.subtract(this.origin);
  55480. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55481. var b = BABYLON.Vector3.Dot(u, v);
  55482. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55483. var d = BABYLON.Vector3.Dot(u, w);
  55484. var e = BABYLON.Vector3.Dot(v, w);
  55485. var D = a * c - b * b; // always >= 0
  55486. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55487. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55488. // compute the line parameters of the two closest points
  55489. if (D < Ray.smallnum) { // the lines are almost parallel
  55490. sN = 0.0; // force using point P0 on segment S1
  55491. sD = 1.0; // to prevent possible division by 0.0 later
  55492. tN = e;
  55493. tD = c;
  55494. }
  55495. else { // get the closest points on the infinite lines
  55496. sN = (b * e - c * d);
  55497. tN = (a * e - b * d);
  55498. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55499. sN = 0.0;
  55500. tN = e;
  55501. tD = c;
  55502. }
  55503. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55504. sN = sD;
  55505. tN = e + b;
  55506. tD = c;
  55507. }
  55508. }
  55509. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55510. tN = 0.0;
  55511. // recompute sc for this edge
  55512. if (-d < 0.0) {
  55513. sN = 0.0;
  55514. }
  55515. else if (-d > a)
  55516. sN = sD;
  55517. else {
  55518. sN = -d;
  55519. sD = a;
  55520. }
  55521. }
  55522. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55523. tN = tD;
  55524. // recompute sc for this edge
  55525. if ((-d + b) < 0.0) {
  55526. sN = 0;
  55527. }
  55528. else if ((-d + b) > a) {
  55529. sN = sD;
  55530. }
  55531. else {
  55532. sN = (-d + b);
  55533. sD = a;
  55534. }
  55535. }
  55536. // finally do the division to get sc and tc
  55537. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55538. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55539. // get the difference of the two closest points
  55540. var qtc = v.multiplyByFloats(tc, tc, tc);
  55541. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55542. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55543. if (isIntersected) {
  55544. return qtc.length();
  55545. }
  55546. return -1;
  55547. };
  55548. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55549. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55550. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55551. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55552. this.direction.normalize();
  55553. return this;
  55554. };
  55555. // Statics
  55556. Ray.Zero = function () {
  55557. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55558. };
  55559. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55560. var result = Ray.Zero();
  55561. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55562. };
  55563. /**
  55564. * 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
  55565. * transformed to the given world matrix.
  55566. * @param origin The origin point
  55567. * @param end The end point
  55568. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55569. */
  55570. Ray.CreateNewFromTo = function (origin, end, world) {
  55571. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55572. var direction = end.subtract(origin);
  55573. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55574. direction.normalize();
  55575. return Ray.Transform(new Ray(origin, direction, length), world);
  55576. };
  55577. Ray.Transform = function (ray, matrix) {
  55578. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55579. Ray.TransformToRef(ray, matrix, result);
  55580. return result;
  55581. };
  55582. Ray.TransformToRef = function (ray, matrix, result) {
  55583. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55584. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55585. result.length = ray.length;
  55586. var dir = result.direction;
  55587. var len = dir.length();
  55588. if (!(len === 0 || len === 1)) {
  55589. var num = 1.0 / len;
  55590. dir.x *= num;
  55591. dir.y *= num;
  55592. dir.z *= num;
  55593. result.length *= len;
  55594. }
  55595. };
  55596. Ray.smallnum = 0.00000001;
  55597. Ray.rayl = 10e8;
  55598. return Ray;
  55599. }());
  55600. BABYLON.Ray = Ray;
  55601. })(BABYLON || (BABYLON = {}));
  55602. //# sourceMappingURL=babylon.ray.js.map
  55603. var BABYLON;
  55604. (function (BABYLON) {
  55605. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55606. if (boxMin.x > sphereCenter.x + sphereRadius)
  55607. return false;
  55608. if (sphereCenter.x - sphereRadius > boxMax.x)
  55609. return false;
  55610. if (boxMin.y > sphereCenter.y + sphereRadius)
  55611. return false;
  55612. if (sphereCenter.y - sphereRadius > boxMax.y)
  55613. return false;
  55614. if (boxMin.z > sphereCenter.z + sphereRadius)
  55615. return false;
  55616. if (sphereCenter.z - sphereRadius > boxMax.z)
  55617. return false;
  55618. return true;
  55619. };
  55620. var getLowestRoot = (function () {
  55621. var result = { root: 0, found: false };
  55622. return function (a, b, c, maxR) {
  55623. result.root = 0;
  55624. result.found = false;
  55625. var determinant = b * b - 4.0 * a * c;
  55626. if (determinant < 0)
  55627. return result;
  55628. var sqrtD = Math.sqrt(determinant);
  55629. var r1 = (-b - sqrtD) / (2.0 * a);
  55630. var r2 = (-b + sqrtD) / (2.0 * a);
  55631. if (r1 > r2) {
  55632. var temp = r2;
  55633. r2 = r1;
  55634. r1 = temp;
  55635. }
  55636. if (r1 > 0 && r1 < maxR) {
  55637. result.root = r1;
  55638. result.found = true;
  55639. return result;
  55640. }
  55641. if (r2 > 0 && r2 < maxR) {
  55642. result.root = r2;
  55643. result.found = true;
  55644. return result;
  55645. }
  55646. return result;
  55647. };
  55648. })();
  55649. var Collider = /** @class */ (function () {
  55650. function Collider() {
  55651. this._collisionPoint = BABYLON.Vector3.Zero();
  55652. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55653. this._tempVector = BABYLON.Vector3.Zero();
  55654. this._tempVector2 = BABYLON.Vector3.Zero();
  55655. this._tempVector3 = BABYLON.Vector3.Zero();
  55656. this._tempVector4 = BABYLON.Vector3.Zero();
  55657. this._edge = BABYLON.Vector3.Zero();
  55658. this._baseToVertex = BABYLON.Vector3.Zero();
  55659. this._destinationPoint = BABYLON.Vector3.Zero();
  55660. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55661. this._displacementVector = BABYLON.Vector3.Zero();
  55662. this._radius = BABYLON.Vector3.One();
  55663. this._retry = 0;
  55664. this._basePointWorld = BABYLON.Vector3.Zero();
  55665. this._velocityWorld = BABYLON.Vector3.Zero();
  55666. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55667. this._collisionMask = -1;
  55668. }
  55669. Object.defineProperty(Collider.prototype, "collisionMask", {
  55670. get: function () {
  55671. return this._collisionMask;
  55672. },
  55673. set: function (mask) {
  55674. this._collisionMask = !isNaN(mask) ? mask : -1;
  55675. },
  55676. enumerable: true,
  55677. configurable: true
  55678. });
  55679. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55680. /**
  55681. * Gets the plane normal used to compute the sliding response (in local space)
  55682. */
  55683. get: function () {
  55684. return this._slidePlaneNormal;
  55685. },
  55686. enumerable: true,
  55687. configurable: true
  55688. });
  55689. // Methods
  55690. Collider.prototype._initialize = function (source, dir, e) {
  55691. this._velocity = dir;
  55692. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55693. this._basePoint = source;
  55694. source.multiplyToRef(this._radius, this._basePointWorld);
  55695. dir.multiplyToRef(this._radius, this._velocityWorld);
  55696. this._velocityWorldLength = this._velocityWorld.length();
  55697. this._epsilon = e;
  55698. this.collisionFound = false;
  55699. };
  55700. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55701. pa.subtractToRef(point, this._tempVector);
  55702. pb.subtractToRef(point, this._tempVector2);
  55703. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55704. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55705. if (d < 0)
  55706. return false;
  55707. pc.subtractToRef(point, this._tempVector3);
  55708. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55709. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55710. if (d < 0)
  55711. return false;
  55712. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55713. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55714. return d >= 0;
  55715. };
  55716. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55717. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55718. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55719. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55720. return false;
  55721. }
  55722. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55723. return false;
  55724. return true;
  55725. };
  55726. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55727. var t0;
  55728. var embeddedInPlane = false;
  55729. //defensive programming, actually not needed.
  55730. if (!trianglePlaneArray) {
  55731. trianglePlaneArray = [];
  55732. }
  55733. if (!trianglePlaneArray[faceIndex]) {
  55734. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55735. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55736. }
  55737. var trianglePlane = trianglePlaneArray[faceIndex];
  55738. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55739. return;
  55740. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55741. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55742. if (normalDotVelocity == 0) {
  55743. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55744. return;
  55745. embeddedInPlane = true;
  55746. t0 = 0;
  55747. }
  55748. else {
  55749. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55750. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55751. if (t0 > t1) {
  55752. var temp = t1;
  55753. t1 = t0;
  55754. t0 = temp;
  55755. }
  55756. if (t0 > 1.0 || t1 < 0.0)
  55757. return;
  55758. if (t0 < 0)
  55759. t0 = 0;
  55760. if (t0 > 1.0)
  55761. t0 = 1.0;
  55762. }
  55763. this._collisionPoint.copyFromFloats(0, 0, 0);
  55764. var found = false;
  55765. var t = 1.0;
  55766. if (!embeddedInPlane) {
  55767. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55768. this._velocity.scaleToRef(t0, this._tempVector);
  55769. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55770. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55771. found = true;
  55772. t = t0;
  55773. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55774. }
  55775. }
  55776. if (!found) {
  55777. var velocitySquaredLength = this._velocity.lengthSquared();
  55778. var a = velocitySquaredLength;
  55779. this._basePoint.subtractToRef(p1, this._tempVector);
  55780. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55781. var c = this._tempVector.lengthSquared() - 1.0;
  55782. var lowestRoot = getLowestRoot(a, b, c, t);
  55783. if (lowestRoot.found) {
  55784. t = lowestRoot.root;
  55785. found = true;
  55786. this._collisionPoint.copyFrom(p1);
  55787. }
  55788. this._basePoint.subtractToRef(p2, this._tempVector);
  55789. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55790. c = this._tempVector.lengthSquared() - 1.0;
  55791. lowestRoot = getLowestRoot(a, b, c, t);
  55792. if (lowestRoot.found) {
  55793. t = lowestRoot.root;
  55794. found = true;
  55795. this._collisionPoint.copyFrom(p2);
  55796. }
  55797. this._basePoint.subtractToRef(p3, this._tempVector);
  55798. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55799. c = this._tempVector.lengthSquared() - 1.0;
  55800. lowestRoot = getLowestRoot(a, b, c, t);
  55801. if (lowestRoot.found) {
  55802. t = lowestRoot.root;
  55803. found = true;
  55804. this._collisionPoint.copyFrom(p3);
  55805. }
  55806. p2.subtractToRef(p1, this._edge);
  55807. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55808. var edgeSquaredLength = this._edge.lengthSquared();
  55809. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55810. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55811. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55812. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55813. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55814. lowestRoot = getLowestRoot(a, b, c, t);
  55815. if (lowestRoot.found) {
  55816. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55817. if (f >= 0.0 && f <= 1.0) {
  55818. t = lowestRoot.root;
  55819. found = true;
  55820. this._edge.scaleInPlace(f);
  55821. p1.addToRef(this._edge, this._collisionPoint);
  55822. }
  55823. }
  55824. p3.subtractToRef(p2, this._edge);
  55825. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55826. edgeSquaredLength = this._edge.lengthSquared();
  55827. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55828. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55829. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55830. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55831. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55832. lowestRoot = getLowestRoot(a, b, c, t);
  55833. if (lowestRoot.found) {
  55834. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55835. if (f >= 0.0 && f <= 1.0) {
  55836. t = lowestRoot.root;
  55837. found = true;
  55838. this._edge.scaleInPlace(f);
  55839. p2.addToRef(this._edge, this._collisionPoint);
  55840. }
  55841. }
  55842. p1.subtractToRef(p3, this._edge);
  55843. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55844. edgeSquaredLength = this._edge.lengthSquared();
  55845. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55846. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55847. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55848. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55849. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55850. lowestRoot = getLowestRoot(a, b, c, t);
  55851. if (lowestRoot.found) {
  55852. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55853. if (f >= 0.0 && f <= 1.0) {
  55854. t = lowestRoot.root;
  55855. found = true;
  55856. this._edge.scaleInPlace(f);
  55857. p3.addToRef(this._edge, this._collisionPoint);
  55858. }
  55859. }
  55860. }
  55861. if (found) {
  55862. var distToCollision = t * this._velocity.length();
  55863. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55864. if (!this.intersectionPoint) {
  55865. this.intersectionPoint = this._collisionPoint.clone();
  55866. }
  55867. else {
  55868. this.intersectionPoint.copyFrom(this._collisionPoint);
  55869. }
  55870. this._nearestDistance = distToCollision;
  55871. this.collisionFound = true;
  55872. }
  55873. }
  55874. };
  55875. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55876. for (var i = indexStart; i < indexEnd; i += 3) {
  55877. var p1 = pts[indices[i] - decal];
  55878. var p2 = pts[indices[i + 1] - decal];
  55879. var p3 = pts[indices[i + 2] - decal];
  55880. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55881. }
  55882. };
  55883. Collider.prototype._getResponse = function (pos, vel) {
  55884. pos.addToRef(vel, this._destinationPoint);
  55885. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55886. this._basePoint.addToRef(vel, pos);
  55887. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55888. this._slidePlaneNormal.normalize();
  55889. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55890. pos.addInPlace(this._displacementVector);
  55891. this.intersectionPoint.addInPlace(this._displacementVector);
  55892. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55893. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55894. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55895. };
  55896. return Collider;
  55897. }());
  55898. BABYLON.Collider = Collider;
  55899. })(BABYLON || (BABYLON = {}));
  55900. //# sourceMappingURL=babylon.collider.js.map
  55901. var BABYLON;
  55902. (function (BABYLON) {
  55903. //WebWorker code will be inserted to this variable.
  55904. BABYLON.CollisionWorker = "";
  55905. /** Defines supported task for worker process */
  55906. var WorkerTaskType;
  55907. (function (WorkerTaskType) {
  55908. /** Initialization */
  55909. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55910. /** Update of geometry */
  55911. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55912. /** Evaluate collision */
  55913. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55914. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55915. /** Defines kind of replies returned by worker */
  55916. var WorkerReplyType;
  55917. (function (WorkerReplyType) {
  55918. /** Success */
  55919. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55920. /** Unkown error */
  55921. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55922. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55923. var CollisionCoordinatorWorker = /** @class */ (function () {
  55924. function CollisionCoordinatorWorker() {
  55925. var _this = this;
  55926. this._scaledPosition = BABYLON.Vector3.Zero();
  55927. this._scaledVelocity = BABYLON.Vector3.Zero();
  55928. this.onMeshUpdated = function (transformNode) {
  55929. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55930. };
  55931. this.onGeometryUpdated = function (geometry) {
  55932. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55933. };
  55934. this._afterRender = function () {
  55935. if (!_this._init)
  55936. return;
  55937. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55938. return;
  55939. }
  55940. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55941. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55942. if (_this._runningUpdated > 4) {
  55943. return;
  55944. }
  55945. ++_this._runningUpdated;
  55946. var payload = {
  55947. updatedMeshes: _this._addUpdateMeshesList,
  55948. updatedGeometries: _this._addUpdateGeometriesList,
  55949. removedGeometries: _this._toRemoveGeometryArray,
  55950. removedMeshes: _this._toRemoveMeshesArray
  55951. };
  55952. var message = {
  55953. payload: payload,
  55954. taskType: WorkerTaskType.UPDATE
  55955. };
  55956. var serializable = [];
  55957. for (var id in payload.updatedGeometries) {
  55958. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55959. //prepare transferables
  55960. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55961. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55962. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55963. }
  55964. }
  55965. _this._worker.postMessage(message, serializable);
  55966. _this._addUpdateMeshesList = {};
  55967. _this._addUpdateGeometriesList = {};
  55968. _this._toRemoveGeometryArray = [];
  55969. _this._toRemoveMeshesArray = [];
  55970. };
  55971. this._onMessageFromWorker = function (e) {
  55972. var returnData = e.data;
  55973. if (returnData.error != WorkerReplyType.SUCCESS) {
  55974. //TODO what errors can be returned from the worker?
  55975. BABYLON.Tools.Warn("error returned from worker!");
  55976. return;
  55977. }
  55978. switch (returnData.taskType) {
  55979. case WorkerTaskType.INIT:
  55980. _this._init = true;
  55981. //Update the worked with ALL of the scene's current state
  55982. _this._scene.meshes.forEach(function (mesh) {
  55983. _this.onMeshAdded(mesh);
  55984. });
  55985. _this._scene.getGeometries().forEach(function (geometry) {
  55986. _this.onGeometryAdded(geometry);
  55987. });
  55988. break;
  55989. case WorkerTaskType.UPDATE:
  55990. _this._runningUpdated--;
  55991. break;
  55992. case WorkerTaskType.COLLIDE:
  55993. var returnPayload = returnData.payload;
  55994. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55995. return;
  55996. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55997. if (callback) {
  55998. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55999. if (mesh) {
  56000. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  56001. }
  56002. }
  56003. //cleanup
  56004. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  56005. break;
  56006. }
  56007. };
  56008. this._collisionsCallbackArray = [];
  56009. this._init = false;
  56010. this._runningUpdated = 0;
  56011. this._addUpdateMeshesList = {};
  56012. this._addUpdateGeometriesList = {};
  56013. this._toRemoveGeometryArray = [];
  56014. this._toRemoveMeshesArray = [];
  56015. }
  56016. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56017. if (!this._init)
  56018. return;
  56019. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  56020. return;
  56021. position.divideToRef(collider._radius, this._scaledPosition);
  56022. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56023. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  56024. var payload = {
  56025. collider: {
  56026. position: this._scaledPosition.asArray(),
  56027. velocity: this._scaledVelocity.asArray(),
  56028. radius: collider._radius.asArray()
  56029. },
  56030. collisionId: collisionIndex,
  56031. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  56032. maximumRetry: maximumRetry
  56033. };
  56034. var message = {
  56035. payload: payload,
  56036. taskType: WorkerTaskType.COLLIDE
  56037. };
  56038. this._worker.postMessage(message);
  56039. };
  56040. CollisionCoordinatorWorker.prototype.init = function (scene) {
  56041. this._scene = scene;
  56042. this._scene.registerAfterRender(this._afterRender);
  56043. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  56044. this._worker = new Worker(workerUrl);
  56045. this._worker.onmessage = this._onMessageFromWorker;
  56046. var message = {
  56047. payload: {},
  56048. taskType: WorkerTaskType.INIT
  56049. };
  56050. this._worker.postMessage(message);
  56051. };
  56052. CollisionCoordinatorWorker.prototype.destroy = function () {
  56053. this._scene.unregisterAfterRender(this._afterRender);
  56054. this._worker.terminate();
  56055. };
  56056. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  56057. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  56058. this.onMeshUpdated(mesh);
  56059. };
  56060. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  56061. this._toRemoveMeshesArray.push(mesh.uniqueId);
  56062. };
  56063. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  56064. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  56065. geometry.onGeometryUpdated = this.onGeometryUpdated;
  56066. this.onGeometryUpdated(geometry);
  56067. };
  56068. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  56069. this._toRemoveGeometryArray.push(geometry.id);
  56070. };
  56071. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  56072. var submeshes = [];
  56073. if (mesh.subMeshes) {
  56074. submeshes = mesh.subMeshes.map(function (sm, idx) {
  56075. var boundingInfo = sm.getBoundingInfo();
  56076. return {
  56077. position: idx,
  56078. verticesStart: sm.verticesStart,
  56079. verticesCount: sm.verticesCount,
  56080. indexStart: sm.indexStart,
  56081. indexCount: sm.indexCount,
  56082. hasMaterial: !!sm.getMaterial(),
  56083. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56084. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56085. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56086. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  56087. };
  56088. });
  56089. }
  56090. var geometryId = null;
  56091. if (mesh instanceof BABYLON.Mesh) {
  56092. var geometry = mesh.geometry;
  56093. geometryId = geometry ? geometry.id : null;
  56094. }
  56095. else if (mesh instanceof BABYLON.InstancedMesh) {
  56096. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  56097. geometryId = geometry ? geometry.id : null;
  56098. }
  56099. var boundingInfo = mesh.getBoundingInfo();
  56100. return {
  56101. uniqueId: mesh.uniqueId,
  56102. id: mesh.id,
  56103. name: mesh.name,
  56104. geometryId: geometryId,
  56105. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56106. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56107. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56108. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  56109. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  56110. subMeshes: submeshes,
  56111. checkCollisions: mesh.checkCollisions
  56112. };
  56113. };
  56114. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  56115. return {
  56116. id: geometry.id,
  56117. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  56118. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  56119. indices: new Uint32Array(geometry.getIndices() || []),
  56120. };
  56121. };
  56122. return CollisionCoordinatorWorker;
  56123. }());
  56124. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  56125. var CollisionCoordinatorLegacy = /** @class */ (function () {
  56126. function CollisionCoordinatorLegacy() {
  56127. this._scaledPosition = BABYLON.Vector3.Zero();
  56128. this._scaledVelocity = BABYLON.Vector3.Zero();
  56129. this._finalPosition = BABYLON.Vector3.Zero();
  56130. }
  56131. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56132. position.divideToRef(collider._radius, this._scaledPosition);
  56133. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56134. collider.collidedMesh = null;
  56135. collider._retry = 0;
  56136. collider._initialVelocity = this._scaledVelocity;
  56137. collider._initialPosition = this._scaledPosition;
  56138. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  56139. this._finalPosition.multiplyInPlace(collider._radius);
  56140. //run the callback
  56141. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  56142. };
  56143. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  56144. this._scene = scene;
  56145. };
  56146. CollisionCoordinatorLegacy.prototype.destroy = function () {
  56147. //Legacy need no destruction method.
  56148. };
  56149. //No update in legacy mode
  56150. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  56151. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  56152. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  56153. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  56154. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  56155. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  56156. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  56157. if (excludedMesh === void 0) { excludedMesh = null; }
  56158. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  56159. if (collider._retry >= maximumRetry) {
  56160. finalPosition.copyFrom(position);
  56161. return;
  56162. }
  56163. // Check if this is a mesh else camera or -1
  56164. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  56165. collider._initialize(position, velocity, closeDistance);
  56166. // Check all meshes
  56167. for (var index = 0; index < this._scene.meshes.length; index++) {
  56168. var mesh = this._scene.meshes[index];
  56169. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  56170. mesh._checkCollision(collider);
  56171. }
  56172. }
  56173. if (!collider.collisionFound) {
  56174. position.addToRef(velocity, finalPosition);
  56175. return;
  56176. }
  56177. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  56178. collider._getResponse(position, velocity);
  56179. }
  56180. if (velocity.length() <= closeDistance) {
  56181. finalPosition.copyFrom(position);
  56182. return;
  56183. }
  56184. collider._retry++;
  56185. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  56186. };
  56187. return CollisionCoordinatorLegacy;
  56188. }());
  56189. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  56190. })(BABYLON || (BABYLON = {}));
  56191. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  56192. var BABYLON;
  56193. (function (BABYLON) {
  56194. /**
  56195. * A particle represents one of the element emitted by a particle system.
  56196. * This is mainly define by its coordinates, direction, velocity and age.
  56197. */
  56198. var Particle = /** @class */ (function () {
  56199. /**
  56200. * Creates a new instance Particle
  56201. * @param particleSystem the particle system the particle belongs to
  56202. */
  56203. function Particle(
  56204. /**
  56205. * particleSystem the particle system the particle belongs to.
  56206. */
  56207. particleSystem) {
  56208. this.particleSystem = particleSystem;
  56209. /**
  56210. * The world position of the particle in the scene.
  56211. */
  56212. this.position = BABYLON.Vector3.Zero();
  56213. /**
  56214. * The world direction of the particle in the scene.
  56215. */
  56216. this.direction = BABYLON.Vector3.Zero();
  56217. /**
  56218. * The color of the particle.
  56219. */
  56220. this.color = new BABYLON.Color4(0, 0, 0, 0);
  56221. /**
  56222. * The color change of the particle per step.
  56223. */
  56224. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  56225. /**
  56226. * Defines how long will the life of the particle be.
  56227. */
  56228. this.lifeTime = 1.0;
  56229. /**
  56230. * The current age of the particle.
  56231. */
  56232. this.age = 0;
  56233. /**
  56234. * The current size of the particle.
  56235. */
  56236. this.size = 0;
  56237. /**
  56238. * The current scale of the particle.
  56239. */
  56240. this.scale = new BABYLON.Vector2(1, 1);
  56241. /**
  56242. * The current angle of the particle.
  56243. */
  56244. this.angle = 0;
  56245. /**
  56246. * Defines how fast is the angle changing.
  56247. */
  56248. this.angularSpeed = 0;
  56249. /**
  56250. * Defines the cell index used by the particle to be rendered from a sprite.
  56251. */
  56252. this.cellIndex = 0;
  56253. this._currentFrameCounter = 0;
  56254. if (!this.particleSystem.isAnimationSheetEnabled) {
  56255. return;
  56256. }
  56257. this.updateCellInfoFromSystem();
  56258. }
  56259. Particle.prototype.updateCellInfoFromSystem = function () {
  56260. this.cellIndex = this.particleSystem.startSpriteCellID;
  56261. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  56262. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  56263. }
  56264. else {
  56265. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  56266. }
  56267. };
  56268. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  56269. // (ageOffset / scaledUpdateSpeed) / available cells
  56270. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  56271. this._currentFrameCounter += scaledUpdateSpeed;
  56272. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  56273. this._currentFrameCounter = 0;
  56274. this.cellIndex++;
  56275. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  56276. this.cellIndex = this.particleSystem.endSpriteCellID;
  56277. }
  56278. }
  56279. };
  56280. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  56281. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  56282. this.cellIndex++;
  56283. this._currentFrameCounter = 0;
  56284. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  56285. if (this.particleSystem.spriteCellLoop) {
  56286. this.cellIndex = this.particleSystem.startSpriteCellID;
  56287. }
  56288. else {
  56289. this.cellIndex = this.particleSystem.endSpriteCellID;
  56290. }
  56291. }
  56292. }
  56293. else {
  56294. this._currentFrameCounter++;
  56295. }
  56296. };
  56297. /**
  56298. * Copy the properties of particle to another one.
  56299. * @param other the particle to copy the information to.
  56300. */
  56301. Particle.prototype.copyTo = function (other) {
  56302. other.position.copyFrom(this.position);
  56303. other.direction.copyFrom(this.direction);
  56304. other.color.copyFrom(this.color);
  56305. other.colorStep.copyFrom(this.colorStep);
  56306. other.lifeTime = this.lifeTime;
  56307. other.age = this.age;
  56308. other.size = this.size;
  56309. other.scale.copyFrom(this.scale);
  56310. other.angle = this.angle;
  56311. other.angularSpeed = this.angularSpeed;
  56312. other.particleSystem = this.particleSystem;
  56313. other.cellIndex = this.cellIndex;
  56314. };
  56315. return Particle;
  56316. }());
  56317. BABYLON.Particle = Particle;
  56318. })(BABYLON || (BABYLON = {}));
  56319. //# sourceMappingURL=babylon.particle.js.map
  56320. var BABYLON;
  56321. (function (BABYLON) {
  56322. /**
  56323. * This represents a particle system in Babylon.
  56324. * 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.
  56325. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56326. * @example https://doc.babylonjs.com/babylon101/particles
  56327. */
  56328. var ParticleSystem = /** @class */ (function () {
  56329. /**
  56330. * Instantiates a particle system.
  56331. * 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.
  56332. * @param name The name of the particle system
  56333. * @param capacity The max number of particles alive at the same time
  56334. * @param scene The scene the particle system belongs to
  56335. * @param customEffect a custom effect used to change the way particles are rendered by default
  56336. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56337. * @param epsilon Offset used to render the particles
  56338. */
  56339. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56340. if (customEffect === void 0) { customEffect = null; }
  56341. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56342. if (epsilon === void 0) { epsilon = 0.01; }
  56343. var _this = this;
  56344. /**
  56345. * List of animations used by the particle system.
  56346. */
  56347. this.animations = [];
  56348. /**
  56349. * The rendering group used by the Particle system to chose when to render.
  56350. */
  56351. this.renderingGroupId = 0;
  56352. /**
  56353. * The emitter represents the Mesh or position we are attaching the particle system to.
  56354. */
  56355. this.emitter = null;
  56356. /**
  56357. * The maximum number of particles to emit per frame
  56358. */
  56359. this.emitRate = 10;
  56360. /**
  56361. * If you want to launch only a few particles at once, that can be done, as well.
  56362. */
  56363. this.manualEmitCount = -1;
  56364. /**
  56365. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56366. */
  56367. this.updateSpeed = 0.01;
  56368. /**
  56369. * The amount of time the particle system is running (depends of the overall update speed).
  56370. */
  56371. this.targetStopDuration = 0;
  56372. /**
  56373. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  56374. */
  56375. this.disposeOnStop = false;
  56376. /**
  56377. * Minimum power of emitting particles.
  56378. */
  56379. this.minEmitPower = 1;
  56380. /**
  56381. * Maximum power of emitting particles.
  56382. */
  56383. this.maxEmitPower = 1;
  56384. /**
  56385. * Minimum life time of emitting particles.
  56386. */
  56387. this.minLifeTime = 1;
  56388. /**
  56389. * Maximum life time of emitting particles.
  56390. */
  56391. this.maxLifeTime = 1;
  56392. /**
  56393. * Minimum Size of emitting particles.
  56394. */
  56395. this.minSize = 1;
  56396. /**
  56397. * Maximum Size of emitting particles.
  56398. */
  56399. this.maxSize = 1;
  56400. /**
  56401. * Minimum scale of emitting particles on X axis.
  56402. */
  56403. this.minScaleX = 1;
  56404. /**
  56405. * Maximum scale of emitting particles on X axis.
  56406. */
  56407. this.maxScaleX = 1;
  56408. /**
  56409. * Minimum scale of emitting particles on Y axis.
  56410. */
  56411. this.minScaleY = 1;
  56412. /**
  56413. * Maximum scale of emitting particles on Y axis.
  56414. */
  56415. this.maxScaleY = 1;
  56416. /**
  56417. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56418. */
  56419. this.minAngularSpeed = 0;
  56420. /**
  56421. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56422. */
  56423. this.maxAngularSpeed = 0;
  56424. /**
  56425. * The layer mask we are rendering the particles through.
  56426. */
  56427. this.layerMask = 0x0FFFFFFF;
  56428. /**
  56429. * This can help using your own shader to render the particle system.
  56430. * The according effect will be created
  56431. */
  56432. this.customShader = null;
  56433. /**
  56434. * By default particle system starts as soon as they are created. This prevents the
  56435. * automatic start to happen and let you decide when to start emitting particles.
  56436. */
  56437. this.preventAutoStart = false;
  56438. /**
  56439. * Callback triggered when the particle animation is ending.
  56440. */
  56441. this.onAnimationEnd = null;
  56442. /**
  56443. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56444. */
  56445. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  56446. /**
  56447. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56448. * to override the particles.
  56449. */
  56450. this.forceDepthWrite = false;
  56451. /**
  56452. * You can use gravity if you want to give an orientation to your particles.
  56453. */
  56454. this.gravity = BABYLON.Vector3.Zero();
  56455. /**
  56456. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56457. */
  56458. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56459. /**
  56460. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56461. */
  56462. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56463. /**
  56464. * Color the particle will have at the end of its lifetime.
  56465. */
  56466. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  56467. /**
  56468. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  56469. */
  56470. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56471. /**
  56472. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  56473. */
  56474. this.spriteCellLoop = true;
  56475. /**
  56476. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  56477. */
  56478. this.spriteCellChangeSpeed = 0;
  56479. /**
  56480. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  56481. */
  56482. this.startSpriteCellID = 0;
  56483. /**
  56484. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  56485. */
  56486. this.endSpriteCellID = 0;
  56487. /**
  56488. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  56489. */
  56490. this.spriteCellWidth = 0;
  56491. /**
  56492. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  56493. */
  56494. this.spriteCellHeight = 0;
  56495. /**
  56496. * An event triggered when the system is disposed.
  56497. */
  56498. this.onDisposeObservable = new BABYLON.Observable();
  56499. this._particles = new Array();
  56500. this._stockParticles = new Array();
  56501. this._newPartsExcess = 0;
  56502. this._vertexBuffers = {};
  56503. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56504. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56505. this._scaledDirection = BABYLON.Vector3.Zero();
  56506. this._scaledGravity = BABYLON.Vector3.Zero();
  56507. this._currentRenderId = -1;
  56508. this._started = false;
  56509. this._stopped = false;
  56510. this._actualFrame = 0;
  56511. this._vertexBufferSize = 12;
  56512. // start of sub system methods
  56513. /**
  56514. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56515. * Its lifetime will start back at 0.
  56516. */
  56517. this.recycleParticle = function (particle) {
  56518. var lastParticle = _this._particles.pop();
  56519. if (lastParticle !== particle) {
  56520. lastParticle.copyTo(particle);
  56521. }
  56522. _this._stockParticles.push(lastParticle);
  56523. };
  56524. this._createParticle = function () {
  56525. var particle;
  56526. if (_this._stockParticles.length !== 0) {
  56527. particle = _this._stockParticles.pop();
  56528. particle.age = 0;
  56529. particle.cellIndex = _this.startSpriteCellID;
  56530. }
  56531. else {
  56532. particle = new BABYLON.Particle(_this);
  56533. }
  56534. return particle;
  56535. };
  56536. this._emitFromParticle = function (particle) {
  56537. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56538. return;
  56539. }
  56540. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56541. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56542. subSystem._rootParticleSystem = _this;
  56543. _this.activeSubSystems.push(subSystem);
  56544. subSystem.start();
  56545. };
  56546. this._appendParticleVertexes = null;
  56547. this.id = name;
  56548. this.name = name;
  56549. this._capacity = capacity;
  56550. this._epsilon = epsilon;
  56551. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56552. if (isAnimationSheetEnabled) {
  56553. this._vertexBufferSize = 13;
  56554. }
  56555. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56556. this._customEffect = customEffect;
  56557. scene.particleSystems.push(this);
  56558. this._createIndexBuffer();
  56559. // 13 floats per particle (x, y, z, r, g, b, a, angle, scaleX, scaleY, offsetX, offsetY) + 1 filler
  56560. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  56561. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  56562. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  56563. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  56564. var options = this._vertexBuffer.createVertexBuffer("options", 7, 3);
  56565. var size = this._vertexBuffer.createVertexBuffer("size", 10, 2);
  56566. if (this._isAnimationSheetEnabled) {
  56567. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 12, 1);
  56568. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56569. }
  56570. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56571. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56572. this._vertexBuffers["options"] = options;
  56573. this._vertexBuffers["size"] = size;
  56574. // Default emitter type
  56575. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56576. this.updateFunction = function (particles) {
  56577. for (var index = 0; index < particles.length; index++) {
  56578. var particle = particles[index];
  56579. particle.age += _this._scaledUpdateSpeed;
  56580. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56581. _this._emitFromParticle(particle);
  56582. _this.recycleParticle(particle);
  56583. index--;
  56584. continue;
  56585. }
  56586. else {
  56587. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56588. particle.color.addInPlace(_this._scaledColorStep);
  56589. if (particle.color.a < 0)
  56590. particle.color.a = 0;
  56591. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56592. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  56593. particle.position.addInPlace(_this._scaledDirection);
  56594. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56595. particle.direction.addInPlace(_this._scaledGravity);
  56596. if (_this._isAnimationSheetEnabled) {
  56597. particle.updateCellIndex(_this._scaledUpdateSpeed);
  56598. }
  56599. }
  56600. }
  56601. };
  56602. }
  56603. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  56604. /**
  56605. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56606. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56607. */
  56608. get: function () {
  56609. if (this.particleEmitterType.direction1) {
  56610. return this.particleEmitterType.direction1;
  56611. }
  56612. return BABYLON.Vector3.Zero();
  56613. },
  56614. set: function (value) {
  56615. if (this.particleEmitterType.direction1) {
  56616. this.particleEmitterType.direction1 = value;
  56617. }
  56618. },
  56619. enumerable: true,
  56620. configurable: true
  56621. });
  56622. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  56623. /**
  56624. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56625. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56626. */
  56627. get: function () {
  56628. if (this.particleEmitterType.direction2) {
  56629. return this.particleEmitterType.direction2;
  56630. }
  56631. return BABYLON.Vector3.Zero();
  56632. },
  56633. set: function (value) {
  56634. if (this.particleEmitterType.direction2) {
  56635. this.particleEmitterType.direction2 = value;
  56636. }
  56637. },
  56638. enumerable: true,
  56639. configurable: true
  56640. });
  56641. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  56642. /**
  56643. * 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.
  56644. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56645. */
  56646. get: function () {
  56647. if (this.particleEmitterType.minEmitBox) {
  56648. return this.particleEmitterType.minEmitBox;
  56649. }
  56650. return BABYLON.Vector3.Zero();
  56651. },
  56652. set: function (value) {
  56653. if (this.particleEmitterType.minEmitBox) {
  56654. this.particleEmitterType.minEmitBox = value;
  56655. }
  56656. },
  56657. enumerable: true,
  56658. configurable: true
  56659. });
  56660. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  56661. /**
  56662. * 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.
  56663. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56664. */
  56665. get: function () {
  56666. if (this.particleEmitterType.maxEmitBox) {
  56667. return this.particleEmitterType.maxEmitBox;
  56668. }
  56669. return BABYLON.Vector3.Zero();
  56670. },
  56671. set: function (value) {
  56672. if (this.particleEmitterType.maxEmitBox) {
  56673. this.particleEmitterType.maxEmitBox = value;
  56674. }
  56675. },
  56676. enumerable: true,
  56677. configurable: true
  56678. });
  56679. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56680. /**
  56681. * Sets a callback that will be triggered when the system is disposed.
  56682. */
  56683. set: function (callback) {
  56684. if (this._onDisposeObserver) {
  56685. this.onDisposeObservable.remove(this._onDisposeObserver);
  56686. }
  56687. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56688. },
  56689. enumerable: true,
  56690. configurable: true
  56691. });
  56692. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  56693. /**
  56694. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  56695. */
  56696. get: function () {
  56697. return this._isAnimationSheetEnabled;
  56698. },
  56699. enumerable: true,
  56700. configurable: true
  56701. });
  56702. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56703. //end of Sub-emitter
  56704. /**
  56705. * Gets the current list of active particles
  56706. */
  56707. get: function () {
  56708. return this._particles;
  56709. },
  56710. enumerable: true,
  56711. configurable: true
  56712. });
  56713. /**
  56714. * Returns the string "ParticleSystem"
  56715. * @returns a string containing the class name
  56716. */
  56717. ParticleSystem.prototype.getClassName = function () {
  56718. return "ParticleSystem";
  56719. };
  56720. ParticleSystem.prototype._createIndexBuffer = function () {
  56721. var indices = [];
  56722. var index = 0;
  56723. for (var count = 0; count < this._capacity; count++) {
  56724. indices.push(index);
  56725. indices.push(index + 1);
  56726. indices.push(index + 2);
  56727. indices.push(index);
  56728. indices.push(index + 2);
  56729. indices.push(index + 3);
  56730. index += 4;
  56731. }
  56732. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56733. };
  56734. /**
  56735. * Gets the maximum number of particles active at the same time.
  56736. * @returns The max number of active particles.
  56737. */
  56738. ParticleSystem.prototype.getCapacity = function () {
  56739. return this._capacity;
  56740. };
  56741. /**
  56742. * Gets Wether there are still active particles in the system.
  56743. * @returns True if it is alive, otherwise false.
  56744. */
  56745. ParticleSystem.prototype.isAlive = function () {
  56746. return this._alive;
  56747. };
  56748. /**
  56749. * Gets Wether the system has been started.
  56750. * @returns True if it has been started, otherwise false.
  56751. */
  56752. ParticleSystem.prototype.isStarted = function () {
  56753. return this._started;
  56754. };
  56755. /**
  56756. * Starts the particle system and begins to emit.
  56757. */
  56758. ParticleSystem.prototype.start = function () {
  56759. this._started = true;
  56760. this._stopped = false;
  56761. this._actualFrame = 0;
  56762. if (this.subEmitters && this.subEmitters.length != 0) {
  56763. this.activeSubSystems = new Array();
  56764. }
  56765. };
  56766. /**
  56767. * Stops the particle system.
  56768. * @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.
  56769. */
  56770. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56771. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56772. this._stopped = true;
  56773. if (stopSubEmitters) {
  56774. this._stopSubEmitters();
  56775. }
  56776. };
  56777. // animation sheet
  56778. /**
  56779. * Remove all active particles
  56780. */
  56781. ParticleSystem.prototype.reset = function () {
  56782. this._stockParticles = [];
  56783. this._particles = [];
  56784. };
  56785. /**
  56786. * @hidden (for internal use only)
  56787. */
  56788. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56789. var offset = index * this._vertexBufferSize;
  56790. this._vertexData[offset] = particle.position.x;
  56791. this._vertexData[offset + 1] = particle.position.y;
  56792. this._vertexData[offset + 2] = particle.position.z;
  56793. this._vertexData[offset + 3] = particle.color.r;
  56794. this._vertexData[offset + 4] = particle.color.g;
  56795. this._vertexData[offset + 5] = particle.color.b;
  56796. this._vertexData[offset + 6] = particle.color.a;
  56797. this._vertexData[offset + 7] = particle.angle;
  56798. this._vertexData[offset + 8] = offsetX;
  56799. this._vertexData[offset + 9] = offsetY;
  56800. this._vertexData[offset + 10] = particle.scale.x * particle.size;
  56801. this._vertexData[offset + 11] = particle.scale.y * particle.size;
  56802. };
  56803. /**
  56804. * @hidden (for internal use only)
  56805. */
  56806. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56807. if (offsetX === 0)
  56808. offsetX = this._epsilon;
  56809. else if (offsetX === 1)
  56810. offsetX = 1 - this._epsilon;
  56811. if (offsetY === 0)
  56812. offsetY = this._epsilon;
  56813. else if (offsetY === 1)
  56814. offsetY = 1 - this._epsilon;
  56815. var offset = index * this._vertexBufferSize;
  56816. this._vertexData[offset] = particle.position.x;
  56817. this._vertexData[offset + 1] = particle.position.y;
  56818. this._vertexData[offset + 2] = particle.position.z;
  56819. this._vertexData[offset + 3] = particle.color.r;
  56820. this._vertexData[offset + 4] = particle.color.g;
  56821. this._vertexData[offset + 5] = particle.color.b;
  56822. this._vertexData[offset + 6] = particle.color.a;
  56823. this._vertexData[offset + 7] = particle.angle;
  56824. this._vertexData[offset + 8] = offsetX;
  56825. this._vertexData[offset + 9] = offsetY;
  56826. this._vertexData[offset + 10] = particle.scale.x * particle.size;
  56827. this._vertexData[offset + 11] = particle.scale.y * particle.size;
  56828. this._vertexData[offset + 12] = particle.cellIndex;
  56829. };
  56830. ParticleSystem.prototype._stopSubEmitters = function () {
  56831. if (!this.activeSubSystems) {
  56832. return;
  56833. }
  56834. this.activeSubSystems.forEach(function (subSystem) {
  56835. subSystem.stop(true);
  56836. });
  56837. this.activeSubSystems = new Array();
  56838. };
  56839. ParticleSystem.prototype._removeFromRoot = function () {
  56840. if (!this._rootParticleSystem) {
  56841. return;
  56842. }
  56843. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56844. if (index !== -1) {
  56845. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56846. }
  56847. };
  56848. // end of sub system methods
  56849. ParticleSystem.prototype._update = function (newParticles) {
  56850. // Update current
  56851. this._alive = this._particles.length > 0;
  56852. this.updateFunction(this._particles);
  56853. // Add new ones
  56854. var worldMatrix;
  56855. if (this.emitter.position) {
  56856. var emitterMesh = this.emitter;
  56857. worldMatrix = emitterMesh.getWorldMatrix();
  56858. }
  56859. else {
  56860. var emitterPosition = this.emitter;
  56861. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56862. }
  56863. var particle;
  56864. for (var index = 0; index < newParticles; index++) {
  56865. if (this._particles.length === this._capacity) {
  56866. break;
  56867. }
  56868. particle = this._createParticle();
  56869. this._particles.push(particle);
  56870. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56871. if (this.startPositionFunction) {
  56872. this.startPositionFunction(worldMatrix, particle.position, particle);
  56873. }
  56874. else {
  56875. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56876. }
  56877. if (this.startDirectionFunction) {
  56878. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56879. }
  56880. else {
  56881. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56882. }
  56883. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56884. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56885. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this.minScaleX, this.maxScaleX), BABYLON.Scalar.RandomRange(this.minScaleY, this.maxScaleY));
  56886. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56887. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56888. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56889. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56890. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56891. }
  56892. };
  56893. ParticleSystem.prototype._getEffect = function () {
  56894. if (this._customEffect) {
  56895. return this._customEffect;
  56896. }
  56897. ;
  56898. var defines = [];
  56899. if (this._scene.clipPlane) {
  56900. defines.push("#define CLIPPLANE");
  56901. }
  56902. if (this._isAnimationSheetEnabled) {
  56903. defines.push("#define ANIMATESHEET");
  56904. }
  56905. // Effect
  56906. var join = defines.join("\n");
  56907. if (this._cachedDefines !== join) {
  56908. this._cachedDefines = join;
  56909. var attributesNamesOrOptions;
  56910. var effectCreationOption;
  56911. if (this._isAnimationSheetEnabled) {
  56912. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "size", "cellIndex"];
  56913. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56914. }
  56915. else {
  56916. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "size",];
  56917. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56918. }
  56919. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56920. }
  56921. return this._effect;
  56922. };
  56923. /**
  56924. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56925. */
  56926. ParticleSystem.prototype.animate = function () {
  56927. if (!this._started)
  56928. return;
  56929. var effect = this._getEffect();
  56930. // Check
  56931. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56932. return;
  56933. if (this._currentRenderId === this._scene.getRenderId()) {
  56934. return;
  56935. }
  56936. this._currentRenderId = this._scene.getRenderId();
  56937. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56938. // determine the number of particles we need to create
  56939. var newParticles;
  56940. if (this.manualEmitCount > -1) {
  56941. newParticles = this.manualEmitCount;
  56942. this._newPartsExcess = 0;
  56943. this.manualEmitCount = 0;
  56944. }
  56945. else {
  56946. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56947. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56948. }
  56949. if (this._newPartsExcess > 1.0) {
  56950. newParticles += this._newPartsExcess >> 0;
  56951. this._newPartsExcess -= this._newPartsExcess >> 0;
  56952. }
  56953. this._alive = false;
  56954. if (!this._stopped) {
  56955. this._actualFrame += this._scaledUpdateSpeed;
  56956. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56957. this.stop();
  56958. }
  56959. else {
  56960. newParticles = 0;
  56961. }
  56962. this._update(newParticles);
  56963. // Stopped?
  56964. if (this._stopped) {
  56965. if (!this._alive) {
  56966. this._started = false;
  56967. if (this.onAnimationEnd) {
  56968. this.onAnimationEnd();
  56969. }
  56970. if (this.disposeOnStop) {
  56971. this._scene._toBeDisposed.push(this);
  56972. }
  56973. }
  56974. }
  56975. // Animation sheet
  56976. if (this._isAnimationSheetEnabled) {
  56977. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56978. }
  56979. else {
  56980. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56981. }
  56982. // Update VBO
  56983. var offset = 0;
  56984. for (var index = 0; index < this._particles.length; index++) {
  56985. var particle = this._particles[index];
  56986. this._appendParticleVertexes(offset, particle);
  56987. offset += 4;
  56988. }
  56989. if (this._vertexBuffer) {
  56990. this._vertexBuffer.update(this._vertexData);
  56991. }
  56992. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56993. this.stop();
  56994. }
  56995. };
  56996. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56997. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56998. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56999. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  57000. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  57001. };
  57002. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  57003. this._appendParticleVertex(offset++, particle, 0, 0);
  57004. this._appendParticleVertex(offset++, particle, 1, 0);
  57005. this._appendParticleVertex(offset++, particle, 1, 1);
  57006. this._appendParticleVertex(offset++, particle, 0, 1);
  57007. };
  57008. /**
  57009. * Rebuilds the particle system.
  57010. */
  57011. ParticleSystem.prototype.rebuild = function () {
  57012. this._createIndexBuffer();
  57013. if (this._vertexBuffer) {
  57014. this._vertexBuffer._rebuild();
  57015. }
  57016. };
  57017. /**
  57018. * Is this system ready to be used/rendered
  57019. * @return true if the system is ready
  57020. */
  57021. ParticleSystem.prototype.isReady = function () {
  57022. var effect = this._getEffect();
  57023. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57024. return false;
  57025. }
  57026. return true;
  57027. };
  57028. /**
  57029. * Renders the particle system in its current state.
  57030. * @returns the current number of particles
  57031. */
  57032. ParticleSystem.prototype.render = function () {
  57033. var effect = this._getEffect();
  57034. // Check
  57035. if (!this.isReady() || !this._particles.length) {
  57036. return 0;
  57037. }
  57038. var engine = this._scene.getEngine();
  57039. // Render
  57040. engine.enableEffect(effect);
  57041. engine.setState(false);
  57042. var viewMatrix = this._scene.getViewMatrix();
  57043. effect.setTexture("diffuseSampler", this.particleTexture);
  57044. effect.setMatrix("view", viewMatrix);
  57045. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  57046. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57047. var baseSize = this.particleTexture.getBaseSize();
  57048. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57049. }
  57050. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  57051. if (this._scene.clipPlane) {
  57052. var clipPlane = this._scene.clipPlane;
  57053. var invView = viewMatrix.clone();
  57054. invView.invert();
  57055. effect.setMatrix("invView", invView);
  57056. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57057. }
  57058. // VBOs
  57059. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  57060. // Draw order
  57061. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  57062. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57063. }
  57064. else {
  57065. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57066. }
  57067. if (this.forceDepthWrite) {
  57068. engine.setDepthWrite(true);
  57069. }
  57070. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  57071. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57072. return this._particles.length;
  57073. };
  57074. /**
  57075. * Disposes the particle system and free the associated resources
  57076. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57077. */
  57078. ParticleSystem.prototype.dispose = function (disposeTexture) {
  57079. if (disposeTexture === void 0) { disposeTexture = true; }
  57080. if (this._vertexBuffer) {
  57081. this._vertexBuffer.dispose();
  57082. this._vertexBuffer = null;
  57083. }
  57084. if (this._indexBuffer) {
  57085. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57086. this._indexBuffer = null;
  57087. }
  57088. if (disposeTexture && this.particleTexture) {
  57089. this.particleTexture.dispose();
  57090. this.particleTexture = null;
  57091. }
  57092. this._removeFromRoot();
  57093. // Remove from scene
  57094. var index = this._scene.particleSystems.indexOf(this);
  57095. if (index > -1) {
  57096. this._scene.particleSystems.splice(index, 1);
  57097. }
  57098. // Callback
  57099. this.onDisposeObservable.notifyObservers(this);
  57100. this.onDisposeObservable.clear();
  57101. };
  57102. /**
  57103. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  57104. * @param radius The radius of the sphere to emit from
  57105. * @returns the emitter
  57106. */
  57107. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  57108. if (radius === void 0) { radius = 1; }
  57109. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  57110. this.particleEmitterType = particleEmitter;
  57111. return particleEmitter;
  57112. };
  57113. /**
  57114. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  57115. * @param radius The radius of the sphere to emit from
  57116. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  57117. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  57118. * @returns the emitter
  57119. */
  57120. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  57121. if (radius === void 0) { radius = 1; }
  57122. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57123. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57124. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  57125. this.particleEmitterType = particleEmitter;
  57126. return particleEmitter;
  57127. };
  57128. /**
  57129. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  57130. * @param radius The radius of the cone to emit from
  57131. * @param angle The base angle of the cone
  57132. * @returns the emitter
  57133. */
  57134. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  57135. if (radius === void 0) { radius = 1; }
  57136. if (angle === void 0) { angle = Math.PI / 4; }
  57137. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  57138. this.particleEmitterType = particleEmitter;
  57139. return particleEmitter;
  57140. };
  57141. // 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.
  57142. /**
  57143. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  57144. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57145. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57146. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57147. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57148. * @returns the emitter
  57149. */
  57150. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  57151. var particleEmitter = new BABYLON.BoxParticleEmitter();
  57152. this.particleEmitterType = particleEmitter;
  57153. this.direction1 = direction1;
  57154. this.direction2 = direction2;
  57155. this.minEmitBox = minEmitBox;
  57156. this.maxEmitBox = maxEmitBox;
  57157. return particleEmitter;
  57158. };
  57159. // Clone
  57160. /**
  57161. * Clones the particle system.
  57162. * @param name The name of the cloned object
  57163. * @param newEmitter The new emitter to use
  57164. * @returns the cloned particle system
  57165. */
  57166. ParticleSystem.prototype.clone = function (name, newEmitter) {
  57167. var custom = null;
  57168. var program = null;
  57169. if (this.customShader != null) {
  57170. program = this.customShader;
  57171. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57172. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57173. }
  57174. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  57175. result.customShader = program;
  57176. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  57177. if (newEmitter === undefined) {
  57178. newEmitter = this.emitter;
  57179. }
  57180. result.emitter = newEmitter;
  57181. if (this.particleTexture) {
  57182. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57183. }
  57184. if (!this.preventAutoStart) {
  57185. result.start();
  57186. }
  57187. return result;
  57188. };
  57189. /**
  57190. * Serializes the particle system to a JSON object.
  57191. * @returns the JSON object
  57192. */
  57193. ParticleSystem.prototype.serialize = function () {
  57194. var serializationObject = {};
  57195. serializationObject.name = this.name;
  57196. serializationObject.id = this.id;
  57197. // Emitter
  57198. if (this.emitter.position) {
  57199. var emitterMesh = this.emitter;
  57200. serializationObject.emitterId = emitterMesh.id;
  57201. }
  57202. else {
  57203. var emitterPosition = this.emitter;
  57204. serializationObject.emitter = emitterPosition.asArray();
  57205. }
  57206. serializationObject.capacity = this.getCapacity();
  57207. if (this.particleTexture) {
  57208. serializationObject.textureName = this.particleTexture.name;
  57209. }
  57210. // Animations
  57211. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57212. // Particle system
  57213. serializationObject.minAngularSpeed = this.minAngularSpeed;
  57214. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  57215. serializationObject.minSize = this.minSize;
  57216. serializationObject.maxSize = this.maxSize;
  57217. serializationObject.minScaleX = this.minScaleX;
  57218. serializationObject.maxScaleX = this.maxScaleX;
  57219. serializationObject.minScaleY = this.minScaleY;
  57220. serializationObject.maxScaleY = this.maxScaleY;
  57221. serializationObject.minEmitPower = this.minEmitPower;
  57222. serializationObject.maxEmitPower = this.maxEmitPower;
  57223. serializationObject.minLifeTime = this.minLifeTime;
  57224. serializationObject.maxLifeTime = this.maxLifeTime;
  57225. serializationObject.emitRate = this.emitRate;
  57226. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57227. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57228. serializationObject.gravity = this.gravity.asArray();
  57229. serializationObject.direction1 = this.direction1.asArray();
  57230. serializationObject.direction2 = this.direction2.asArray();
  57231. serializationObject.color1 = this.color1.asArray();
  57232. serializationObject.color2 = this.color2.asArray();
  57233. serializationObject.colorDead = this.colorDead.asArray();
  57234. serializationObject.updateSpeed = this.updateSpeed;
  57235. serializationObject.targetStopDuration = this.targetStopDuration;
  57236. serializationObject.textureMask = this.textureMask.asArray();
  57237. serializationObject.blendMode = this.blendMode;
  57238. serializationObject.customShader = this.customShader;
  57239. serializationObject.preventAutoStart = this.preventAutoStart;
  57240. serializationObject.startSpriteCellID = this.startSpriteCellID;
  57241. serializationObject.endSpriteCellID = this.endSpriteCellID;
  57242. serializationObject.spriteCellLoop = this.spriteCellLoop;
  57243. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  57244. serializationObject.spriteCellWidth = this.spriteCellWidth;
  57245. serializationObject.spriteCellHeight = this.spriteCellHeight;
  57246. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57247. // Emitter
  57248. if (this.particleEmitterType) {
  57249. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57250. }
  57251. return serializationObject;
  57252. };
  57253. /**
  57254. * Parses a JSON object to create a particle system.
  57255. * @param parsedParticleSystem The JSON object to parse
  57256. * @param scene The scene to create the particle system in
  57257. * @param rootUrl The root url to use to load external dependencies like texture
  57258. * @returns the Parsed particle system
  57259. */
  57260. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57261. var name = parsedParticleSystem.name;
  57262. var custom = null;
  57263. var program = null;
  57264. if (parsedParticleSystem.customShader) {
  57265. program = parsedParticleSystem.customShader;
  57266. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57267. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57268. }
  57269. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  57270. particleSystem.customShader = program;
  57271. if (parsedParticleSystem.id) {
  57272. particleSystem.id = parsedParticleSystem.id;
  57273. }
  57274. // Auto start
  57275. if (parsedParticleSystem.preventAutoStart) {
  57276. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  57277. }
  57278. // Texture
  57279. if (parsedParticleSystem.textureName) {
  57280. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57281. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57282. }
  57283. // Emitter
  57284. if (parsedParticleSystem.emitterId) {
  57285. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57286. }
  57287. else {
  57288. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57289. }
  57290. // Animations
  57291. if (parsedParticleSystem.animations) {
  57292. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57293. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57294. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57295. }
  57296. }
  57297. if (parsedParticleSystem.autoAnimate) {
  57298. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57299. }
  57300. // Particle system
  57301. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57302. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57303. particleSystem.minSize = parsedParticleSystem.minSize;
  57304. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57305. if (parsedParticleSystem.minScaleX) {
  57306. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  57307. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  57308. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  57309. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  57310. }
  57311. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57312. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57313. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57314. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57315. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57316. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  57317. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  57318. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57319. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  57320. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  57321. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57322. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57323. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57324. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57325. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57326. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57327. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57328. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57329. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57330. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  57331. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57332. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57333. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57334. if (!particleSystem.preventAutoStart) {
  57335. particleSystem.start();
  57336. }
  57337. return particleSystem;
  57338. };
  57339. /**
  57340. * Source color is added to the destination color without alpha affecting the result.
  57341. */
  57342. ParticleSystem.BLENDMODE_ONEONE = 0;
  57343. /**
  57344. * Blend current color and particle color using particle’s alpha.
  57345. */
  57346. ParticleSystem.BLENDMODE_STANDARD = 1;
  57347. return ParticleSystem;
  57348. }());
  57349. BABYLON.ParticleSystem = ParticleSystem;
  57350. })(BABYLON || (BABYLON = {}));
  57351. //# sourceMappingURL=babylon.particleSystem.js.map
  57352. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  57353. var BABYLON;
  57354. (function (BABYLON) {
  57355. /**
  57356. * Particle emitter emitting particles from the inside of a box.
  57357. * It emits the particles randomly between 2 given directions.
  57358. */
  57359. var BoxParticleEmitter = /** @class */ (function () {
  57360. /**
  57361. * Creates a new instance BoxParticleEmitter
  57362. */
  57363. function BoxParticleEmitter() {
  57364. /**
  57365. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57366. */
  57367. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57368. /**
  57369. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57370. */
  57371. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57372. /**
  57373. * 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.
  57374. */
  57375. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57376. /**
  57377. * 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.
  57378. */
  57379. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  57380. }
  57381. /**
  57382. * Called by the particle System when the direction is computed for the created particle.
  57383. * @param emitPower is the power of the particle (speed)
  57384. * @param worldMatrix is the world matrix of the particle system
  57385. * @param directionToUpdate is the direction vector to update with the result
  57386. * @param particle is the particle we are computed the direction for
  57387. */
  57388. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57389. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57390. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57391. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57392. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57393. };
  57394. /**
  57395. * Called by the particle System when the position is computed for the created particle.
  57396. * @param worldMatrix is the world matrix of the particle system
  57397. * @param positionToUpdate is the position vector to update with the result
  57398. * @param particle is the particle we are computed the position for
  57399. */
  57400. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57401. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  57402. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  57403. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  57404. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57405. };
  57406. /**
  57407. * Clones the current emitter and returns a copy of it
  57408. * @returns the new emitter
  57409. */
  57410. BoxParticleEmitter.prototype.clone = function () {
  57411. var newOne = new BoxParticleEmitter();
  57412. BABYLON.Tools.DeepCopy(this, newOne);
  57413. return newOne;
  57414. };
  57415. /**
  57416. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57417. * @param effect defines the update shader
  57418. */
  57419. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57420. effect.setVector3("direction1", this.direction1);
  57421. effect.setVector3("direction2", this.direction2);
  57422. effect.setVector3("minEmitBox", this.minEmitBox);
  57423. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57424. };
  57425. /**
  57426. * Returns a string to use to update the GPU particles update shader
  57427. * @returns a string containng the defines string
  57428. */
  57429. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57430. return "#define BOXEMITTER";
  57431. };
  57432. /**
  57433. * Returns the string "BoxEmitter"
  57434. * @returns a string containing the class name
  57435. */
  57436. BoxParticleEmitter.prototype.getClassName = function () {
  57437. return "BoxEmitter";
  57438. };
  57439. /**
  57440. * Serializes the particle system to a JSON object.
  57441. * @returns the JSON object
  57442. */
  57443. BoxParticleEmitter.prototype.serialize = function () {
  57444. var serializationObject = {};
  57445. serializationObject.type = this.getClassName();
  57446. serializationObject.direction1 = this.direction1.asArray();
  57447. serializationObject.direction2 = this.direction2.asArray();
  57448. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57449. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57450. return serializationObject;
  57451. };
  57452. /**
  57453. * Parse properties from a JSON object
  57454. * @param serializationObject defines the JSON object
  57455. */
  57456. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57457. this.direction1.copyFrom(serializationObject.direction1);
  57458. this.direction2.copyFrom(serializationObject.direction2);
  57459. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  57460. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  57461. };
  57462. return BoxParticleEmitter;
  57463. }());
  57464. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57465. })(BABYLON || (BABYLON = {}));
  57466. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57467. var BABYLON;
  57468. (function (BABYLON) {
  57469. /**
  57470. * Particle emitter emitting particles from the inside of a cone.
  57471. * It emits the particles alongside the cone volume from the base to the particle.
  57472. * The emission direction might be randomized.
  57473. */
  57474. var ConeParticleEmitter = /** @class */ (function () {
  57475. /**
  57476. * Creates a new instance ConeParticleEmitter
  57477. * @param radius the radius of the emission cone (1 by default)
  57478. * @param angles the cone base angle (PI by default)
  57479. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  57480. */
  57481. function ConeParticleEmitter(radius, angle,
  57482. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  57483. directionRandomizer) {
  57484. if (radius === void 0) { radius = 1; }
  57485. if (angle === void 0) { angle = Math.PI; }
  57486. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57487. this.directionRandomizer = directionRandomizer;
  57488. this.angle = angle;
  57489. this.radius = radius;
  57490. }
  57491. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  57492. /**
  57493. * Gets or sets the radius of the emission cone
  57494. */
  57495. get: function () {
  57496. return this._radius;
  57497. },
  57498. set: function (value) {
  57499. this._radius = value;
  57500. this._buildHeight();
  57501. },
  57502. enumerable: true,
  57503. configurable: true
  57504. });
  57505. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  57506. /**
  57507. * Gets or sets the angle of the emission cone
  57508. */
  57509. get: function () {
  57510. return this._angle;
  57511. },
  57512. set: function (value) {
  57513. this._angle = value;
  57514. this._buildHeight();
  57515. },
  57516. enumerable: true,
  57517. configurable: true
  57518. });
  57519. ConeParticleEmitter.prototype._buildHeight = function () {
  57520. if (this._angle !== 0) {
  57521. this._height = this._radius / Math.tan(this._angle / 2);
  57522. }
  57523. else {
  57524. this._height = 1;
  57525. }
  57526. };
  57527. /**
  57528. * Called by the particle System when the direction is computed for the created particle.
  57529. * @param emitPower is the power of the particle (speed)
  57530. * @param worldMatrix is the world matrix of the particle system
  57531. * @param directionToUpdate is the direction vector to update with the result
  57532. * @param particle is the particle we are computed the direction for
  57533. */
  57534. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57535. if (this._angle === 0) {
  57536. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  57537. }
  57538. else {
  57539. // measure the direction Vector from the emitter to the particle.
  57540. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57541. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57542. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57543. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57544. direction.x += randX;
  57545. direction.y += randY;
  57546. direction.z += randZ;
  57547. direction.normalize();
  57548. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57549. }
  57550. };
  57551. /**
  57552. * Called by the particle System when the position is computed for the created particle.
  57553. * @param worldMatrix is the world matrix of the particle system
  57554. * @param positionToUpdate is the position vector to update with the result
  57555. * @param particle is the particle we are computed the position for
  57556. */
  57557. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57558. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57559. var h = BABYLON.Scalar.RandomRange(0, 1);
  57560. // Better distribution in a cone at normal angles.
  57561. h = 1 - h * h;
  57562. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  57563. radius = radius * h;
  57564. var randX = radius * Math.sin(s);
  57565. var randZ = radius * Math.cos(s);
  57566. var randY = h * this._height;
  57567. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57568. };
  57569. /**
  57570. * Clones the current emitter and returns a copy of it
  57571. * @returns the new emitter
  57572. */
  57573. ConeParticleEmitter.prototype.clone = function () {
  57574. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  57575. BABYLON.Tools.DeepCopy(this, newOne);
  57576. return newOne;
  57577. };
  57578. /**
  57579. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57580. * @param effect defines the update shader
  57581. */
  57582. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57583. effect.setFloat("radius", this._radius);
  57584. effect.setFloat("coneAngle", this._angle);
  57585. effect.setFloat("height", this._height);
  57586. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57587. };
  57588. /**
  57589. * Returns a string to use to update the GPU particles update shader
  57590. * @returns a string containng the defines string
  57591. */
  57592. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57593. return "#define CONEEMITTER";
  57594. };
  57595. /**
  57596. * Returns the string "BoxEmitter"
  57597. * @returns a string containing the class name
  57598. */
  57599. ConeParticleEmitter.prototype.getClassName = function () {
  57600. return "ConeEmitter";
  57601. };
  57602. /**
  57603. * Serializes the particle system to a JSON object.
  57604. * @returns the JSON object
  57605. */
  57606. ConeParticleEmitter.prototype.serialize = function () {
  57607. var serializationObject = {};
  57608. serializationObject.type = this.getClassName();
  57609. serializationObject.radius = this._radius;
  57610. serializationObject.angle = this._angle;
  57611. serializationObject.directionRandomizer = this.directionRandomizer;
  57612. return serializationObject;
  57613. };
  57614. /**
  57615. * Parse properties from a JSON object
  57616. * @param serializationObject defines the JSON object
  57617. */
  57618. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57619. this.radius = serializationObject.radius;
  57620. this.angle = serializationObject.angle;
  57621. this.directionRandomizer = serializationObject.directionRandomizer;
  57622. };
  57623. return ConeParticleEmitter;
  57624. }());
  57625. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57626. })(BABYLON || (BABYLON = {}));
  57627. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57628. var BABYLON;
  57629. (function (BABYLON) {
  57630. /**
  57631. * Particle emitter emitting particles from the inside of a sphere.
  57632. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57633. */
  57634. var SphereParticleEmitter = /** @class */ (function () {
  57635. /**
  57636. * Creates a new instance SphereParticleEmitter
  57637. * @param radius the radius of the emission sphere (1 by default)
  57638. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57639. */
  57640. function SphereParticleEmitter(
  57641. /**
  57642. * The radius of the emission sphere.
  57643. */
  57644. radius,
  57645. /**
  57646. * How much to randomize the particle direction [0-1].
  57647. */
  57648. directionRandomizer) {
  57649. if (radius === void 0) { radius = 1; }
  57650. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57651. this.radius = radius;
  57652. this.directionRandomizer = directionRandomizer;
  57653. }
  57654. /**
  57655. * Called by the particle System when the direction is computed for the created particle.
  57656. * @param emitPower is the power of the particle (speed)
  57657. * @param worldMatrix is the world matrix of the particle system
  57658. * @param directionToUpdate is the direction vector to update with the result
  57659. * @param particle is the particle we are computed the direction for
  57660. */
  57661. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57662. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57663. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57664. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57665. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57666. direction.x += randX;
  57667. direction.y += randY;
  57668. direction.z += randZ;
  57669. direction.normalize();
  57670. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57671. };
  57672. /**
  57673. * Called by the particle System when the position is computed for the created particle.
  57674. * @param worldMatrix is the world matrix of the particle system
  57675. * @param positionToUpdate is the position vector to update with the result
  57676. * @param particle is the particle we are computed the position for
  57677. */
  57678. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57679. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57680. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  57681. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  57682. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57683. var randY = randRadius * Math.cos(theta);
  57684. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57685. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57686. };
  57687. /**
  57688. * Clones the current emitter and returns a copy of it
  57689. * @returns the new emitter
  57690. */
  57691. SphereParticleEmitter.prototype.clone = function () {
  57692. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57693. BABYLON.Tools.DeepCopy(this, newOne);
  57694. return newOne;
  57695. };
  57696. /**
  57697. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57698. * @param effect defines the update shader
  57699. */
  57700. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57701. effect.setFloat("radius", this.radius);
  57702. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57703. };
  57704. /**
  57705. * Returns a string to use to update the GPU particles update shader
  57706. * @returns a string containng the defines string
  57707. */
  57708. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57709. return "#define SPHEREEMITTER";
  57710. };
  57711. /**
  57712. * Returns the string "SphereParticleEmitter"
  57713. * @returns a string containing the class name
  57714. */
  57715. SphereParticleEmitter.prototype.getClassName = function () {
  57716. return "SphereParticleEmitter";
  57717. };
  57718. /**
  57719. * Serializes the particle system to a JSON object.
  57720. * @returns the JSON object
  57721. */
  57722. SphereParticleEmitter.prototype.serialize = function () {
  57723. var serializationObject = {};
  57724. serializationObject.type = this.getClassName();
  57725. serializationObject.radius = this.radius;
  57726. serializationObject.directionRandomizer = this.directionRandomizer;
  57727. return serializationObject;
  57728. };
  57729. /**
  57730. * Parse properties from a JSON object
  57731. * @param serializationObject defines the JSON object
  57732. */
  57733. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57734. this.radius = serializationObject.radius;
  57735. this.directionRandomizer = serializationObject.directionRandomizer;
  57736. };
  57737. return SphereParticleEmitter;
  57738. }());
  57739. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57740. /**
  57741. * Particle emitter emitting particles from the inside of a sphere.
  57742. * It emits the particles randomly between two vectors.
  57743. */
  57744. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57745. __extends(SphereDirectedParticleEmitter, _super);
  57746. /**
  57747. * Creates a new instance SphereDirectedParticleEmitter
  57748. * @param radius the radius of the emission sphere (1 by default)
  57749. * @param direction1 the min limit of the emission direction (up vector by default)
  57750. * @param direction2 the max limit of the emission direction (up vector by default)
  57751. */
  57752. function SphereDirectedParticleEmitter(radius,
  57753. /**
  57754. * The min limit of the emission direction.
  57755. */
  57756. direction1,
  57757. /**
  57758. * The max limit of the emission direction.
  57759. */
  57760. direction2) {
  57761. if (radius === void 0) { radius = 1; }
  57762. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57763. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57764. var _this = _super.call(this, radius) || this;
  57765. _this.direction1 = direction1;
  57766. _this.direction2 = direction2;
  57767. return _this;
  57768. }
  57769. /**
  57770. * Called by the particle System when the direction is computed for the created particle.
  57771. * @param emitPower is the power of the particle (speed)
  57772. * @param worldMatrix is the world matrix of the particle system
  57773. * @param directionToUpdate is the direction vector to update with the result
  57774. * @param particle is the particle we are computed the direction for
  57775. */
  57776. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57777. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57778. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57779. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57780. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57781. };
  57782. /**
  57783. * Clones the current emitter and returns a copy of it
  57784. * @returns the new emitter
  57785. */
  57786. SphereDirectedParticleEmitter.prototype.clone = function () {
  57787. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57788. BABYLON.Tools.DeepCopy(this, newOne);
  57789. return newOne;
  57790. };
  57791. /**
  57792. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57793. * @param effect defines the update shader
  57794. */
  57795. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57796. effect.setFloat("radius", this.radius);
  57797. effect.setVector3("direction1", this.direction1);
  57798. effect.setVector3("direction2", this.direction2);
  57799. };
  57800. /**
  57801. * Returns a string to use to update the GPU particles update shader
  57802. * @returns a string containng the defines string
  57803. */
  57804. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57805. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57806. };
  57807. /**
  57808. * Returns the string "SphereDirectedParticleEmitter"
  57809. * @returns a string containing the class name
  57810. */
  57811. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57812. return "SphereDirectedParticleEmitter";
  57813. };
  57814. /**
  57815. * Serializes the particle system to a JSON object.
  57816. * @returns the JSON object
  57817. */
  57818. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57819. var serializationObject = _super.prototype.serialize.call(this);
  57820. serializationObject.direction1 = this.direction1.asArray();
  57821. serializationObject.direction2 = this.direction2.asArray();
  57822. return serializationObject;
  57823. };
  57824. /**
  57825. * Parse properties from a JSON object
  57826. * @param serializationObject defines the JSON object
  57827. */
  57828. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57829. _super.prototype.parse.call(this, serializationObject);
  57830. this.direction1.copyFrom(serializationObject.direction1);
  57831. this.direction2.copyFrom(serializationObject.direction2);
  57832. };
  57833. return SphereDirectedParticleEmitter;
  57834. }(SphereParticleEmitter));
  57835. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57836. })(BABYLON || (BABYLON = {}));
  57837. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57838. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57839. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57840. s = arguments[i];
  57841. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57842. t[p] = s[p];
  57843. }
  57844. return t;
  57845. };
  57846. var BABYLON;
  57847. (function (BABYLON) {
  57848. /**
  57849. * This represents a GPU particle system in Babylon
  57850. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57851. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57852. */
  57853. var GPUParticleSystem = /** @class */ (function () {
  57854. /**
  57855. * Instantiates a GPU particle system.
  57856. * 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.
  57857. * @param name The name of the particle system
  57858. * @param capacity The max number of particles alive at the same time
  57859. * @param scene The scene the particle system belongs to
  57860. */
  57861. function GPUParticleSystem(name, options, scene) {
  57862. /**
  57863. * The emitter represents the Mesh or position we are attaching the particle system to.
  57864. */
  57865. this.emitter = null;
  57866. /**
  57867. * The rendering group used by the Particle system to chose when to render.
  57868. */
  57869. this.renderingGroupId = 0;
  57870. /**
  57871. * The layer mask we are rendering the particles through.
  57872. */
  57873. this.layerMask = 0x0FFFFFFF;
  57874. this._targetIndex = 0;
  57875. this._currentRenderId = -1;
  57876. this._started = false;
  57877. this._stopped = false;
  57878. this._timeDelta = 0;
  57879. this._attributesStrideSize = 18;
  57880. this._actualFrame = 0;
  57881. /**
  57882. * List of animations used by the particle system.
  57883. */
  57884. this.animations = [];
  57885. /**
  57886. * An event triggered when the system is disposed.
  57887. */
  57888. this.onDisposeObservable = new BABYLON.Observable();
  57889. /**
  57890. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57891. */
  57892. this.updateSpeed = 0.01;
  57893. /**
  57894. * The amount of time the particle system is running (depends of the overall update speed).
  57895. */
  57896. this.targetStopDuration = 0;
  57897. /**
  57898. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57899. */
  57900. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57901. /**
  57902. * Minimum life time of emitting particles.
  57903. */
  57904. this.minLifeTime = 1;
  57905. /**
  57906. * Maximum life time of emitting particles.
  57907. */
  57908. this.maxLifeTime = 1;
  57909. /**
  57910. * Minimum Size of emitting particles.
  57911. */
  57912. this.minSize = 1;
  57913. /**
  57914. * Maximum Size of emitting particles.
  57915. */
  57916. this.maxSize = 1;
  57917. /**
  57918. * Minimum scale of emitting particles on X axis.
  57919. */
  57920. this.minScaleX = 1;
  57921. /**
  57922. * Maximum scale of emitting particles on X axis.
  57923. */
  57924. this.maxScaleX = 1;
  57925. /**
  57926. * Minimum scale of emitting particles on Y axis.
  57927. */
  57928. this.minScaleY = 1;
  57929. /**
  57930. * Maximum scale of emitting particles on Y axis.
  57931. */
  57932. this.maxScaleY = 1;
  57933. /**
  57934. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57935. */
  57936. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57937. /**
  57938. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57939. */
  57940. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57941. /**
  57942. * Color the particle will have at the end of its lifetime.
  57943. */
  57944. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57945. /**
  57946. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57947. */
  57948. this.emitRate = 100;
  57949. /**
  57950. * You can use gravity if you want to give an orientation to your particles.
  57951. */
  57952. this.gravity = BABYLON.Vector3.Zero();
  57953. /**
  57954. * Minimum power of emitting particles.
  57955. */
  57956. this.minEmitPower = 1;
  57957. /**
  57958. * Maximum power of emitting particles.
  57959. */
  57960. this.maxEmitPower = 1;
  57961. /**
  57962. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57963. */
  57964. this.minAngularSpeed = 0;
  57965. /**
  57966. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57967. */
  57968. this.maxAngularSpeed = 0;
  57969. /**
  57970. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57971. * to override the particles.
  57972. */
  57973. this.forceDepthWrite = false;
  57974. this.id = name;
  57975. this.name = name;
  57976. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57977. this._engine = this._scene.getEngine();
  57978. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57979. this._capacity = fullOptions.capacity;
  57980. this._activeCount = fullOptions.capacity;
  57981. this._currentActiveCount = 0;
  57982. this._scene.particleSystems.push(this);
  57983. this._updateEffectOptions = {
  57984. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "angle"],
  57985. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  57986. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57987. "angleRange"],
  57988. uniformBuffersNames: [],
  57989. samplers: ["randomSampler"],
  57990. defines: "",
  57991. fallbacks: null,
  57992. onCompiled: null,
  57993. onError: null,
  57994. indexParameters: null,
  57995. maxSimultaneousLights: 0,
  57996. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection", "outAngle"]
  57997. };
  57998. // Random data
  57999. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  58000. var d = [];
  58001. for (var i = 0; i < maxTextureSize; ++i) {
  58002. d.push(Math.random());
  58003. d.push(Math.random());
  58004. d.push(Math.random());
  58005. d.push(Math.random());
  58006. }
  58007. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  58008. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58009. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58010. this._randomTextureSize = maxTextureSize;
  58011. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  58012. }
  58013. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  58014. /**
  58015. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  58016. */
  58017. get: function () {
  58018. if (!BABYLON.Engine.LastCreatedEngine) {
  58019. return false;
  58020. }
  58021. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  58022. },
  58023. enumerable: true,
  58024. configurable: true
  58025. });
  58026. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  58027. /**
  58028. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58029. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58030. */
  58031. get: function () {
  58032. if (this.particleEmitterType.direction1) {
  58033. return this.particleEmitterType.direction1;
  58034. }
  58035. return BABYLON.Vector3.Zero();
  58036. },
  58037. set: function (value) {
  58038. if (this.particleEmitterType.direction1) {
  58039. this.particleEmitterType.direction1 = value;
  58040. }
  58041. },
  58042. enumerable: true,
  58043. configurable: true
  58044. });
  58045. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  58046. /**
  58047. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58048. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58049. */
  58050. get: function () {
  58051. if (this.particleEmitterType.direction2) {
  58052. return this.particleEmitterType.direction2;
  58053. }
  58054. return BABYLON.Vector3.Zero();
  58055. },
  58056. set: function (value) {
  58057. if (this.particleEmitterType.direction2) {
  58058. this.particleEmitterType.direction2 = value;
  58059. }
  58060. },
  58061. enumerable: true,
  58062. configurable: true
  58063. });
  58064. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  58065. /**
  58066. * 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.
  58067. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58068. */
  58069. get: function () {
  58070. if (this.particleEmitterType.minEmitBox) {
  58071. return this.particleEmitterType.minEmitBox;
  58072. }
  58073. return BABYLON.Vector3.Zero();
  58074. },
  58075. set: function (value) {
  58076. if (this.particleEmitterType.minEmitBox) {
  58077. this.particleEmitterType.minEmitBox = value;
  58078. }
  58079. },
  58080. enumerable: true,
  58081. configurable: true
  58082. });
  58083. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  58084. /**
  58085. * 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.
  58086. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58087. */
  58088. get: function () {
  58089. if (this.particleEmitterType.maxEmitBox) {
  58090. return this.particleEmitterType.maxEmitBox;
  58091. }
  58092. return BABYLON.Vector3.Zero();
  58093. },
  58094. set: function (value) {
  58095. if (this.particleEmitterType.maxEmitBox) {
  58096. this.particleEmitterType.maxEmitBox = value;
  58097. }
  58098. },
  58099. enumerable: true,
  58100. configurable: true
  58101. });
  58102. /**
  58103. * Gets the maximum number of particles active at the same time.
  58104. * @returns The max number of active particles.
  58105. */
  58106. GPUParticleSystem.prototype.getCapacity = function () {
  58107. return this._capacity;
  58108. };
  58109. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  58110. /**
  58111. * Gets or set the number of active particles
  58112. */
  58113. get: function () {
  58114. return this._activeCount;
  58115. },
  58116. set: function (value) {
  58117. this._activeCount = Math.min(value, this._capacity);
  58118. },
  58119. enumerable: true,
  58120. configurable: true
  58121. });
  58122. /**
  58123. * Is this system ready to be used/rendered
  58124. * @return true if the system is ready
  58125. */
  58126. GPUParticleSystem.prototype.isReady = function () {
  58127. if (!this._updateEffect) {
  58128. this._recreateUpdateEffect();
  58129. this._recreateRenderEffect();
  58130. return false;
  58131. }
  58132. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  58133. return false;
  58134. }
  58135. return true;
  58136. };
  58137. /**
  58138. * Gets Wether the system has been started.
  58139. * @returns True if it has been started, otherwise false.
  58140. */
  58141. GPUParticleSystem.prototype.isStarted = function () {
  58142. return this._started;
  58143. };
  58144. /**
  58145. * Starts the particle system and begins to emit.
  58146. */
  58147. GPUParticleSystem.prototype.start = function () {
  58148. this._started = true;
  58149. this._stopped = false;
  58150. };
  58151. /**
  58152. * Stops the particle system.
  58153. */
  58154. GPUParticleSystem.prototype.stop = function () {
  58155. this._stopped = true;
  58156. };
  58157. /**
  58158. * Remove all active particles
  58159. */
  58160. GPUParticleSystem.prototype.reset = function () {
  58161. this._releaseBuffers();
  58162. this._releaseVAOs();
  58163. this._currentActiveCount = 0;
  58164. this._targetIndex = 0;
  58165. };
  58166. /**
  58167. * Returns the string "GPUParticleSystem"
  58168. * @returns a string containing the class name
  58169. */
  58170. GPUParticleSystem.prototype.getClassName = function () {
  58171. return "GPUParticleSystem";
  58172. };
  58173. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  58174. var updateVertexBuffers = {};
  58175. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  58176. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  58177. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  58178. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  58179. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 3);
  58180. updateVertexBuffers["color"] = source.createVertexBuffer("color", 9, 4);
  58181. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 13, 3);
  58182. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", 16, 2);
  58183. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  58184. this._engine.bindArrayBuffer(null);
  58185. return vao;
  58186. };
  58187. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  58188. var renderVertexBuffers = {};
  58189. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  58190. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  58191. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  58192. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 3, this._attributesStrideSize, true);
  58193. renderVertexBuffers["color"] = source.createVertexBuffer("color", 9, 4, this._attributesStrideSize, true);
  58194. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", 16, 2, this._attributesStrideSize, true);
  58195. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  58196. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  58197. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  58198. this._engine.bindArrayBuffer(null);
  58199. return vao;
  58200. };
  58201. GPUParticleSystem.prototype._initialize = function (force) {
  58202. if (force === void 0) { force = false; }
  58203. if (this._buffer0 && !force) {
  58204. return;
  58205. }
  58206. var engine = this._scene.getEngine();
  58207. var data = new Array();
  58208. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  58209. // position
  58210. data.push(0.0);
  58211. data.push(0.0);
  58212. data.push(0.0);
  58213. // Age and life
  58214. data.push(0.0); // create the particle as a dead one to create a new one at start
  58215. data.push(0.0);
  58216. // Seed
  58217. data.push(Math.random());
  58218. // Size
  58219. data.push(0.0);
  58220. data.push(0.0);
  58221. data.push(0.0);
  58222. // color
  58223. data.push(0.0);
  58224. data.push(0.0);
  58225. data.push(0.0);
  58226. data.push(0.0);
  58227. // direction
  58228. data.push(0.0);
  58229. data.push(0.0);
  58230. data.push(0.0);
  58231. // angle
  58232. data.push(0.0);
  58233. data.push(0.0);
  58234. }
  58235. // Sprite data
  58236. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  58237. -0.5, 0.5, 0, 1,
  58238. -0.5, -0.5, 0, 0,
  58239. 0.5, -0.5, 1, 0]);
  58240. // Buffers
  58241. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  58242. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  58243. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  58244. // Update VAO
  58245. this._updateVAO = [];
  58246. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  58247. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  58248. // Render VAO
  58249. this._renderVAO = [];
  58250. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  58251. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  58252. // Links
  58253. this._sourceBuffer = this._buffer0;
  58254. this._targetBuffer = this._buffer1;
  58255. };
  58256. /** @hidden */
  58257. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  58258. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  58259. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  58260. return;
  58261. }
  58262. this._updateEffectOptions.defines = defines;
  58263. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  58264. };
  58265. /** @hidden */
  58266. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  58267. var defines = "";
  58268. if (this._scene.clipPlane) {
  58269. defines = "\n#define CLIPPLANE";
  58270. }
  58271. if (this._renderEffect && this._renderEffect.defines === defines) {
  58272. return;
  58273. }
  58274. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  58275. };
  58276. /**
  58277. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  58278. */
  58279. GPUParticleSystem.prototype.animate = function () {
  58280. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  58281. this._actualFrame += this._timeDelta;
  58282. if (!this._stopped) {
  58283. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  58284. this.stop();
  58285. }
  58286. }
  58287. };
  58288. /**
  58289. * Renders the particle system in its current state.
  58290. * @returns the current number of particles
  58291. */
  58292. GPUParticleSystem.prototype.render = function () {
  58293. if (!this._started) {
  58294. return 0;
  58295. }
  58296. this._recreateUpdateEffect();
  58297. this._recreateRenderEffect();
  58298. if (!this.isReady()) {
  58299. return 0;
  58300. }
  58301. if (this._currentRenderId === this._scene.getRenderId()) {
  58302. return 0;
  58303. }
  58304. this._currentRenderId = this._scene.getRenderId();
  58305. // Get everything ready to render
  58306. this._initialize();
  58307. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  58308. // Enable update effect
  58309. this._engine.enableEffect(this._updateEffect);
  58310. this._engine.setState(false);
  58311. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  58312. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  58313. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  58314. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  58315. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  58316. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  58317. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  58318. this._updateEffect.setDirectColor4("color1", this.color1);
  58319. this._updateEffect.setDirectColor4("color2", this.color2);
  58320. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  58321. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  58322. this._updateEffect.setFloat2("angleRange", this.minAngularSpeed, this.maxAngularSpeed);
  58323. this._updateEffect.setVector3("gravity", this.gravity);
  58324. if (this.particleEmitterType) {
  58325. this.particleEmitterType.applyToShader(this._updateEffect);
  58326. }
  58327. var emitterWM;
  58328. if (this.emitter.position) {
  58329. var emitterMesh = this.emitter;
  58330. emitterWM = emitterMesh.getWorldMatrix();
  58331. }
  58332. else {
  58333. var emitterPosition = this.emitter;
  58334. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58335. }
  58336. this._updateEffect.setMatrix("emitterWM", emitterWM);
  58337. // Bind source VAO
  58338. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  58339. // Update
  58340. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  58341. this._engine.setRasterizerState(false);
  58342. this._engine.beginTransformFeedback();
  58343. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  58344. this._engine.endTransformFeedback();
  58345. this._engine.setRasterizerState(true);
  58346. this._engine.bindTransformFeedbackBuffer(null);
  58347. // Enable render effect
  58348. this._engine.enableEffect(this._renderEffect);
  58349. var viewMatrix = this._scene.getViewMatrix();
  58350. this._renderEffect.setMatrix("view", viewMatrix);
  58351. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  58352. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  58353. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  58354. if (this._scene.clipPlane) {
  58355. var clipPlane = this._scene.clipPlane;
  58356. var invView = viewMatrix.clone();
  58357. invView.invert();
  58358. this._renderEffect.setMatrix("invView", invView);
  58359. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  58360. }
  58361. // Draw order
  58362. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  58363. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58364. }
  58365. else {
  58366. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58367. }
  58368. if (this.forceDepthWrite) {
  58369. this._engine.setDepthWrite(true);
  58370. }
  58371. // Bind source VAO
  58372. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  58373. // Render
  58374. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  58375. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58376. // Switch VAOs
  58377. this._targetIndex++;
  58378. if (this._targetIndex === 2) {
  58379. this._targetIndex = 0;
  58380. }
  58381. // Switch buffers
  58382. var tmpBuffer = this._sourceBuffer;
  58383. this._sourceBuffer = this._targetBuffer;
  58384. this._targetBuffer = tmpBuffer;
  58385. return this._currentActiveCount;
  58386. };
  58387. /**
  58388. * Rebuilds the particle system
  58389. */
  58390. GPUParticleSystem.prototype.rebuild = function () {
  58391. this._initialize(true);
  58392. };
  58393. GPUParticleSystem.prototype._releaseBuffers = function () {
  58394. if (this._buffer0) {
  58395. this._buffer0.dispose();
  58396. this._buffer0 = null;
  58397. }
  58398. if (this._buffer1) {
  58399. this._buffer1.dispose();
  58400. this._buffer1 = null;
  58401. }
  58402. if (this._spriteBuffer) {
  58403. this._spriteBuffer.dispose();
  58404. this._spriteBuffer = null;
  58405. }
  58406. };
  58407. GPUParticleSystem.prototype._releaseVAOs = function () {
  58408. if (!this._updateVAO) {
  58409. return;
  58410. }
  58411. for (var index = 0; index < this._updateVAO.length; index++) {
  58412. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  58413. }
  58414. this._updateVAO = [];
  58415. for (var index = 0; index < this._renderVAO.length; index++) {
  58416. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  58417. }
  58418. this._renderVAO = [];
  58419. };
  58420. /**
  58421. * Disposes the particle system and free the associated resources
  58422. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58423. */
  58424. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  58425. if (disposeTexture === void 0) { disposeTexture = true; }
  58426. var index = this._scene.particleSystems.indexOf(this);
  58427. if (index > -1) {
  58428. this._scene.particleSystems.splice(index, 1);
  58429. }
  58430. this._releaseBuffers();
  58431. this._releaseVAOs();
  58432. if (this._randomTexture) {
  58433. this._randomTexture.dispose();
  58434. this._randomTexture = null;
  58435. }
  58436. if (disposeTexture && this.particleTexture) {
  58437. this.particleTexture.dispose();
  58438. this.particleTexture = null;
  58439. }
  58440. // Callback
  58441. this.onDisposeObservable.notifyObservers(this);
  58442. this.onDisposeObservable.clear();
  58443. };
  58444. /**
  58445. * Clones the particle system.
  58446. * @param name The name of the cloned object
  58447. * @param newEmitter The new emitter to use
  58448. * @returns the cloned particle system
  58449. */
  58450. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  58451. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  58452. BABYLON.Tools.DeepCopy(this, result);
  58453. if (newEmitter === undefined) {
  58454. newEmitter = this.emitter;
  58455. }
  58456. result.emitter = newEmitter;
  58457. if (this.particleTexture) {
  58458. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58459. }
  58460. return result;
  58461. };
  58462. /**
  58463. * Serializes the particle system to a JSON object.
  58464. * @returns the JSON object
  58465. */
  58466. GPUParticleSystem.prototype.serialize = function () {
  58467. var serializationObject = {};
  58468. serializationObject.name = this.name;
  58469. serializationObject.id = this.id;
  58470. // Emitter
  58471. if (this.emitter.position) {
  58472. var emitterMesh = this.emitter;
  58473. serializationObject.emitterId = emitterMesh.id;
  58474. }
  58475. else {
  58476. var emitterPosition = this.emitter;
  58477. serializationObject.emitter = emitterPosition.asArray();
  58478. }
  58479. serializationObject.capacity = this.getCapacity();
  58480. if (this.particleTexture) {
  58481. serializationObject.textureName = this.particleTexture.name;
  58482. }
  58483. // Animations
  58484. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  58485. // Particle system
  58486. serializationObject.activeParticleCount = this.activeParticleCount;
  58487. serializationObject.randomTextureSize = this._randomTextureSize;
  58488. serializationObject.minSize = this.minSize;
  58489. serializationObject.maxSize = this.maxSize;
  58490. serializationObject.minEmitPower = this.minEmitPower;
  58491. serializationObject.maxEmitPower = this.maxEmitPower;
  58492. serializationObject.minLifeTime = this.minLifeTime;
  58493. serializationObject.maxLifeTime = this.maxLifeTime;
  58494. serializationObject.minAngularSpeed = this.minAngularSpeed;
  58495. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  58496. serializationObject.emitRate = this.emitRate;
  58497. serializationObject.gravity = this.gravity.asArray();
  58498. serializationObject.color1 = this.color1.asArray();
  58499. serializationObject.color2 = this.color2.asArray();
  58500. serializationObject.colorDead = this.colorDead.asArray();
  58501. serializationObject.updateSpeed = this.updateSpeed;
  58502. serializationObject.targetStopDuration = this.targetStopDuration;
  58503. serializationObject.blendMode = this.blendMode;
  58504. // Emitter
  58505. if (this.particleEmitterType) {
  58506. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  58507. }
  58508. return serializationObject;
  58509. };
  58510. /**
  58511. * Parses a JSON object to create a GPU particle system.
  58512. * @param parsedParticleSystem The JSON object to parse
  58513. * @param scene The scene to create the particle system in
  58514. * @param rootUrl The root url to use to load external dependencies like texture
  58515. * @returns the parsed GPU particle system
  58516. */
  58517. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58518. var name = parsedParticleSystem.name;
  58519. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  58520. if (parsedParticleSystem.id) {
  58521. particleSystem.id = parsedParticleSystem.id;
  58522. }
  58523. // Texture
  58524. if (parsedParticleSystem.textureName) {
  58525. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  58526. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  58527. }
  58528. // Emitter
  58529. if (parsedParticleSystem.emitterId) {
  58530. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  58531. }
  58532. else {
  58533. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  58534. }
  58535. // Animations
  58536. if (parsedParticleSystem.animations) {
  58537. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  58538. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  58539. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58540. }
  58541. }
  58542. // Particle system
  58543. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  58544. particleSystem.minSize = parsedParticleSystem.minSize;
  58545. particleSystem.maxSize = parsedParticleSystem.maxSize;
  58546. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  58547. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  58548. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  58549. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  58550. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  58551. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  58552. particleSystem.emitRate = parsedParticleSystem.emitRate;
  58553. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  58554. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  58555. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  58556. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  58557. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  58558. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  58559. particleSystem.blendMode = parsedParticleSystem.blendMode;
  58560. // Emitter
  58561. if (parsedParticleSystem.particleEmitterType) {
  58562. var emitterType = void 0;
  58563. switch (parsedParticleSystem.particleEmitterType.type) {
  58564. case "SphereEmitter":
  58565. emitterType = new BABYLON.SphereParticleEmitter();
  58566. break;
  58567. case "SphereDirectedParticleEmitter":
  58568. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  58569. break;
  58570. case "ConeEmitter":
  58571. emitterType = new BABYLON.ConeParticleEmitter();
  58572. break;
  58573. case "BoxEmitter":
  58574. default:
  58575. emitterType = new BABYLON.BoxParticleEmitter();
  58576. break;
  58577. }
  58578. emitterType.parse(parsedParticleSystem.particleEmitterType);
  58579. particleSystem.particleEmitterType = emitterType;
  58580. }
  58581. return particleSystem;
  58582. };
  58583. return GPUParticleSystem;
  58584. }());
  58585. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58586. })(BABYLON || (BABYLON = {}));
  58587. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58588. var BABYLON;
  58589. (function (BABYLON) {
  58590. /**
  58591. * Represents one particle of a solid particle system.
  58592. */
  58593. var SolidParticle = /** @class */ (function () {
  58594. /**
  58595. * Creates a Solid Particle object.
  58596. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58597. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58598. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58599. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58600. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58601. * @param shapeId (integer) is the model shape identifier in the SPS.
  58602. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58603. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58604. */
  58605. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58606. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58607. /**
  58608. * particle global index
  58609. */
  58610. this.idx = 0;
  58611. /**
  58612. * The color of the particle
  58613. */
  58614. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58615. /**
  58616. * The world space position of the particle.
  58617. */
  58618. this.position = BABYLON.Vector3.Zero();
  58619. /**
  58620. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58621. */
  58622. this.rotation = BABYLON.Vector3.Zero();
  58623. /**
  58624. * The scaling of the particle.
  58625. */
  58626. this.scaling = BABYLON.Vector3.One();
  58627. /**
  58628. * The uvs of the particle.
  58629. */
  58630. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58631. /**
  58632. * The current speed of the particle.
  58633. */
  58634. this.velocity = BABYLON.Vector3.Zero();
  58635. /**
  58636. * The pivot point in the particle local space.
  58637. */
  58638. this.pivot = BABYLON.Vector3.Zero();
  58639. /**
  58640. * Must the particle be translated from its pivot point in its local space ?
  58641. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58642. * Default : false
  58643. */
  58644. this.translateFromPivot = false;
  58645. /**
  58646. * Is the particle active or not ?
  58647. */
  58648. this.alive = true;
  58649. /**
  58650. * Is the particle visible or not ?
  58651. */
  58652. this.isVisible = true;
  58653. /**
  58654. * Index of this particle in the global "positions" array (Internal use)
  58655. */
  58656. this._pos = 0;
  58657. /**
  58658. * Index of this particle in the global "indices" array (Internal use)
  58659. */
  58660. this._ind = 0;
  58661. /**
  58662. * ModelShape id of this particle
  58663. */
  58664. this.shapeId = 0;
  58665. /**
  58666. * Index of the particle in its shape id (Internal use)
  58667. */
  58668. this.idxInShape = 0;
  58669. /**
  58670. * Still set as invisible in order to skip useless computations (Internal use)
  58671. */
  58672. this._stillInvisible = false;
  58673. /**
  58674. * Last computed particle rotation matrix
  58675. */
  58676. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58677. /**
  58678. * Parent particle Id, if any.
  58679. * Default null.
  58680. */
  58681. this.parentId = null;
  58682. /**
  58683. * Internal global position in the SPS.
  58684. */
  58685. this._globalPosition = BABYLON.Vector3.Zero();
  58686. this.idx = particleIndex;
  58687. this._pos = positionIndex;
  58688. this._ind = indiceIndex;
  58689. this._model = model;
  58690. this.shapeId = shapeId;
  58691. this.idxInShape = idxInShape;
  58692. this._sps = sps;
  58693. if (modelBoundingInfo) {
  58694. this._modelBoundingInfo = modelBoundingInfo;
  58695. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58696. }
  58697. }
  58698. Object.defineProperty(SolidParticle.prototype, "scale", {
  58699. /**
  58700. * Legacy support, changed scale to scaling
  58701. */
  58702. get: function () {
  58703. return this.scaling;
  58704. },
  58705. /**
  58706. * Legacy support, changed scale to scaling
  58707. */
  58708. set: function (scale) {
  58709. this.scaling = scale;
  58710. },
  58711. enumerable: true,
  58712. configurable: true
  58713. });
  58714. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58715. /**
  58716. * Legacy support, changed quaternion to rotationQuaternion
  58717. */
  58718. get: function () {
  58719. return this.rotationQuaternion;
  58720. },
  58721. /**
  58722. * Legacy support, changed quaternion to rotationQuaternion
  58723. */
  58724. set: function (q) {
  58725. this.rotationQuaternion = q;
  58726. },
  58727. enumerable: true,
  58728. configurable: true
  58729. });
  58730. /**
  58731. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58732. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58733. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58734. * @returns true if it intersects
  58735. */
  58736. SolidParticle.prototype.intersectsMesh = function (target) {
  58737. if (!this._boundingInfo || !target._boundingInfo) {
  58738. return false;
  58739. }
  58740. if (this._sps._bSphereOnly) {
  58741. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58742. }
  58743. return this._boundingInfo.intersects(target._boundingInfo, false);
  58744. };
  58745. return SolidParticle;
  58746. }());
  58747. BABYLON.SolidParticle = SolidParticle;
  58748. /**
  58749. * Represents the shape of the model used by one particle of a solid particle system.
  58750. * SPS internal tool, don't use it manually.
  58751. */
  58752. var ModelShape = /** @class */ (function () {
  58753. /**
  58754. * 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.
  58755. * SPS internal tool, don't use it manually.
  58756. * @hidden
  58757. */
  58758. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58759. /**
  58760. * length of the shape in the model indices array (internal use)
  58761. */
  58762. this._indicesLength = 0;
  58763. this.shapeID = id;
  58764. this._shape = shape;
  58765. this._indicesLength = indicesLength;
  58766. this._shapeUV = shapeUV;
  58767. this._positionFunction = posFunction;
  58768. this._vertexFunction = vtxFunction;
  58769. }
  58770. return ModelShape;
  58771. }());
  58772. BABYLON.ModelShape = ModelShape;
  58773. /**
  58774. * Represents a Depth Sorted Particle in the solid particle system.
  58775. */
  58776. var DepthSortedParticle = /** @class */ (function () {
  58777. function DepthSortedParticle() {
  58778. /**
  58779. * Index of the particle in the "indices" array
  58780. */
  58781. this.ind = 0;
  58782. /**
  58783. * Length of the particle shape in the "indices" array
  58784. */
  58785. this.indicesLength = 0;
  58786. /**
  58787. * Squared distance from the particle to the camera
  58788. */
  58789. this.sqDistance = 0.0;
  58790. }
  58791. return DepthSortedParticle;
  58792. }());
  58793. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58794. })(BABYLON || (BABYLON = {}));
  58795. //# sourceMappingURL=babylon.solidParticle.js.map
  58796. var BABYLON;
  58797. (function (BABYLON) {
  58798. /**
  58799. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58800. *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.
  58801. * The SPS is also a particle system. It provides some methods to manage the particles.
  58802. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58803. *
  58804. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58805. */
  58806. var SolidParticleSystem = /** @class */ (function () {
  58807. /**
  58808. * Creates a SPS (Solid Particle System) object.
  58809. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58810. * @param scene (Scene) is the scene in which the SPS is added.
  58811. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58812. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58813. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58814. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58815. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58816. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58817. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58818. */
  58819. function SolidParticleSystem(name, scene, options) {
  58820. /**
  58821. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58822. * Example : var p = SPS.particles[i];
  58823. */
  58824. this.particles = new Array();
  58825. /**
  58826. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58827. */
  58828. this.nbParticles = 0;
  58829. /**
  58830. * If the particles must ever face the camera (default false). Useful for planar particles.
  58831. */
  58832. this.billboard = false;
  58833. /**
  58834. * Recompute normals when adding a shape
  58835. */
  58836. this.recomputeNormals = true;
  58837. /**
  58838. * This a counter ofr your own usage. It's not set by any SPS functions.
  58839. */
  58840. this.counter = 0;
  58841. /**
  58842. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58843. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58844. */
  58845. this.vars = {};
  58846. /**
  58847. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58848. */
  58849. this._bSphereOnly = false;
  58850. /**
  58851. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58852. */
  58853. this._bSphereRadiusFactor = 1.0;
  58854. this._positions = new Array();
  58855. this._indices = new Array();
  58856. this._normals = new Array();
  58857. this._colors = new Array();
  58858. this._uvs = new Array();
  58859. this._index = 0; // indices index
  58860. this._updatable = true;
  58861. this._pickable = false;
  58862. this._isVisibilityBoxLocked = false;
  58863. this._alwaysVisible = false;
  58864. this._depthSort = false;
  58865. this._shapeCounter = 0;
  58866. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58867. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58868. this._computeParticleColor = true;
  58869. this._computeParticleTexture = true;
  58870. this._computeParticleRotation = true;
  58871. this._computeParticleVertex = false;
  58872. this._computeBoundingBox = false;
  58873. this._depthSortParticles = true;
  58874. this._cam_axisZ = BABYLON.Vector3.Zero();
  58875. this._cam_axisY = BABYLON.Vector3.Zero();
  58876. this._cam_axisX = BABYLON.Vector3.Zero();
  58877. this._axisZ = BABYLON.Axis.Z;
  58878. this._camDir = BABYLON.Vector3.Zero();
  58879. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58880. this._rotMatrix = new BABYLON.Matrix();
  58881. this._invertMatrix = new BABYLON.Matrix();
  58882. this._rotated = BABYLON.Vector3.Zero();
  58883. this._quaternion = new BABYLON.Quaternion();
  58884. this._vertex = BABYLON.Vector3.Zero();
  58885. this._normal = BABYLON.Vector3.Zero();
  58886. this._yaw = 0.0;
  58887. this._pitch = 0.0;
  58888. this._roll = 0.0;
  58889. this._halfroll = 0.0;
  58890. this._halfpitch = 0.0;
  58891. this._halfyaw = 0.0;
  58892. this._sinRoll = 0.0;
  58893. this._cosRoll = 0.0;
  58894. this._sinPitch = 0.0;
  58895. this._cosPitch = 0.0;
  58896. this._sinYaw = 0.0;
  58897. this._cosYaw = 0.0;
  58898. this._mustUnrotateFixedNormals = false;
  58899. this._minimum = BABYLON.Vector3.Zero();
  58900. this._maximum = BABYLON.Vector3.Zero();
  58901. this._minBbox = BABYLON.Vector3.Zero();
  58902. this._maxBbox = BABYLON.Vector3.Zero();
  58903. this._particlesIntersect = false;
  58904. this._depthSortFunction = function (p1, p2) {
  58905. return (p2.sqDistance - p1.sqDistance);
  58906. };
  58907. this._needs32Bits = false;
  58908. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58909. this._scaledPivot = BABYLON.Vector3.Zero();
  58910. this._particleHasParent = false;
  58911. this.name = name;
  58912. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58913. this._camera = scene.activeCamera;
  58914. this._pickable = options ? options.isPickable : false;
  58915. this._depthSort = options ? options.enableDepthSort : false;
  58916. this._particlesIntersect = options ? options.particleIntersection : false;
  58917. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58918. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58919. if (options && options.updatable !== undefined) {
  58920. this._updatable = options.updatable;
  58921. }
  58922. else {
  58923. this._updatable = true;
  58924. }
  58925. if (this._pickable) {
  58926. this.pickedParticles = [];
  58927. }
  58928. if (this._depthSort) {
  58929. this.depthSortedParticles = [];
  58930. }
  58931. }
  58932. /**
  58933. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58934. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58935. * @returns the created mesh
  58936. */
  58937. SolidParticleSystem.prototype.buildMesh = function () {
  58938. if (this.nbParticles === 0) {
  58939. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58940. this.addShape(triangle, 1);
  58941. triangle.dispose();
  58942. }
  58943. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58944. this._positions32 = new Float32Array(this._positions);
  58945. this._uvs32 = new Float32Array(this._uvs);
  58946. this._colors32 = new Float32Array(this._colors);
  58947. if (this.recomputeNormals) {
  58948. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58949. }
  58950. this._normals32 = new Float32Array(this._normals);
  58951. this._fixedNormal32 = new Float32Array(this._normals);
  58952. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58953. this._unrotateFixedNormals();
  58954. }
  58955. var vertexData = new BABYLON.VertexData();
  58956. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58957. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58958. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58959. if (this._uvs32.length > 0) {
  58960. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58961. }
  58962. if (this._colors32.length > 0) {
  58963. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58964. }
  58965. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58966. vertexData.applyToMesh(mesh, this._updatable);
  58967. this.mesh = mesh;
  58968. this.mesh.isPickable = this._pickable;
  58969. // free memory
  58970. if (!this._depthSort) {
  58971. this._indices = null;
  58972. }
  58973. this._positions = null;
  58974. this._normals = null;
  58975. this._uvs = null;
  58976. this._colors = null;
  58977. if (!this._updatable) {
  58978. this.particles.length = 0;
  58979. }
  58980. return mesh;
  58981. };
  58982. /**
  58983. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58984. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58985. * Thus the particles generated from `digest()` have their property `position` set yet.
  58986. * @param mesh ( Mesh ) is the mesh to be digested
  58987. * @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
  58988. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58989. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58990. * @returns the current SPS
  58991. */
  58992. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58993. var size = (options && options.facetNb) || 1;
  58994. var number = (options && options.number) || 0;
  58995. var delta = (options && options.delta) || 0;
  58996. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58997. var meshInd = mesh.getIndices();
  58998. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58999. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59000. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59001. var f = 0; // facet counter
  59002. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  59003. // compute size from number
  59004. if (number) {
  59005. number = (number > totalFacets) ? totalFacets : number;
  59006. size = Math.round(totalFacets / number);
  59007. delta = 0;
  59008. }
  59009. else {
  59010. size = (size > totalFacets) ? totalFacets : size;
  59011. }
  59012. var facetPos = []; // submesh positions
  59013. var facetInd = []; // submesh indices
  59014. var facetUV = []; // submesh UV
  59015. var facetCol = []; // submesh colors
  59016. var barycenter = BABYLON.Vector3.Zero();
  59017. var sizeO = size;
  59018. while (f < totalFacets) {
  59019. size = sizeO + Math.floor((1 + delta) * Math.random());
  59020. if (f > totalFacets - size) {
  59021. size = totalFacets - f;
  59022. }
  59023. // reset temp arrays
  59024. facetPos.length = 0;
  59025. facetInd.length = 0;
  59026. facetUV.length = 0;
  59027. facetCol.length = 0;
  59028. // iterate over "size" facets
  59029. var fi = 0;
  59030. for (var j = f * 3; j < (f + size) * 3; j++) {
  59031. facetInd.push(fi);
  59032. var i = meshInd[j];
  59033. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  59034. if (meshUV) {
  59035. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  59036. }
  59037. if (meshCol) {
  59038. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  59039. }
  59040. fi++;
  59041. }
  59042. // create a model shape for each single particle
  59043. var idx = this.nbParticles;
  59044. var shape = this._posToShape(facetPos);
  59045. var shapeUV = this._uvsToShapeUV(facetUV);
  59046. // compute the barycenter of the shape
  59047. var v;
  59048. for (v = 0; v < shape.length; v++) {
  59049. barycenter.addInPlace(shape[v]);
  59050. }
  59051. barycenter.scaleInPlace(1 / shape.length);
  59052. // shift the shape from its barycenter to the origin
  59053. for (v = 0; v < shape.length; v++) {
  59054. shape[v].subtractInPlace(barycenter);
  59055. }
  59056. var bInfo;
  59057. if (this._particlesIntersect) {
  59058. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  59059. }
  59060. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  59061. // add the particle in the SPS
  59062. var currentPos = this._positions.length;
  59063. var currentInd = this._indices.length;
  59064. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  59065. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  59066. // initialize the particle position
  59067. this.particles[this.nbParticles].position.addInPlace(barycenter);
  59068. this._index += shape.length;
  59069. idx++;
  59070. this.nbParticles++;
  59071. this._shapeCounter++;
  59072. f += size;
  59073. }
  59074. return this;
  59075. };
  59076. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  59077. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  59078. var index = 0;
  59079. var idx = 0;
  59080. for (var p = 0; p < this.particles.length; p++) {
  59081. this._particle = this.particles[p];
  59082. this._shape = this._particle._model._shape;
  59083. if (this._particle.rotationQuaternion) {
  59084. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  59085. }
  59086. else {
  59087. this._yaw = this._particle.rotation.y;
  59088. this._pitch = this._particle.rotation.x;
  59089. this._roll = this._particle.rotation.z;
  59090. this._quaternionRotationYPR();
  59091. }
  59092. this._quaternionToRotationMatrix();
  59093. this._rotMatrix.invertToRef(this._invertMatrix);
  59094. for (var pt = 0; pt < this._shape.length; pt++) {
  59095. idx = index + pt * 3;
  59096. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  59097. this._fixedNormal32[idx] = this._normal.x;
  59098. this._fixedNormal32[idx + 1] = this._normal.y;
  59099. this._fixedNormal32[idx + 2] = this._normal.z;
  59100. }
  59101. index = idx + 3;
  59102. }
  59103. };
  59104. //reset copy
  59105. SolidParticleSystem.prototype._resetCopy = function () {
  59106. this._copy.position.x = 0;
  59107. this._copy.position.y = 0;
  59108. this._copy.position.z = 0;
  59109. this._copy.rotation.x = 0;
  59110. this._copy.rotation.y = 0;
  59111. this._copy.rotation.z = 0;
  59112. this._copy.rotationQuaternion = null;
  59113. this._copy.scaling.x = 1.0;
  59114. this._copy.scaling.y = 1.0;
  59115. this._copy.scaling.z = 1.0;
  59116. this._copy.uvs.x = 0;
  59117. this._copy.uvs.y = 0;
  59118. this._copy.uvs.z = 1.0;
  59119. this._copy.uvs.w = 1.0;
  59120. this._copy.color = null;
  59121. this._copy.translateFromPivot = false;
  59122. };
  59123. // _meshBuilder : inserts the shape model in the global SPS mesh
  59124. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  59125. var i;
  59126. var u = 0;
  59127. var c = 0;
  59128. var n = 0;
  59129. this._resetCopy();
  59130. if (options && options.positionFunction) { // call to custom positionFunction
  59131. options.positionFunction(this._copy, idx, idxInShape);
  59132. this._mustUnrotateFixedNormals = true;
  59133. }
  59134. if (this._copy.rotationQuaternion) {
  59135. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  59136. }
  59137. else {
  59138. this._yaw = this._copy.rotation.y;
  59139. this._pitch = this._copy.rotation.x;
  59140. this._roll = this._copy.rotation.z;
  59141. this._quaternionRotationYPR();
  59142. }
  59143. this._quaternionToRotationMatrix();
  59144. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  59145. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  59146. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  59147. if (this._copy.translateFromPivot) {
  59148. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  59149. }
  59150. else {
  59151. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  59152. }
  59153. for (i = 0; i < shape.length; i++) {
  59154. this._vertex.x = shape[i].x;
  59155. this._vertex.y = shape[i].y;
  59156. this._vertex.z = shape[i].z;
  59157. if (options && options.vertexFunction) {
  59158. options.vertexFunction(this._copy, this._vertex, i);
  59159. }
  59160. this._vertex.x *= this._copy.scaling.x;
  59161. this._vertex.y *= this._copy.scaling.y;
  59162. this._vertex.z *= this._copy.scaling.z;
  59163. this._vertex.x -= this._scaledPivot.x;
  59164. this._vertex.y -= this._scaledPivot.y;
  59165. this._vertex.z -= this._scaledPivot.z;
  59166. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  59167. this._rotated.addInPlace(this._pivotBackTranslation);
  59168. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  59169. if (meshUV) {
  59170. 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);
  59171. u += 2;
  59172. }
  59173. if (this._copy.color) {
  59174. this._color = this._copy.color;
  59175. }
  59176. else if (meshCol && meshCol[c] !== undefined) {
  59177. this._color.r = meshCol[c];
  59178. this._color.g = meshCol[c + 1];
  59179. this._color.b = meshCol[c + 2];
  59180. this._color.a = meshCol[c + 3];
  59181. }
  59182. else {
  59183. this._color.r = 1.0;
  59184. this._color.g = 1.0;
  59185. this._color.b = 1.0;
  59186. this._color.a = 1.0;
  59187. }
  59188. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  59189. c += 4;
  59190. if (!this.recomputeNormals && meshNor) {
  59191. this._normal.x = meshNor[n];
  59192. this._normal.y = meshNor[n + 1];
  59193. this._normal.z = meshNor[n + 2];
  59194. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  59195. normals.push(this._normal.x, this._normal.y, this._normal.z);
  59196. n += 3;
  59197. }
  59198. }
  59199. for (i = 0; i < meshInd.length; i++) {
  59200. var current_ind = p + meshInd[i];
  59201. indices.push(current_ind);
  59202. if (current_ind > 65535) {
  59203. this._needs32Bits = true;
  59204. }
  59205. }
  59206. if (this._pickable) {
  59207. var nbfaces = meshInd.length / 3;
  59208. for (i = 0; i < nbfaces; i++) {
  59209. this.pickedParticles.push({ idx: idx, faceId: i });
  59210. }
  59211. }
  59212. if (this._depthSort) {
  59213. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  59214. }
  59215. return this._copy;
  59216. };
  59217. // returns a shape array from positions array
  59218. SolidParticleSystem.prototype._posToShape = function (positions) {
  59219. var shape = [];
  59220. for (var i = 0; i < positions.length; i += 3) {
  59221. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  59222. }
  59223. return shape;
  59224. };
  59225. // returns a shapeUV array from a Vector4 uvs
  59226. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  59227. var shapeUV = [];
  59228. if (uvs) {
  59229. for (var i = 0; i < uvs.length; i++)
  59230. shapeUV.push(uvs[i]);
  59231. }
  59232. return shapeUV;
  59233. };
  59234. // adds a new particle object in the particles array
  59235. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  59236. if (bInfo === void 0) { bInfo = null; }
  59237. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  59238. this.particles.push(sp);
  59239. return sp;
  59240. };
  59241. /**
  59242. * Adds some particles to the SPS from the model shape. Returns the shape id.
  59243. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  59244. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  59245. * @param nb (positive integer) the number of particles to be created from this model
  59246. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  59247. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  59248. * @returns the number of shapes in the system
  59249. */
  59250. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  59251. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59252. var meshInd = mesh.getIndices();
  59253. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59254. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59255. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59256. var bbInfo;
  59257. if (this._particlesIntersect) {
  59258. bbInfo = mesh.getBoundingInfo();
  59259. }
  59260. var shape = this._posToShape(meshPos);
  59261. var shapeUV = this._uvsToShapeUV(meshUV);
  59262. var posfunc = options ? options.positionFunction : null;
  59263. var vtxfunc = options ? options.vertexFunction : null;
  59264. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  59265. // particles
  59266. var sp;
  59267. var currentCopy;
  59268. var idx = this.nbParticles;
  59269. for (var i = 0; i < nb; i++) {
  59270. var currentPos = this._positions.length;
  59271. var currentInd = this._indices.length;
  59272. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  59273. if (this._updatable) {
  59274. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  59275. sp.position.copyFrom(currentCopy.position);
  59276. sp.rotation.copyFrom(currentCopy.rotation);
  59277. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  59278. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  59279. }
  59280. if (currentCopy.color && sp.color) {
  59281. sp.color.copyFrom(currentCopy.color);
  59282. }
  59283. sp.scaling.copyFrom(currentCopy.scaling);
  59284. sp.uvs.copyFrom(currentCopy.uvs);
  59285. }
  59286. this._index += shape.length;
  59287. idx++;
  59288. }
  59289. this.nbParticles += nb;
  59290. this._shapeCounter++;
  59291. return this._shapeCounter - 1;
  59292. };
  59293. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  59294. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  59295. this._resetCopy();
  59296. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  59297. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  59298. }
  59299. if (this._copy.rotationQuaternion) {
  59300. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  59301. }
  59302. else {
  59303. this._yaw = this._copy.rotation.y;
  59304. this._pitch = this._copy.rotation.x;
  59305. this._roll = this._copy.rotation.z;
  59306. this._quaternionRotationYPR();
  59307. }
  59308. this._quaternionToRotationMatrix();
  59309. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59310. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59311. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59312. if (this._copy.translateFromPivot) {
  59313. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  59314. }
  59315. else {
  59316. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  59317. }
  59318. this._shape = particle._model._shape;
  59319. for (var pt = 0; pt < this._shape.length; pt++) {
  59320. this._vertex.x = this._shape[pt].x;
  59321. this._vertex.y = this._shape[pt].y;
  59322. this._vertex.z = this._shape[pt].z;
  59323. if (particle._model._vertexFunction) {
  59324. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  59325. }
  59326. this._vertex.x *= this._copy.scaling.x;
  59327. this._vertex.y *= this._copy.scaling.y;
  59328. this._vertex.z *= this._copy.scaling.z;
  59329. this._vertex.x -= this._scaledPivot.x;
  59330. this._vertex.y -= this._scaledPivot.y;
  59331. this._vertex.z -= this._scaledPivot.z;
  59332. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  59333. this._rotated.addInPlace(this._pivotBackTranslation);
  59334. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  59335. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  59336. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  59337. }
  59338. particle.position.x = 0.0;
  59339. particle.position.y = 0.0;
  59340. particle.position.z = 0.0;
  59341. particle.rotation.x = 0.0;
  59342. particle.rotation.y = 0.0;
  59343. particle.rotation.z = 0.0;
  59344. particle.rotationQuaternion = null;
  59345. particle.scaling.x = 1.0;
  59346. particle.scaling.y = 1.0;
  59347. particle.scaling.z = 1.0;
  59348. particle.uvs.x = 0.0;
  59349. particle.uvs.y = 0.0;
  59350. particle.uvs.z = 1.0;
  59351. particle.uvs.w = 1.0;
  59352. particle.pivot.x = 0.0;
  59353. particle.pivot.y = 0.0;
  59354. particle.pivot.z = 0.0;
  59355. particle.translateFromPivot = false;
  59356. particle.parentId = null;
  59357. };
  59358. /**
  59359. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  59360. * @returns the SPS.
  59361. */
  59362. SolidParticleSystem.prototype.rebuildMesh = function () {
  59363. for (var p = 0; p < this.particles.length; p++) {
  59364. this._rebuildParticle(this.particles[p]);
  59365. }
  59366. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59367. return this;
  59368. };
  59369. /**
  59370. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  59371. * This method calls `updateParticle()` for each particle of the SPS.
  59372. * For an animated SPS, it is usually called within the render loop.
  59373. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  59374. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  59375. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  59376. * @returns the SPS.
  59377. */
  59378. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  59379. if (start === void 0) { start = 0; }
  59380. if (end === void 0) { end = this.nbParticles - 1; }
  59381. if (update === void 0) { update = true; }
  59382. if (!this._updatable) {
  59383. return this;
  59384. }
  59385. // custom beforeUpdate
  59386. this.beforeUpdateParticles(start, end, update);
  59387. this._cam_axisX.x = 1.0;
  59388. this._cam_axisX.y = 0.0;
  59389. this._cam_axisX.z = 0.0;
  59390. this._cam_axisY.x = 0.0;
  59391. this._cam_axisY.y = 1.0;
  59392. this._cam_axisY.z = 0.0;
  59393. this._cam_axisZ.x = 0.0;
  59394. this._cam_axisZ.y = 0.0;
  59395. this._cam_axisZ.z = 1.0;
  59396. // cases when the World Matrix is to be computed first
  59397. if (this.billboard || this._depthSort) {
  59398. this.mesh.computeWorldMatrix(true);
  59399. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  59400. }
  59401. // if the particles will always face the camera
  59402. if (this.billboard) {
  59403. // compute the camera position and un-rotate it by the current mesh rotation
  59404. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  59405. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  59406. this._cam_axisZ.normalize();
  59407. // same for camera up vector extracted from the cam view matrix
  59408. var view = this._camera.getViewMatrix(true);
  59409. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  59410. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  59411. this._cam_axisY.normalize();
  59412. this._cam_axisX.normalize();
  59413. }
  59414. // if depthSort, compute the camera global position in the mesh local system
  59415. if (this._depthSort) {
  59416. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  59417. }
  59418. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  59419. var idx = 0; // current position index in the global array positions32
  59420. var index = 0; // position start index in the global array positions32 of the current particle
  59421. var colidx = 0; // current color index in the global array colors32
  59422. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  59423. var uvidx = 0; // current uv index in the global array uvs32
  59424. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  59425. var pt = 0; // current index in the particle model shape
  59426. if (this.mesh.isFacetDataEnabled) {
  59427. this._computeBoundingBox = true;
  59428. }
  59429. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  59430. if (this._computeBoundingBox) {
  59431. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  59432. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  59433. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  59434. }
  59435. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  59436. if (this.mesh._boundingInfo) {
  59437. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  59438. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  59439. }
  59440. }
  59441. }
  59442. // particle loop
  59443. index = this.particles[start]._pos;
  59444. var vpos = (index / 3) | 0;
  59445. colorIndex = vpos * 4;
  59446. uvIndex = vpos * 2;
  59447. for (var p = start; p <= end; p++) {
  59448. this._particle = this.particles[p];
  59449. this._shape = this._particle._model._shape;
  59450. this._shapeUV = this._particle._model._shapeUV;
  59451. // call to custom user function to update the particle properties
  59452. this.updateParticle(this._particle);
  59453. // camera-particle distance for depth sorting
  59454. if (this._depthSort && this._depthSortParticles) {
  59455. var dsp = this.depthSortedParticles[p];
  59456. dsp.ind = this._particle._ind;
  59457. dsp.indicesLength = this._particle._model._indicesLength;
  59458. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  59459. }
  59460. // skip the computations for inactive or already invisible particles
  59461. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  59462. // increment indexes for the next particle
  59463. pt = this._shape.length;
  59464. index += pt * 3;
  59465. colorIndex += pt * 4;
  59466. uvIndex += pt * 2;
  59467. continue;
  59468. }
  59469. if (this._particle.isVisible) {
  59470. this._particle._stillInvisible = false; // un-mark permanent invisibility
  59471. this._particleHasParent = (this._particle.parentId !== null);
  59472. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59473. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59474. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59475. // particle rotation matrix
  59476. if (this.billboard) {
  59477. this._particle.rotation.x = 0.0;
  59478. this._particle.rotation.y = 0.0;
  59479. }
  59480. if (this._computeParticleRotation || this.billboard) {
  59481. if (this._particle.rotationQuaternion) {
  59482. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  59483. }
  59484. else {
  59485. this._yaw = this._particle.rotation.y;
  59486. this._pitch = this._particle.rotation.x;
  59487. this._roll = this._particle.rotation.z;
  59488. this._quaternionRotationYPR();
  59489. }
  59490. this._quaternionToRotationMatrix();
  59491. }
  59492. if (this._particleHasParent) {
  59493. this._parent = this.particles[this._particle.parentId];
  59494. 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];
  59495. 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];
  59496. 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];
  59497. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  59498. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  59499. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  59500. if (this._computeParticleRotation || this.billboard) {
  59501. 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];
  59502. 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];
  59503. 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];
  59504. 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];
  59505. 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];
  59506. 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];
  59507. 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];
  59508. 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];
  59509. 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];
  59510. }
  59511. }
  59512. else {
  59513. this._particle._globalPosition.x = this._particle.position.x;
  59514. this._particle._globalPosition.y = this._particle.position.y;
  59515. this._particle._globalPosition.z = this._particle.position.z;
  59516. if (this._computeParticleRotation || this.billboard) {
  59517. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  59518. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  59519. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  59520. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  59521. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  59522. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  59523. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  59524. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  59525. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  59526. }
  59527. }
  59528. if (this._particle.translateFromPivot) {
  59529. this._pivotBackTranslation.x = 0.0;
  59530. this._pivotBackTranslation.y = 0.0;
  59531. this._pivotBackTranslation.z = 0.0;
  59532. }
  59533. else {
  59534. this._pivotBackTranslation.x = this._scaledPivot.x;
  59535. this._pivotBackTranslation.y = this._scaledPivot.y;
  59536. this._pivotBackTranslation.z = this._scaledPivot.z;
  59537. }
  59538. // particle vertex loop
  59539. for (pt = 0; pt < this._shape.length; pt++) {
  59540. idx = index + pt * 3;
  59541. colidx = colorIndex + pt * 4;
  59542. uvidx = uvIndex + pt * 2;
  59543. this._vertex.x = this._shape[pt].x;
  59544. this._vertex.y = this._shape[pt].y;
  59545. this._vertex.z = this._shape[pt].z;
  59546. if (this._computeParticleVertex) {
  59547. this.updateParticleVertex(this._particle, this._vertex, pt);
  59548. }
  59549. // positions
  59550. this._vertex.x *= this._particle.scaling.x;
  59551. this._vertex.y *= this._particle.scaling.y;
  59552. this._vertex.z *= this._particle.scaling.z;
  59553. this._vertex.x -= this._scaledPivot.x;
  59554. this._vertex.y -= this._scaledPivot.y;
  59555. this._vertex.z -= this._scaledPivot.z;
  59556. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59557. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59558. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59559. this._rotated.x += this._pivotBackTranslation.x;
  59560. this._rotated.y += this._pivotBackTranslation.y;
  59561. this._rotated.z += this._pivotBackTranslation.z;
  59562. 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;
  59563. 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;
  59564. 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;
  59565. if (this._computeBoundingBox) {
  59566. if (this._positions32[idx] < this._minimum.x) {
  59567. this._minimum.x = this._positions32[idx];
  59568. }
  59569. if (this._positions32[idx] > this._maximum.x) {
  59570. this._maximum.x = this._positions32[idx];
  59571. }
  59572. if (this._positions32[idx + 1] < this._minimum.y) {
  59573. this._minimum.y = this._positions32[idx + 1];
  59574. }
  59575. if (this._positions32[idx + 1] > this._maximum.y) {
  59576. this._maximum.y = this._positions32[idx + 1];
  59577. }
  59578. if (this._positions32[idx + 2] < this._minimum.z) {
  59579. this._minimum.z = this._positions32[idx + 2];
  59580. }
  59581. if (this._positions32[idx + 2] > this._maximum.z) {
  59582. this._maximum.z = this._positions32[idx + 2];
  59583. }
  59584. }
  59585. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59586. if (!this._computeParticleVertex) {
  59587. this._normal.x = this._fixedNormal32[idx];
  59588. this._normal.y = this._fixedNormal32[idx + 1];
  59589. this._normal.z = this._fixedNormal32[idx + 2];
  59590. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59591. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59592. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59593. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59594. 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;
  59595. 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;
  59596. }
  59597. if (this._computeParticleColor && this._particle.color) {
  59598. this._colors32[colidx] = this._particle.color.r;
  59599. this._colors32[colidx + 1] = this._particle.color.g;
  59600. this._colors32[colidx + 2] = this._particle.color.b;
  59601. this._colors32[colidx + 3] = this._particle.color.a;
  59602. }
  59603. if (this._computeParticleTexture) {
  59604. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59605. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59606. }
  59607. }
  59608. }
  59609. // particle just set invisible : scaled to zero and positioned at the origin
  59610. else {
  59611. this._particle._stillInvisible = true; // mark the particle as invisible
  59612. for (pt = 0; pt < this._shape.length; pt++) {
  59613. idx = index + pt * 3;
  59614. colidx = colorIndex + pt * 4;
  59615. uvidx = uvIndex + pt * 2;
  59616. this._positions32[idx] = 0.0;
  59617. this._positions32[idx + 1] = 0.0;
  59618. this._positions32[idx + 2] = 0.0;
  59619. this._normals32[idx] = 0.0;
  59620. this._normals32[idx + 1] = 0.0;
  59621. this._normals32[idx + 2] = 0.0;
  59622. if (this._computeParticleColor && this._particle.color) {
  59623. this._colors32[colidx] = this._particle.color.r;
  59624. this._colors32[colidx + 1] = this._particle.color.g;
  59625. this._colors32[colidx + 2] = this._particle.color.b;
  59626. this._colors32[colidx + 3] = this._particle.color.a;
  59627. }
  59628. if (this._computeParticleTexture) {
  59629. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59630. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59631. }
  59632. }
  59633. }
  59634. // if the particle intersections must be computed : update the bbInfo
  59635. if (this._particlesIntersect) {
  59636. var bInfo = this._particle._boundingInfo;
  59637. var bBox = bInfo.boundingBox;
  59638. var bSphere = bInfo.boundingSphere;
  59639. if (!this._bSphereOnly) {
  59640. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59641. for (var b = 0; b < bBox.vectors.length; b++) {
  59642. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59643. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59644. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59645. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59646. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59647. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59648. 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;
  59649. 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;
  59650. 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;
  59651. }
  59652. bBox._update(this.mesh._worldMatrix);
  59653. }
  59654. // place and scale the particle bouding sphere in the SPS local system, then update it
  59655. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59656. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59657. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59658. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59659. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59660. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59661. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59662. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59663. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59664. 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));
  59665. bSphere._update(this.mesh._worldMatrix);
  59666. }
  59667. // increment indexes for the next particle
  59668. index = idx + 3;
  59669. colorIndex = colidx + 4;
  59670. uvIndex = uvidx + 2;
  59671. }
  59672. // if the VBO must be updated
  59673. if (update) {
  59674. if (this._computeParticleColor) {
  59675. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59676. }
  59677. if (this._computeParticleTexture) {
  59678. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59679. }
  59680. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59681. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59682. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59683. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59684. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59685. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59686. for (var i = 0; i < this._normals32.length; i++) {
  59687. this._fixedNormal32[i] = this._normals32[i];
  59688. }
  59689. }
  59690. if (!this.mesh.areNormalsFrozen) {
  59691. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59692. }
  59693. }
  59694. if (this._depthSort && this._depthSortParticles) {
  59695. this.depthSortedParticles.sort(this._depthSortFunction);
  59696. var dspl = this.depthSortedParticles.length;
  59697. var sorted = 0;
  59698. var lind = 0;
  59699. var sind = 0;
  59700. var sid = 0;
  59701. for (sorted = 0; sorted < dspl; sorted++) {
  59702. lind = this.depthSortedParticles[sorted].indicesLength;
  59703. sind = this.depthSortedParticles[sorted].ind;
  59704. for (var i = 0; i < lind; i++) {
  59705. this._indices32[sid] = this._indices[sind + i];
  59706. sid++;
  59707. }
  59708. }
  59709. this.mesh.updateIndices(this._indices32);
  59710. }
  59711. }
  59712. if (this._computeBoundingBox) {
  59713. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59714. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59715. }
  59716. this.afterUpdateParticles(start, end, update);
  59717. return this;
  59718. };
  59719. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59720. this._halfroll = this._roll * 0.5;
  59721. this._halfpitch = this._pitch * 0.5;
  59722. this._halfyaw = this._yaw * 0.5;
  59723. this._sinRoll = Math.sin(this._halfroll);
  59724. this._cosRoll = Math.cos(this._halfroll);
  59725. this._sinPitch = Math.sin(this._halfpitch);
  59726. this._cosPitch = Math.cos(this._halfpitch);
  59727. this._sinYaw = Math.sin(this._halfyaw);
  59728. this._cosYaw = Math.cos(this._halfyaw);
  59729. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59730. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59731. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59732. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59733. };
  59734. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59735. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59736. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59737. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59738. this._rotMatrix.m[3] = 0;
  59739. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59740. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59741. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59742. this._rotMatrix.m[7] = 0;
  59743. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59744. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59745. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59746. this._rotMatrix.m[11] = 0;
  59747. this._rotMatrix.m[12] = 0;
  59748. this._rotMatrix.m[13] = 0;
  59749. this._rotMatrix.m[14] = 0;
  59750. this._rotMatrix.m[15] = 1.0;
  59751. };
  59752. /**
  59753. * Disposes the SPS.
  59754. */
  59755. SolidParticleSystem.prototype.dispose = function () {
  59756. this.mesh.dispose();
  59757. this.vars = null;
  59758. // drop references to internal big arrays for the GC
  59759. this._positions = null;
  59760. this._indices = null;
  59761. this._normals = null;
  59762. this._uvs = null;
  59763. this._colors = null;
  59764. this._indices32 = null;
  59765. this._positions32 = null;
  59766. this._normals32 = null;
  59767. this._fixedNormal32 = null;
  59768. this._uvs32 = null;
  59769. this._colors32 = null;
  59770. this.pickedParticles = null;
  59771. };
  59772. /**
  59773. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59774. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59775. * @returns the SPS.
  59776. */
  59777. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59778. if (!this._isVisibilityBoxLocked) {
  59779. this.mesh.refreshBoundingInfo();
  59780. }
  59781. return this;
  59782. };
  59783. /**
  59784. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59785. * @param size the size (float) of the visibility box
  59786. * note : this doesn't lock the SPS mesh bounding box.
  59787. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59788. */
  59789. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59790. var vis = size / 2;
  59791. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59792. };
  59793. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59794. /**
  59795. * Gets whether the SPS as always visible or not
  59796. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59797. */
  59798. get: function () {
  59799. return this._alwaysVisible;
  59800. },
  59801. /**
  59802. * Sets the SPS as always visible or not
  59803. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59804. */
  59805. set: function (val) {
  59806. this._alwaysVisible = val;
  59807. this.mesh.alwaysSelectAsActiveMesh = val;
  59808. },
  59809. enumerable: true,
  59810. configurable: true
  59811. });
  59812. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59813. /**
  59814. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59815. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59816. */
  59817. get: function () {
  59818. return this._isVisibilityBoxLocked;
  59819. },
  59820. /**
  59821. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59822. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59823. */
  59824. set: function (val) {
  59825. this._isVisibilityBoxLocked = val;
  59826. var boundingInfo = this.mesh.getBoundingInfo();
  59827. boundingInfo.isLocked = val;
  59828. },
  59829. enumerable: true,
  59830. configurable: true
  59831. });
  59832. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59833. /**
  59834. * Gets if `setParticles()` computes the particle rotations or not.
  59835. * Default value : true. The SPS is faster when it's set to false.
  59836. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59837. */
  59838. get: function () {
  59839. return this._computeParticleRotation;
  59840. },
  59841. /**
  59842. * Tells to `setParticles()` to compute the particle rotations or not.
  59843. * Default value : true. The SPS is faster when it's set to false.
  59844. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59845. */
  59846. set: function (val) {
  59847. this._computeParticleRotation = val;
  59848. },
  59849. enumerable: true,
  59850. configurable: true
  59851. });
  59852. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59853. /**
  59854. * Gets if `setParticles()` computes the particle colors or not.
  59855. * Default value : true. The SPS is faster when it's set to false.
  59856. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59857. */
  59858. get: function () {
  59859. return this._computeParticleColor;
  59860. },
  59861. /**
  59862. * Tells to `setParticles()` to compute the particle colors or not.
  59863. * Default value : true. The SPS is faster when it's set to false.
  59864. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59865. */
  59866. set: function (val) {
  59867. this._computeParticleColor = val;
  59868. },
  59869. enumerable: true,
  59870. configurable: true
  59871. });
  59872. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59873. /**
  59874. * Gets if `setParticles()` computes the particle textures or not.
  59875. * Default value : true. The SPS is faster when it's set to false.
  59876. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59877. */
  59878. get: function () {
  59879. return this._computeParticleTexture;
  59880. },
  59881. set: function (val) {
  59882. this._computeParticleTexture = val;
  59883. },
  59884. enumerable: true,
  59885. configurable: true
  59886. });
  59887. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59888. /**
  59889. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59890. * Default value : false. The SPS is faster when it's set to false.
  59891. * Note : the particle custom vertex positions aren't stored values.
  59892. */
  59893. get: function () {
  59894. return this._computeParticleVertex;
  59895. },
  59896. /**
  59897. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59898. * Default value : false. The SPS is faster when it's set to false.
  59899. * Note : the particle custom vertex positions aren't stored values.
  59900. */
  59901. set: function (val) {
  59902. this._computeParticleVertex = val;
  59903. },
  59904. enumerable: true,
  59905. configurable: true
  59906. });
  59907. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59908. /**
  59909. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59910. */
  59911. get: function () {
  59912. return this._computeBoundingBox;
  59913. },
  59914. /**
  59915. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59916. */
  59917. set: function (val) {
  59918. this._computeBoundingBox = val;
  59919. },
  59920. enumerable: true,
  59921. configurable: true
  59922. });
  59923. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59924. /**
  59925. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59926. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59927. * Default : `true`
  59928. */
  59929. get: function () {
  59930. return this._depthSortParticles;
  59931. },
  59932. /**
  59933. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59934. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59935. * Default : `true`
  59936. */
  59937. set: function (val) {
  59938. this._depthSortParticles = val;
  59939. },
  59940. enumerable: true,
  59941. configurable: true
  59942. });
  59943. // =======================================================================
  59944. // Particle behavior logic
  59945. // these following methods may be overwritten by the user to fit his needs
  59946. /**
  59947. * This function does nothing. It may be overwritten to set all the particle first values.
  59948. * The SPS doesn't call this function, you may have to call it by your own.
  59949. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59950. */
  59951. SolidParticleSystem.prototype.initParticles = function () {
  59952. };
  59953. /**
  59954. * This function does nothing. It may be overwritten to recycle a particle.
  59955. * The SPS doesn't call this function, you may have to call it by your own.
  59956. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59957. * @param particle The particle to recycle
  59958. * @returns the recycled particle
  59959. */
  59960. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59961. return particle;
  59962. };
  59963. /**
  59964. * Updates a particle : this function should be overwritten by the user.
  59965. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59966. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59967. * @example : just set a particle position or velocity and recycle conditions
  59968. * @param particle The particle to update
  59969. * @returns the updated particle
  59970. */
  59971. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59972. return particle;
  59973. };
  59974. /**
  59975. * Updates a vertex of a particle : it can be overwritten by the user.
  59976. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59977. * @param particle the current particle
  59978. * @param vertex the current index of the current particle
  59979. * @param pt the index of the current vertex in the particle shape
  59980. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59981. * @example : just set a vertex particle position
  59982. * @returns the updated vertex
  59983. */
  59984. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59985. return vertex;
  59986. };
  59987. /**
  59988. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59989. * This does nothing and may be overwritten by the user.
  59990. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59991. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59992. * @param update the boolean update value actually passed to setParticles()
  59993. */
  59994. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59995. };
  59996. /**
  59997. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59998. * This will be passed three parameters.
  59999. * This does nothing and may be overwritten by the user.
  60000. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  60001. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  60002. * @param update the boolean update value actually passed to setParticles()
  60003. */
  60004. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  60005. };
  60006. return SolidParticleSystem;
  60007. }());
  60008. BABYLON.SolidParticleSystem = SolidParticleSystem;
  60009. })(BABYLON || (BABYLON = {}));
  60010. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  60011. var BABYLON;
  60012. (function (BABYLON) {
  60013. var ShaderMaterial = /** @class */ (function (_super) {
  60014. __extends(ShaderMaterial, _super);
  60015. function ShaderMaterial(name, scene, shaderPath, options) {
  60016. var _this = _super.call(this, name, scene) || this;
  60017. _this._textures = {};
  60018. _this._textureArrays = {};
  60019. _this._floats = {};
  60020. _this._ints = {};
  60021. _this._floatsArrays = {};
  60022. _this._colors3 = {};
  60023. _this._colors3Arrays = {};
  60024. _this._colors4 = {};
  60025. _this._vectors2 = {};
  60026. _this._vectors3 = {};
  60027. _this._vectors4 = {};
  60028. _this._matrices = {};
  60029. _this._matrices3x3 = {};
  60030. _this._matrices2x2 = {};
  60031. _this._vectors2Arrays = {};
  60032. _this._vectors3Arrays = {};
  60033. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  60034. _this._shaderPath = shaderPath;
  60035. options.needAlphaBlending = options.needAlphaBlending || false;
  60036. options.needAlphaTesting = options.needAlphaTesting || false;
  60037. options.attributes = options.attributes || ["position", "normal", "uv"];
  60038. options.uniforms = options.uniforms || ["worldViewProjection"];
  60039. options.uniformBuffers = options.uniformBuffers || [];
  60040. options.samplers = options.samplers || [];
  60041. options.defines = options.defines || [];
  60042. _this._options = options;
  60043. return _this;
  60044. }
  60045. ShaderMaterial.prototype.getClassName = function () {
  60046. return "ShaderMaterial";
  60047. };
  60048. ShaderMaterial.prototype.needAlphaBlending = function () {
  60049. return this._options.needAlphaBlending;
  60050. };
  60051. ShaderMaterial.prototype.needAlphaTesting = function () {
  60052. return this._options.needAlphaTesting;
  60053. };
  60054. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  60055. if (this._options.uniforms.indexOf(uniformName) === -1) {
  60056. this._options.uniforms.push(uniformName);
  60057. }
  60058. };
  60059. ShaderMaterial.prototype.setTexture = function (name, texture) {
  60060. if (this._options.samplers.indexOf(name) === -1) {
  60061. this._options.samplers.push(name);
  60062. }
  60063. this._textures[name] = texture;
  60064. return this;
  60065. };
  60066. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  60067. if (this._options.samplers.indexOf(name) === -1) {
  60068. this._options.samplers.push(name);
  60069. }
  60070. this._checkUniform(name);
  60071. this._textureArrays[name] = textures;
  60072. return this;
  60073. };
  60074. ShaderMaterial.prototype.setFloat = function (name, value) {
  60075. this._checkUniform(name);
  60076. this._floats[name] = value;
  60077. return this;
  60078. };
  60079. ShaderMaterial.prototype.setInt = function (name, value) {
  60080. this._checkUniform(name);
  60081. this._ints[name] = value;
  60082. return this;
  60083. };
  60084. ShaderMaterial.prototype.setFloats = function (name, value) {
  60085. this._checkUniform(name);
  60086. this._floatsArrays[name] = value;
  60087. return this;
  60088. };
  60089. ShaderMaterial.prototype.setColor3 = function (name, value) {
  60090. this._checkUniform(name);
  60091. this._colors3[name] = value;
  60092. return this;
  60093. };
  60094. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  60095. this._checkUniform(name);
  60096. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  60097. color.toArray(arr, arr.length);
  60098. return arr;
  60099. }, []);
  60100. return this;
  60101. };
  60102. ShaderMaterial.prototype.setColor4 = function (name, value) {
  60103. this._checkUniform(name);
  60104. this._colors4[name] = value;
  60105. return this;
  60106. };
  60107. ShaderMaterial.prototype.setVector2 = function (name, value) {
  60108. this._checkUniform(name);
  60109. this._vectors2[name] = value;
  60110. return this;
  60111. };
  60112. ShaderMaterial.prototype.setVector3 = function (name, value) {
  60113. this._checkUniform(name);
  60114. this._vectors3[name] = value;
  60115. return this;
  60116. };
  60117. ShaderMaterial.prototype.setVector4 = function (name, value) {
  60118. this._checkUniform(name);
  60119. this._vectors4[name] = value;
  60120. return this;
  60121. };
  60122. ShaderMaterial.prototype.setMatrix = function (name, value) {
  60123. this._checkUniform(name);
  60124. this._matrices[name] = value;
  60125. return this;
  60126. };
  60127. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  60128. this._checkUniform(name);
  60129. this._matrices3x3[name] = value;
  60130. return this;
  60131. };
  60132. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  60133. this._checkUniform(name);
  60134. this._matrices2x2[name] = value;
  60135. return this;
  60136. };
  60137. ShaderMaterial.prototype.setArray2 = function (name, value) {
  60138. this._checkUniform(name);
  60139. this._vectors2Arrays[name] = value;
  60140. return this;
  60141. };
  60142. ShaderMaterial.prototype.setArray3 = function (name, value) {
  60143. this._checkUniform(name);
  60144. this._vectors3Arrays[name] = value;
  60145. return this;
  60146. };
  60147. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  60148. if (!mesh) {
  60149. return true;
  60150. }
  60151. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  60152. return false;
  60153. }
  60154. return false;
  60155. };
  60156. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  60157. var scene = this.getScene();
  60158. var engine = scene.getEngine();
  60159. if (!this.checkReadyOnEveryCall) {
  60160. if (this._renderId === scene.getRenderId()) {
  60161. if (this._checkCache(scene, mesh, useInstances)) {
  60162. return true;
  60163. }
  60164. }
  60165. }
  60166. // Instances
  60167. var defines = [];
  60168. var attribs = [];
  60169. var fallbacks = new BABYLON.EffectFallbacks();
  60170. if (useInstances) {
  60171. defines.push("#define INSTANCES");
  60172. }
  60173. for (var index = 0; index < this._options.defines.length; index++) {
  60174. defines.push(this._options.defines[index]);
  60175. }
  60176. for (var index = 0; index < this._options.attributes.length; index++) {
  60177. attribs.push(this._options.attributes[index]);
  60178. }
  60179. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  60180. attribs.push(BABYLON.VertexBuffer.ColorKind);
  60181. defines.push("#define VERTEXCOLOR");
  60182. }
  60183. // Bones
  60184. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60185. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60186. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60187. if (mesh.numBoneInfluencers > 4) {
  60188. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60189. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60190. }
  60191. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60192. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60193. fallbacks.addCPUSkinningFallback(0, mesh);
  60194. if (this._options.uniforms.indexOf("mBones") === -1) {
  60195. this._options.uniforms.push("mBones");
  60196. }
  60197. }
  60198. else {
  60199. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60200. }
  60201. // Textures
  60202. for (var name in this._textures) {
  60203. if (!this._textures[name].isReady()) {
  60204. return false;
  60205. }
  60206. }
  60207. // Alpha test
  60208. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  60209. defines.push("#define ALPHATEST");
  60210. }
  60211. var previousEffect = this._effect;
  60212. var join = defines.join("\n");
  60213. this._effect = engine.createEffect(this._shaderPath, {
  60214. attributes: attribs,
  60215. uniformsNames: this._options.uniforms,
  60216. uniformBuffersNames: this._options.uniformBuffers,
  60217. samplers: this._options.samplers,
  60218. defines: join,
  60219. fallbacks: fallbacks,
  60220. onCompiled: this.onCompiled,
  60221. onError: this.onError
  60222. }, engine);
  60223. if (!this._effect.isReady()) {
  60224. return false;
  60225. }
  60226. if (previousEffect !== this._effect) {
  60227. scene.resetCachedMaterial();
  60228. }
  60229. this._renderId = scene.getRenderId();
  60230. return true;
  60231. };
  60232. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  60233. var scene = this.getScene();
  60234. if (!this._effect) {
  60235. return;
  60236. }
  60237. if (this._options.uniforms.indexOf("world") !== -1) {
  60238. this._effect.setMatrix("world", world);
  60239. }
  60240. if (this._options.uniforms.indexOf("worldView") !== -1) {
  60241. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  60242. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  60243. }
  60244. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  60245. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  60246. }
  60247. };
  60248. ShaderMaterial.prototype.bind = function (world, mesh) {
  60249. // Std values
  60250. this.bindOnlyWorldMatrix(world);
  60251. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  60252. if (this._options.uniforms.indexOf("view") !== -1) {
  60253. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  60254. }
  60255. if (this._options.uniforms.indexOf("projection") !== -1) {
  60256. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  60257. }
  60258. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  60259. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  60260. }
  60261. // Bones
  60262. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  60263. var name;
  60264. // Texture
  60265. for (name in this._textures) {
  60266. this._effect.setTexture(name, this._textures[name]);
  60267. }
  60268. // Texture arrays
  60269. for (name in this._textureArrays) {
  60270. this._effect.setTextureArray(name, this._textureArrays[name]);
  60271. }
  60272. // Int
  60273. for (name in this._ints) {
  60274. this._effect.setInt(name, this._ints[name]);
  60275. }
  60276. // Float
  60277. for (name in this._floats) {
  60278. this._effect.setFloat(name, this._floats[name]);
  60279. }
  60280. // Floats
  60281. for (name in this._floatsArrays) {
  60282. this._effect.setArray(name, this._floatsArrays[name]);
  60283. }
  60284. // Color3
  60285. for (name in this._colors3) {
  60286. this._effect.setColor3(name, this._colors3[name]);
  60287. }
  60288. for (name in this._colors3Arrays) {
  60289. this._effect.setArray3(name, this._colors3Arrays[name]);
  60290. }
  60291. // Color4
  60292. for (name in this._colors4) {
  60293. var color = this._colors4[name];
  60294. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60295. }
  60296. // Vector2
  60297. for (name in this._vectors2) {
  60298. this._effect.setVector2(name, this._vectors2[name]);
  60299. }
  60300. // Vector3
  60301. for (name in this._vectors3) {
  60302. this._effect.setVector3(name, this._vectors3[name]);
  60303. }
  60304. // Vector4
  60305. for (name in this._vectors4) {
  60306. this._effect.setVector4(name, this._vectors4[name]);
  60307. }
  60308. // Matrix
  60309. for (name in this._matrices) {
  60310. this._effect.setMatrix(name, this._matrices[name]);
  60311. }
  60312. // Matrix 3x3
  60313. for (name in this._matrices3x3) {
  60314. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  60315. }
  60316. // Matrix 2x2
  60317. for (name in this._matrices2x2) {
  60318. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  60319. }
  60320. // Vector2Array
  60321. for (name in this._vectors2Arrays) {
  60322. this._effect.setArray2(name, this._vectors2Arrays[name]);
  60323. }
  60324. // Vector3Array
  60325. for (name in this._vectors3Arrays) {
  60326. this._effect.setArray3(name, this._vectors3Arrays[name]);
  60327. }
  60328. }
  60329. this._afterBind(mesh);
  60330. };
  60331. ShaderMaterial.prototype.getActiveTextures = function () {
  60332. var activeTextures = _super.prototype.getActiveTextures.call(this);
  60333. for (var name in this._textures) {
  60334. activeTextures.push(this._textures[name]);
  60335. }
  60336. for (var name in this._textureArrays) {
  60337. var array = this._textureArrays[name];
  60338. for (var index = 0; index < array.length; index++) {
  60339. activeTextures.push(array[index]);
  60340. }
  60341. }
  60342. return activeTextures;
  60343. };
  60344. ShaderMaterial.prototype.hasTexture = function (texture) {
  60345. if (_super.prototype.hasTexture.call(this, texture)) {
  60346. return true;
  60347. }
  60348. for (var name in this._textures) {
  60349. if (this._textures[name] === texture) {
  60350. return true;
  60351. }
  60352. }
  60353. for (var name in this._textureArrays) {
  60354. var array = this._textureArrays[name];
  60355. for (var index = 0; index < array.length; index++) {
  60356. if (array[index] === texture) {
  60357. return true;
  60358. }
  60359. }
  60360. }
  60361. return false;
  60362. };
  60363. ShaderMaterial.prototype.clone = function (name) {
  60364. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  60365. return newShaderMaterial;
  60366. };
  60367. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60368. if (forceDisposeTextures) {
  60369. var name;
  60370. for (name in this._textures) {
  60371. this._textures[name].dispose();
  60372. }
  60373. for (name in this._textureArrays) {
  60374. var array = this._textureArrays[name];
  60375. for (var index = 0; index < array.length; index++) {
  60376. array[index].dispose();
  60377. }
  60378. }
  60379. }
  60380. this._textures = {};
  60381. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60382. };
  60383. ShaderMaterial.prototype.serialize = function () {
  60384. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60385. serializationObject.customType = "BABYLON.ShaderMaterial";
  60386. serializationObject.options = this._options;
  60387. serializationObject.shaderPath = this._shaderPath;
  60388. var name;
  60389. // Texture
  60390. serializationObject.textures = {};
  60391. for (name in this._textures) {
  60392. serializationObject.textures[name] = this._textures[name].serialize();
  60393. }
  60394. // Texture arrays
  60395. serializationObject.textureArrays = {};
  60396. for (name in this._textureArrays) {
  60397. serializationObject.textureArrays[name] = [];
  60398. var array = this._textureArrays[name];
  60399. for (var index = 0; index < array.length; index++) {
  60400. serializationObject.textureArrays[name].push(array[index].serialize());
  60401. }
  60402. }
  60403. // Float
  60404. serializationObject.floats = {};
  60405. for (name in this._floats) {
  60406. serializationObject.floats[name] = this._floats[name];
  60407. }
  60408. // Float s
  60409. serializationObject.FloatArrays = {};
  60410. for (name in this._floatsArrays) {
  60411. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  60412. }
  60413. // Color3
  60414. serializationObject.colors3 = {};
  60415. for (name in this._colors3) {
  60416. serializationObject.colors3[name] = this._colors3[name].asArray();
  60417. }
  60418. // Color3 array
  60419. serializationObject.colors3Arrays = {};
  60420. for (name in this._colors3Arrays) {
  60421. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  60422. }
  60423. // Color4
  60424. serializationObject.colors4 = {};
  60425. for (name in this._colors4) {
  60426. serializationObject.colors4[name] = this._colors4[name].asArray();
  60427. }
  60428. // Vector2
  60429. serializationObject.vectors2 = {};
  60430. for (name in this._vectors2) {
  60431. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  60432. }
  60433. // Vector3
  60434. serializationObject.vectors3 = {};
  60435. for (name in this._vectors3) {
  60436. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  60437. }
  60438. // Vector4
  60439. serializationObject.vectors4 = {};
  60440. for (name in this._vectors4) {
  60441. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  60442. }
  60443. // Matrix
  60444. serializationObject.matrices = {};
  60445. for (name in this._matrices) {
  60446. serializationObject.matrices[name] = this._matrices[name].asArray();
  60447. }
  60448. // Matrix 3x3
  60449. serializationObject.matrices3x3 = {};
  60450. for (name in this._matrices3x3) {
  60451. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  60452. }
  60453. // Matrix 2x2
  60454. serializationObject.matrices2x2 = {};
  60455. for (name in this._matrices2x2) {
  60456. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  60457. }
  60458. // Vector2Array
  60459. serializationObject.vectors2Arrays = {};
  60460. for (name in this._vectors2Arrays) {
  60461. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60462. }
  60463. // Vector3Array
  60464. serializationObject.vectors3Arrays = {};
  60465. for (name in this._vectors3Arrays) {
  60466. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60467. }
  60468. return serializationObject;
  60469. };
  60470. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60471. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60472. var name;
  60473. // Texture
  60474. for (name in source.textures) {
  60475. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60476. }
  60477. // Texture arrays
  60478. for (name in source.textureArrays) {
  60479. var array = source.textureArrays[name];
  60480. var textureArray = new Array();
  60481. for (var index = 0; index < array.length; index++) {
  60482. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60483. }
  60484. material.setTextureArray(name, textureArray);
  60485. }
  60486. // Float
  60487. for (name in source.floats) {
  60488. material.setFloat(name, source.floats[name]);
  60489. }
  60490. // Float s
  60491. for (name in source.floatsArrays) {
  60492. material.setFloats(name, source.floatsArrays[name]);
  60493. }
  60494. // Color3
  60495. for (name in source.colors3) {
  60496. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60497. }
  60498. // Color3 arrays
  60499. for (name in source.colors3Arrays) {
  60500. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60501. if (i % 3 === 0) {
  60502. arr.push([num]);
  60503. }
  60504. else {
  60505. arr[arr.length - 1].push(num);
  60506. }
  60507. return arr;
  60508. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60509. material.setColor3Array(name, colors);
  60510. }
  60511. // Color4
  60512. for (name in source.colors4) {
  60513. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60514. }
  60515. // Vector2
  60516. for (name in source.vectors2) {
  60517. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60518. }
  60519. // Vector3
  60520. for (name in source.vectors3) {
  60521. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60522. }
  60523. // Vector4
  60524. for (name in source.vectors4) {
  60525. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60526. }
  60527. // Matrix
  60528. for (name in source.matrices) {
  60529. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60530. }
  60531. // Matrix 3x3
  60532. for (name in source.matrices3x3) {
  60533. material.setMatrix3x3(name, source.matrices3x3[name]);
  60534. }
  60535. // Matrix 2x2
  60536. for (name in source.matrices2x2) {
  60537. material.setMatrix2x2(name, source.matrices2x2[name]);
  60538. }
  60539. // Vector2Array
  60540. for (name in source.vectors2Arrays) {
  60541. material.setArray2(name, source.vectors2Arrays[name]);
  60542. }
  60543. // Vector3Array
  60544. for (name in source.vectors3Arrays) {
  60545. material.setArray3(name, source.vectors3Arrays[name]);
  60546. }
  60547. return material;
  60548. };
  60549. return ShaderMaterial;
  60550. }(BABYLON.Material));
  60551. BABYLON.ShaderMaterial = ShaderMaterial;
  60552. })(BABYLON || (BABYLON = {}));
  60553. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60554. var BABYLON;
  60555. (function (BABYLON) {
  60556. var GroundMesh = /** @class */ (function (_super) {
  60557. __extends(GroundMesh, _super);
  60558. function GroundMesh(name, scene) {
  60559. var _this = _super.call(this, name, scene) || this;
  60560. _this.generateOctree = false;
  60561. return _this;
  60562. }
  60563. GroundMesh.prototype.getClassName = function () {
  60564. return "GroundMesh";
  60565. };
  60566. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60567. get: function () {
  60568. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60569. },
  60570. enumerable: true,
  60571. configurable: true
  60572. });
  60573. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60574. get: function () {
  60575. return this._subdivisionsX;
  60576. },
  60577. enumerable: true,
  60578. configurable: true
  60579. });
  60580. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60581. get: function () {
  60582. return this._subdivisionsY;
  60583. },
  60584. enumerable: true,
  60585. configurable: true
  60586. });
  60587. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60588. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60589. this._subdivisionsX = chunksCount;
  60590. this._subdivisionsY = chunksCount;
  60591. this.subdivide(chunksCount);
  60592. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60593. };
  60594. /**
  60595. * Returns a height (y) value in the Worl system :
  60596. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60597. * Returns the ground y position if (x, z) are outside the ground surface.
  60598. */
  60599. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60600. var world = this.getWorldMatrix();
  60601. var invMat = BABYLON.Tmp.Matrix[5];
  60602. world.invertToRef(invMat);
  60603. var tmpVect = BABYLON.Tmp.Vector3[8];
  60604. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60605. x = tmpVect.x;
  60606. z = tmpVect.z;
  60607. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60608. return this.position.y;
  60609. }
  60610. if (!this._heightQuads || this._heightQuads.length == 0) {
  60611. this._initHeightQuads();
  60612. this._computeHeightQuads();
  60613. }
  60614. var facet = this._getFacetAt(x, z);
  60615. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60616. // return y in the World system
  60617. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60618. return tmpVect.y;
  60619. };
  60620. /**
  60621. * Returns a normalized vector (Vector3) orthogonal to the ground
  60622. * at the ground coordinates (x, z) expressed in the World system.
  60623. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60624. */
  60625. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60626. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60627. this.getNormalAtCoordinatesToRef(x, z, normal);
  60628. return normal;
  60629. };
  60630. /**
  60631. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60632. * at the ground coordinates (x, z) expressed in the World system.
  60633. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60634. * Returns the GroundMesh.
  60635. */
  60636. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60637. var world = this.getWorldMatrix();
  60638. var tmpMat = BABYLON.Tmp.Matrix[5];
  60639. world.invertToRef(tmpMat);
  60640. var tmpVect = BABYLON.Tmp.Vector3[8];
  60641. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60642. x = tmpVect.x;
  60643. z = tmpVect.z;
  60644. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60645. return this;
  60646. }
  60647. if (!this._heightQuads || this._heightQuads.length == 0) {
  60648. this._initHeightQuads();
  60649. this._computeHeightQuads();
  60650. }
  60651. var facet = this._getFacetAt(x, z);
  60652. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60653. return this;
  60654. };
  60655. /**
  60656. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60657. * if the ground has been updated.
  60658. * This can be used in the render loop.
  60659. * Returns the GroundMesh.
  60660. */
  60661. GroundMesh.prototype.updateCoordinateHeights = function () {
  60662. if (!this._heightQuads || this._heightQuads.length == 0) {
  60663. this._initHeightQuads();
  60664. }
  60665. this._computeHeightQuads();
  60666. return this;
  60667. };
  60668. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60669. GroundMesh.prototype._getFacetAt = function (x, z) {
  60670. // retrieve col and row from x, z coordinates in the ground local system
  60671. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60672. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60673. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60674. var facet;
  60675. if (z < quad.slope.x * x + quad.slope.y) {
  60676. facet = quad.facet1;
  60677. }
  60678. else {
  60679. facet = quad.facet2;
  60680. }
  60681. return facet;
  60682. };
  60683. // Creates and populates the heightMap array with "facet" elements :
  60684. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60685. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60686. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60687. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60688. // Returns the GroundMesh.
  60689. GroundMesh.prototype._initHeightQuads = function () {
  60690. var subdivisionsX = this._subdivisionsX;
  60691. var subdivisionsY = this._subdivisionsY;
  60692. this._heightQuads = new Array();
  60693. for (var row = 0; row < subdivisionsY; row++) {
  60694. for (var col = 0; col < subdivisionsX; col++) {
  60695. 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) };
  60696. this._heightQuads[row * subdivisionsX + col] = quad;
  60697. }
  60698. }
  60699. return this;
  60700. };
  60701. // Compute each quad element values and update the the heightMap array :
  60702. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60703. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60704. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60705. // Returns the GroundMesh.
  60706. GroundMesh.prototype._computeHeightQuads = function () {
  60707. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60708. if (!positions) {
  60709. return this;
  60710. }
  60711. var v1 = BABYLON.Tmp.Vector3[3];
  60712. var v2 = BABYLON.Tmp.Vector3[2];
  60713. var v3 = BABYLON.Tmp.Vector3[1];
  60714. var v4 = BABYLON.Tmp.Vector3[0];
  60715. var v1v2 = BABYLON.Tmp.Vector3[4];
  60716. var v1v3 = BABYLON.Tmp.Vector3[5];
  60717. var v1v4 = BABYLON.Tmp.Vector3[6];
  60718. var norm1 = BABYLON.Tmp.Vector3[7];
  60719. var norm2 = BABYLON.Tmp.Vector3[8];
  60720. var i = 0;
  60721. var j = 0;
  60722. var k = 0;
  60723. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60724. var h = 0;
  60725. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60726. var d2 = 0;
  60727. var subdivisionsX = this._subdivisionsX;
  60728. var subdivisionsY = this._subdivisionsY;
  60729. for (var row = 0; row < subdivisionsY; row++) {
  60730. for (var col = 0; col < subdivisionsX; col++) {
  60731. i = col * 3;
  60732. j = row * (subdivisionsX + 1) * 3;
  60733. k = (row + 1) * (subdivisionsX + 1) * 3;
  60734. v1.x = positions[j + i];
  60735. v1.y = positions[j + i + 1];
  60736. v1.z = positions[j + i + 2];
  60737. v2.x = positions[j + i + 3];
  60738. v2.y = positions[j + i + 4];
  60739. v2.z = positions[j + i + 5];
  60740. v3.x = positions[k + i];
  60741. v3.y = positions[k + i + 1];
  60742. v3.z = positions[k + i + 2];
  60743. v4.x = positions[k + i + 3];
  60744. v4.y = positions[k + i + 4];
  60745. v4.z = positions[k + i + 5];
  60746. // 2D slope V1V4
  60747. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60748. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60749. // facet equations :
  60750. // we compute each facet normal vector
  60751. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60752. // we compute the value d by applying the equation to v1 which belongs to the plane
  60753. // then we store the facet equation in a Vector4
  60754. v2.subtractToRef(v1, v1v2);
  60755. v3.subtractToRef(v1, v1v3);
  60756. v4.subtractToRef(v1, v1v4);
  60757. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60758. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60759. norm1.normalize();
  60760. norm2.normalize();
  60761. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60762. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60763. var quad = this._heightQuads[row * subdivisionsX + col];
  60764. quad.slope.copyFromFloats(cd, h);
  60765. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60766. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60767. }
  60768. }
  60769. return this;
  60770. };
  60771. GroundMesh.prototype.serialize = function (serializationObject) {
  60772. _super.prototype.serialize.call(this, serializationObject);
  60773. serializationObject.subdivisionsX = this._subdivisionsX;
  60774. serializationObject.subdivisionsY = this._subdivisionsY;
  60775. serializationObject.minX = this._minX;
  60776. serializationObject.maxX = this._maxX;
  60777. serializationObject.minZ = this._minZ;
  60778. serializationObject.maxZ = this._maxZ;
  60779. serializationObject.width = this._width;
  60780. serializationObject.height = this._height;
  60781. };
  60782. GroundMesh.Parse = function (parsedMesh, scene) {
  60783. var result = new GroundMesh(parsedMesh.name, scene);
  60784. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60785. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60786. result._minX = parsedMesh.minX;
  60787. result._maxX = parsedMesh.maxX;
  60788. result._minZ = parsedMesh.minZ;
  60789. result._maxZ = parsedMesh.maxZ;
  60790. result._width = parsedMesh.width;
  60791. result._height = parsedMesh.height;
  60792. return result;
  60793. };
  60794. return GroundMesh;
  60795. }(BABYLON.Mesh));
  60796. BABYLON.GroundMesh = GroundMesh;
  60797. })(BABYLON || (BABYLON = {}));
  60798. //# sourceMappingURL=babylon.groundMesh.js.map
  60799. var BABYLON;
  60800. (function (BABYLON) {
  60801. /**
  60802. * Creates an instance based on a source mesh.
  60803. */
  60804. var InstancedMesh = /** @class */ (function (_super) {
  60805. __extends(InstancedMesh, _super);
  60806. function InstancedMesh(name, source) {
  60807. var _this = _super.call(this, name, source.getScene()) || this;
  60808. source.instances.push(_this);
  60809. _this._sourceMesh = source;
  60810. _this.position.copyFrom(source.position);
  60811. _this.rotation.copyFrom(source.rotation);
  60812. _this.scaling.copyFrom(source.scaling);
  60813. if (source.rotationQuaternion) {
  60814. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60815. }
  60816. _this.infiniteDistance = source.infiniteDistance;
  60817. _this.setPivotMatrix(source.getPivotMatrix());
  60818. _this.refreshBoundingInfo();
  60819. _this._syncSubMeshes();
  60820. return _this;
  60821. }
  60822. /**
  60823. * Returns the string "InstancedMesh".
  60824. */
  60825. InstancedMesh.prototype.getClassName = function () {
  60826. return "InstancedMesh";
  60827. };
  60828. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60829. // Methods
  60830. get: function () {
  60831. return this._sourceMesh.receiveShadows;
  60832. },
  60833. enumerable: true,
  60834. configurable: true
  60835. });
  60836. Object.defineProperty(InstancedMesh.prototype, "material", {
  60837. get: function () {
  60838. return this._sourceMesh.material;
  60839. },
  60840. enumerable: true,
  60841. configurable: true
  60842. });
  60843. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60844. get: function () {
  60845. return this._sourceMesh.visibility;
  60846. },
  60847. enumerable: true,
  60848. configurable: true
  60849. });
  60850. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60851. get: function () {
  60852. return this._sourceMesh.skeleton;
  60853. },
  60854. enumerable: true,
  60855. configurable: true
  60856. });
  60857. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60858. get: function () {
  60859. return this._sourceMesh.renderingGroupId;
  60860. },
  60861. set: function (value) {
  60862. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60863. return;
  60864. }
  60865. //no-op with warning
  60866. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60867. },
  60868. enumerable: true,
  60869. configurable: true
  60870. });
  60871. /**
  60872. * Returns the total number of vertices (integer).
  60873. */
  60874. InstancedMesh.prototype.getTotalVertices = function () {
  60875. return this._sourceMesh.getTotalVertices();
  60876. };
  60877. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60878. get: function () {
  60879. return this._sourceMesh;
  60880. },
  60881. enumerable: true,
  60882. configurable: true
  60883. });
  60884. /**
  60885. * Is this node ready to be used/rendered
  60886. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60887. * @return {boolean} is it ready
  60888. */
  60889. InstancedMesh.prototype.isReady = function (completeCheck) {
  60890. if (completeCheck === void 0) { completeCheck = false; }
  60891. return this._sourceMesh.isReady(completeCheck, true);
  60892. };
  60893. /**
  60894. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60895. */
  60896. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60897. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60898. };
  60899. /**
  60900. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60901. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60902. * The `data` are either a numeric array either a Float32Array.
  60903. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60904. * 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).
  60905. * Note that a new underlying VertexBuffer object is created each call.
  60906. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60907. *
  60908. * Possible `kind` values :
  60909. * - BABYLON.VertexBuffer.PositionKind
  60910. * - BABYLON.VertexBuffer.UVKind
  60911. * - BABYLON.VertexBuffer.UV2Kind
  60912. * - BABYLON.VertexBuffer.UV3Kind
  60913. * - BABYLON.VertexBuffer.UV4Kind
  60914. * - BABYLON.VertexBuffer.UV5Kind
  60915. * - BABYLON.VertexBuffer.UV6Kind
  60916. * - BABYLON.VertexBuffer.ColorKind
  60917. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60918. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60919. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60920. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60921. *
  60922. * Returns the Mesh.
  60923. */
  60924. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60925. if (this.sourceMesh) {
  60926. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60927. }
  60928. return this.sourceMesh;
  60929. };
  60930. /**
  60931. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60932. * If the mesh has no geometry, it is simply returned as it is.
  60933. * The `data` are either a numeric array either a Float32Array.
  60934. * No new underlying VertexBuffer object is created.
  60935. * 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.
  60936. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60937. *
  60938. * Possible `kind` values :
  60939. * - BABYLON.VertexBuffer.PositionKind
  60940. * - BABYLON.VertexBuffer.UVKind
  60941. * - BABYLON.VertexBuffer.UV2Kind
  60942. * - BABYLON.VertexBuffer.UV3Kind
  60943. * - BABYLON.VertexBuffer.UV4Kind
  60944. * - BABYLON.VertexBuffer.UV5Kind
  60945. * - BABYLON.VertexBuffer.UV6Kind
  60946. * - BABYLON.VertexBuffer.ColorKind
  60947. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60948. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60949. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60950. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60951. *
  60952. * Returns the Mesh.
  60953. */
  60954. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60955. if (this.sourceMesh) {
  60956. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60957. }
  60958. return this.sourceMesh;
  60959. };
  60960. /**
  60961. * Sets the mesh indices.
  60962. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60963. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60964. * This method creates a new index buffer each call.
  60965. * Returns the Mesh.
  60966. */
  60967. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60968. if (totalVertices === void 0) { totalVertices = null; }
  60969. if (this.sourceMesh) {
  60970. this.sourceMesh.setIndices(indices, totalVertices);
  60971. }
  60972. return this.sourceMesh;
  60973. };
  60974. /**
  60975. * Boolean : True if the mesh owns the requested kind of data.
  60976. */
  60977. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60978. return this._sourceMesh.isVerticesDataPresent(kind);
  60979. };
  60980. /**
  60981. * Returns an array of indices (IndicesArray).
  60982. */
  60983. InstancedMesh.prototype.getIndices = function () {
  60984. return this._sourceMesh.getIndices();
  60985. };
  60986. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60987. get: function () {
  60988. return this._sourceMesh._positions;
  60989. },
  60990. enumerable: true,
  60991. configurable: true
  60992. });
  60993. /**
  60994. * Sets a new updated BoundingInfo to the mesh.
  60995. * Returns the mesh.
  60996. */
  60997. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60998. var meshBB = this._sourceMesh.getBoundingInfo();
  60999. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  61000. this._updateBoundingInfo();
  61001. return this;
  61002. };
  61003. InstancedMesh.prototype._preActivate = function () {
  61004. if (this._currentLOD) {
  61005. this._currentLOD._preActivate();
  61006. }
  61007. return this;
  61008. };
  61009. InstancedMesh.prototype._activate = function (renderId) {
  61010. if (this._currentLOD) {
  61011. this._currentLOD._registerInstanceForRenderId(this, renderId);
  61012. }
  61013. return this;
  61014. };
  61015. /**
  61016. * Returns the current associated LOD AbstractMesh.
  61017. */
  61018. InstancedMesh.prototype.getLOD = function (camera) {
  61019. if (!camera) {
  61020. return this;
  61021. }
  61022. var boundingInfo = this.getBoundingInfo();
  61023. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  61024. if (this._currentLOD === this.sourceMesh) {
  61025. return this;
  61026. }
  61027. return this._currentLOD;
  61028. };
  61029. InstancedMesh.prototype._syncSubMeshes = function () {
  61030. this.releaseSubMeshes();
  61031. if (this._sourceMesh.subMeshes) {
  61032. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  61033. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  61034. }
  61035. }
  61036. return this;
  61037. };
  61038. InstancedMesh.prototype._generatePointsArray = function () {
  61039. return this._sourceMesh._generatePointsArray();
  61040. };
  61041. /**
  61042. * Creates a new InstancedMesh from the current mesh.
  61043. * - name (string) : the cloned mesh name
  61044. * - newParent (optional Node) : the optional Node to parent the clone to.
  61045. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  61046. *
  61047. * Returns the clone.
  61048. */
  61049. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61050. var result = this._sourceMesh.createInstance(name);
  61051. // Deep copy
  61052. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  61053. // Bounding info
  61054. this.refreshBoundingInfo();
  61055. // Parent
  61056. if (newParent) {
  61057. result.parent = newParent;
  61058. }
  61059. if (!doNotCloneChildren) {
  61060. // Children
  61061. for (var index = 0; index < this.getScene().meshes.length; index++) {
  61062. var mesh = this.getScene().meshes[index];
  61063. if (mesh.parent === this) {
  61064. mesh.clone(mesh.name, result);
  61065. }
  61066. }
  61067. }
  61068. result.computeWorldMatrix(true);
  61069. return result;
  61070. };
  61071. /**
  61072. * Disposes the InstancedMesh.
  61073. * Returns nothing.
  61074. */
  61075. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  61076. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  61077. // Remove from mesh
  61078. var index = this._sourceMesh.instances.indexOf(this);
  61079. this._sourceMesh.instances.splice(index, 1);
  61080. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  61081. };
  61082. return InstancedMesh;
  61083. }(BABYLON.AbstractMesh));
  61084. BABYLON.InstancedMesh = InstancedMesh;
  61085. })(BABYLON || (BABYLON = {}));
  61086. //# sourceMappingURL=babylon.instancedMesh.js.map
  61087. var BABYLON;
  61088. (function (BABYLON) {
  61089. var LinesMesh = /** @class */ (function (_super) {
  61090. __extends(LinesMesh, _super);
  61091. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  61092. if (scene === void 0) { scene = null; }
  61093. if (parent === void 0) { parent = null; }
  61094. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  61095. _this.useVertexColor = useVertexColor;
  61096. _this.useVertexAlpha = useVertexAlpha;
  61097. _this.color = new BABYLON.Color3(1, 1, 1);
  61098. _this.alpha = 1;
  61099. if (source) {
  61100. _this.color = source.color.clone();
  61101. _this.alpha = source.alpha;
  61102. _this.useVertexColor = source.useVertexColor;
  61103. _this.useVertexAlpha = source.useVertexAlpha;
  61104. }
  61105. _this._intersectionThreshold = 0.1;
  61106. var defines = [];
  61107. var options = {
  61108. attributes: [BABYLON.VertexBuffer.PositionKind],
  61109. uniforms: ["world", "viewProjection"],
  61110. needAlphaBlending: true,
  61111. defines: defines
  61112. };
  61113. if (useVertexAlpha === false) {
  61114. options.needAlphaBlending = false;
  61115. }
  61116. if (!useVertexColor) {
  61117. options.uniforms.push("color");
  61118. }
  61119. else {
  61120. options.defines.push("#define VERTEXCOLOR");
  61121. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  61122. }
  61123. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  61124. return _this;
  61125. }
  61126. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  61127. /**
  61128. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  61129. * This margin is expressed in world space coordinates, so its value may vary.
  61130. * Default value is 0.1
  61131. * @returns the intersection Threshold value.
  61132. */
  61133. get: function () {
  61134. return this._intersectionThreshold;
  61135. },
  61136. /**
  61137. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  61138. * This margin is expressed in world space coordinates, so its value may vary.
  61139. * @param value the new threshold to apply
  61140. */
  61141. set: function (value) {
  61142. if (this._intersectionThreshold === value) {
  61143. return;
  61144. }
  61145. this._intersectionThreshold = value;
  61146. if (this.geometry) {
  61147. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  61148. }
  61149. },
  61150. enumerable: true,
  61151. configurable: true
  61152. });
  61153. /**
  61154. * Returns the string "LineMesh"
  61155. */
  61156. LinesMesh.prototype.getClassName = function () {
  61157. return "LinesMesh";
  61158. };
  61159. Object.defineProperty(LinesMesh.prototype, "material", {
  61160. get: function () {
  61161. return this._colorShader;
  61162. },
  61163. set: function (value) {
  61164. // Do nothing
  61165. },
  61166. enumerable: true,
  61167. configurable: true
  61168. });
  61169. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  61170. get: function () {
  61171. return false;
  61172. },
  61173. enumerable: true,
  61174. configurable: true
  61175. });
  61176. LinesMesh.prototype.createInstance = function (name) {
  61177. throw new Error("LinesMeshes do not support createInstance.");
  61178. };
  61179. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  61180. if (!this._geometry) {
  61181. return this;
  61182. }
  61183. // VBOs
  61184. this._geometry._bind(this._colorShader.getEffect());
  61185. // Color
  61186. if (!this.useVertexColor) {
  61187. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  61188. }
  61189. return this;
  61190. };
  61191. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  61192. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  61193. return this;
  61194. }
  61195. var engine = this.getScene().getEngine();
  61196. // Draw order
  61197. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  61198. return this;
  61199. };
  61200. LinesMesh.prototype.dispose = function (doNotRecurse) {
  61201. this._colorShader.dispose();
  61202. _super.prototype.dispose.call(this, doNotRecurse);
  61203. };
  61204. /**
  61205. * Returns a new LineMesh object cloned from the current one.
  61206. */
  61207. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61208. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  61209. };
  61210. return LinesMesh;
  61211. }(BABYLON.Mesh));
  61212. BABYLON.LinesMesh = LinesMesh;
  61213. })(BABYLON || (BABYLON = {}));
  61214. //# sourceMappingURL=babylon.linesMesh.js.map
  61215. var BABYLON;
  61216. (function (BABYLON) {
  61217. /**
  61218. * Class containing static functions to help procedurally build meshes
  61219. */
  61220. var MeshBuilder = /** @class */ (function () {
  61221. function MeshBuilder() {
  61222. }
  61223. MeshBuilder.updateSideOrientation = function (orientation) {
  61224. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  61225. return BABYLON.Mesh.DOUBLESIDE;
  61226. }
  61227. if (orientation === undefined || orientation === null) {
  61228. return BABYLON.Mesh.FRONTSIDE;
  61229. }
  61230. return orientation;
  61231. };
  61232. /**
  61233. * Creates a box mesh
  61234. * * The parameter `size` sets the size (float) of each box side (default 1)
  61235. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  61236. * * 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)
  61237. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61238. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61239. * * 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
  61240. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61241. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  61242. * @param name defines the name of the mesh
  61243. * @param options defines the options used to create the mesh
  61244. * @param scene defines the hosting scene
  61245. * @returns the box mesh
  61246. */
  61247. MeshBuilder.CreateBox = function (name, options, scene) {
  61248. if (scene === void 0) { scene = null; }
  61249. var box = new BABYLON.Mesh(name, scene);
  61250. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61251. box._originalBuilderSideOrientation = options.sideOrientation;
  61252. var vertexData = BABYLON.VertexData.CreateBox(options);
  61253. vertexData.applyToMesh(box, options.updatable);
  61254. return box;
  61255. };
  61256. /**
  61257. * Creates a sphere mesh
  61258. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  61259. * * 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`)
  61260. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  61261. * * 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
  61262. * * 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)
  61263. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61264. * * 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
  61265. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61266. * @param name defines the name of the mesh
  61267. * @param options defines the options used to create the mesh
  61268. * @param scene defines the hosting scene
  61269. * @returns the sphere mesh
  61270. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  61271. */
  61272. MeshBuilder.CreateSphere = function (name, options, scene) {
  61273. var sphere = new BABYLON.Mesh(name, scene);
  61274. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61275. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61276. var vertexData = BABYLON.VertexData.CreateSphere(options);
  61277. vertexData.applyToMesh(sphere, options.updatable);
  61278. return sphere;
  61279. };
  61280. /**
  61281. * Creates a plane polygonal mesh. By default, this is a disc
  61282. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  61283. * * 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
  61284. * * 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
  61285. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61286. * * 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
  61287. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61288. * @param name defines the name of the mesh
  61289. * @param options defines the options used to create the mesh
  61290. * @param scene defines the hosting scene
  61291. * @returns the plane polygonal mesh
  61292. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  61293. */
  61294. MeshBuilder.CreateDisc = function (name, options, scene) {
  61295. if (scene === void 0) { scene = null; }
  61296. var disc = new BABYLON.Mesh(name, scene);
  61297. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61298. disc._originalBuilderSideOrientation = options.sideOrientation;
  61299. var vertexData = BABYLON.VertexData.CreateDisc(options);
  61300. vertexData.applyToMesh(disc, options.updatable);
  61301. return disc;
  61302. };
  61303. /**
  61304. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  61305. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  61306. * * 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`)
  61307. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  61308. * * 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
  61309. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61310. * * 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
  61311. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61312. * @param name defines the name of the mesh
  61313. * @param options defines the options used to create the mesh
  61314. * @param scene defines the hosting scene
  61315. * @returns the icosahedron mesh
  61316. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  61317. */
  61318. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  61319. var sphere = new BABYLON.Mesh(name, scene);
  61320. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61321. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61322. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  61323. vertexData.applyToMesh(sphere, options.updatable);
  61324. return sphere;
  61325. };
  61326. ;
  61327. /**
  61328. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61329. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  61330. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  61331. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  61332. * * 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
  61333. * * 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
  61334. * * 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
  61335. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61336. * * 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
  61337. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61338. * * 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
  61339. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  61340. * * 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
  61341. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  61342. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61343. * @param name defines the name of the mesh
  61344. * @param options defines the options used to create the mesh
  61345. * @param scene defines the hosting scene
  61346. * @returns the ribbon mesh
  61347. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  61348. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61349. */
  61350. MeshBuilder.CreateRibbon = function (name, options, scene) {
  61351. if (scene === void 0) { scene = null; }
  61352. var pathArray = options.pathArray;
  61353. var closeArray = options.closeArray;
  61354. var closePath = options.closePath;
  61355. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61356. var instance = options.instance;
  61357. var updatable = options.updatable;
  61358. if (instance) { // existing ribbon instance update
  61359. // positionFunction : ribbon case
  61360. // only pathArray and sideOrientation parameters are taken into account for positions update
  61361. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  61362. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  61363. var positionFunction = function (positions) {
  61364. var minlg = pathArray[0].length;
  61365. var i = 0;
  61366. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  61367. for (var si = 1; si <= ns; si++) {
  61368. for (var p = 0; p < pathArray.length; p++) {
  61369. var path = pathArray[p];
  61370. var l = path.length;
  61371. minlg = (minlg < l) ? minlg : l;
  61372. var j = 0;
  61373. while (j < minlg) {
  61374. positions[i] = path[j].x;
  61375. positions[i + 1] = path[j].y;
  61376. positions[i + 2] = path[j].z;
  61377. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  61378. BABYLON.Tmp.Vector3[0].x = path[j].x;
  61379. }
  61380. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  61381. BABYLON.Tmp.Vector3[1].x = path[j].x;
  61382. }
  61383. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  61384. BABYLON.Tmp.Vector3[0].y = path[j].y;
  61385. }
  61386. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  61387. BABYLON.Tmp.Vector3[1].y = path[j].y;
  61388. }
  61389. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  61390. BABYLON.Tmp.Vector3[0].z = path[j].z;
  61391. }
  61392. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  61393. BABYLON.Tmp.Vector3[1].z = path[j].z;
  61394. }
  61395. j++;
  61396. i += 3;
  61397. }
  61398. if (instance._closePath) {
  61399. positions[i] = path[0].x;
  61400. positions[i + 1] = path[0].y;
  61401. positions[i + 2] = path[0].z;
  61402. i += 3;
  61403. }
  61404. }
  61405. }
  61406. };
  61407. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61408. positionFunction(positions);
  61409. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  61410. instance._boundingInfo.update(instance._worldMatrix);
  61411. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61412. if (options.colors) {
  61413. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61414. for (var c = 0; c < options.colors.length; c++) {
  61415. colors[c * 4] = options.colors[c].r;
  61416. colors[c * 4 + 1] = options.colors[c].g;
  61417. colors[c * 4 + 2] = options.colors[c].b;
  61418. colors[c * 4 + 3] = options.colors[c].a;
  61419. }
  61420. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  61421. }
  61422. if (options.uvs) {
  61423. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61424. for (var i = 0; i < options.uvs.length; i++) {
  61425. uvs[i * 2] = options.uvs[i].x;
  61426. uvs[i * 2 + 1] = options.uvs[i].y;
  61427. }
  61428. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  61429. }
  61430. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  61431. var indices = instance.getIndices();
  61432. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61433. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  61434. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  61435. if (instance._closePath) {
  61436. var indexFirst = 0;
  61437. var indexLast = 0;
  61438. for (var p = 0; p < pathArray.length; p++) {
  61439. indexFirst = instance._idx[p] * 3;
  61440. if (p + 1 < pathArray.length) {
  61441. indexLast = (instance._idx[p + 1] - 1) * 3;
  61442. }
  61443. else {
  61444. indexLast = normals.length - 3;
  61445. }
  61446. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  61447. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  61448. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  61449. normals[indexLast] = normals[indexFirst];
  61450. normals[indexLast + 1] = normals[indexFirst + 1];
  61451. normals[indexLast + 2] = normals[indexFirst + 2];
  61452. }
  61453. }
  61454. if (!(instance.areNormalsFrozen)) {
  61455. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  61456. }
  61457. }
  61458. return instance;
  61459. }
  61460. else { // new ribbon creation
  61461. var ribbon = new BABYLON.Mesh(name, scene);
  61462. ribbon._originalBuilderSideOrientation = sideOrientation;
  61463. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  61464. if (closePath) {
  61465. ribbon._idx = vertexData._idx;
  61466. }
  61467. ribbon._closePath = closePath;
  61468. ribbon._closeArray = closeArray;
  61469. vertexData.applyToMesh(ribbon, updatable);
  61470. return ribbon;
  61471. }
  61472. };
  61473. /**
  61474. * Creates a cylinder or a cone mesh
  61475. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  61476. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  61477. * * 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.
  61478. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  61479. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  61480. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  61481. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  61482. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  61483. * * 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).
  61484. * * 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
  61485. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61486. * * 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
  61487. * * 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.
  61488. * * If `enclose` is false, a ring surface is one element.
  61489. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61490. * * 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
  61491. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61492. * * 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
  61493. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61494. * @param name defines the name of the mesh
  61495. * @param options defines the options used to create the mesh
  61496. * @param scene defines the hosting scene
  61497. * @returns the cylinder mesh
  61498. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61499. */
  61500. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61501. var cylinder = new BABYLON.Mesh(name, scene);
  61502. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61503. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61504. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61505. vertexData.applyToMesh(cylinder, options.updatable);
  61506. return cylinder;
  61507. };
  61508. /**
  61509. * Creates a torus mesh
  61510. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61511. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61512. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61513. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61514. * * 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
  61515. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61516. * @param name defines the name of the mesh
  61517. * @param options defines the options used to create the mesh
  61518. * @param scene defines the hosting scene
  61519. * @returns the torus mesh
  61520. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61521. */
  61522. MeshBuilder.CreateTorus = function (name, options, scene) {
  61523. var torus = new BABYLON.Mesh(name, scene);
  61524. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61525. torus._originalBuilderSideOrientation = options.sideOrientation;
  61526. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61527. vertexData.applyToMesh(torus, options.updatable);
  61528. return torus;
  61529. };
  61530. /**
  61531. * Creates a torus knot mesh
  61532. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61533. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61534. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61535. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61536. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61537. * * 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
  61538. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61539. * @param name defines the name of the mesh
  61540. * @param options defines the options used to create the mesh
  61541. * @param scene defines the hosting scene
  61542. * @returns the torus knot mesh
  61543. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  61544. */
  61545. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  61546. var torusKnot = new BABYLON.Mesh(name, scene);
  61547. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61548. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  61549. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  61550. vertexData.applyToMesh(torusKnot, options.updatable);
  61551. return torusKnot;
  61552. };
  61553. /**
  61554. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61555. * * 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
  61556. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61557. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61558. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61559. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61560. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61561. * * 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
  61562. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61563. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61564. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61565. * @param name defines the name of the new line system
  61566. * @param options defines the options used to create the line system
  61567. * @param scene defines the hosting scene
  61568. * @returns a new line system mesh
  61569. */
  61570. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61571. var instance = options.instance;
  61572. var lines = options.lines;
  61573. var colors = options.colors;
  61574. if (instance) { // lines update
  61575. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61576. var vertexColor;
  61577. var lineColors;
  61578. if (colors) {
  61579. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61580. }
  61581. var i = 0;
  61582. var c = 0;
  61583. for (var l = 0; l < lines.length; l++) {
  61584. var points = lines[l];
  61585. for (var p = 0; p < points.length; p++) {
  61586. positions[i] = points[p].x;
  61587. positions[i + 1] = points[p].y;
  61588. positions[i + 2] = points[p].z;
  61589. if (colors && vertexColor) {
  61590. lineColors = colors[l];
  61591. vertexColor[c] = lineColors[p].r;
  61592. vertexColor[c + 1] = lineColors[p].g;
  61593. vertexColor[c + 2] = lineColors[p].b;
  61594. vertexColor[c + 3] = lineColors[p].a;
  61595. c += 4;
  61596. }
  61597. i += 3;
  61598. }
  61599. }
  61600. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61601. if (colors && vertexColor) {
  61602. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61603. }
  61604. return instance;
  61605. }
  61606. // line system creation
  61607. var useVertexColor = (colors) ? true : false;
  61608. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61609. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61610. vertexData.applyToMesh(lineSystem, options.updatable);
  61611. return lineSystem;
  61612. };
  61613. /**
  61614. * Creates a line mesh
  61615. * 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
  61616. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61617. * * The parameter `points` is an array successive Vector3
  61618. * * 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
  61619. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61620. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61621. * * When updating an instance, remember that only point positions can change, not the number of points
  61622. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61623. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61624. * @param name defines the name of the new line system
  61625. * @param options defines the options used to create the line system
  61626. * @param scene defines the hosting scene
  61627. * @returns a new line mesh
  61628. */
  61629. MeshBuilder.CreateLines = function (name, options, scene) {
  61630. if (scene === void 0) { scene = null; }
  61631. var colors = (options.colors) ? [options.colors] : null;
  61632. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61633. return lines;
  61634. };
  61635. /**
  61636. * Creates a dashed line mesh
  61637. * * 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
  61638. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61639. * * The parameter `points` is an array successive Vector3
  61640. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61641. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61642. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61643. * * 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
  61644. * * When updating an instance, remember that only point positions can change, not the number of points
  61645. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61646. * @param name defines the name of the mesh
  61647. * @param options defines the options used to create the mesh
  61648. * @param scene defines the hosting scene
  61649. * @returns the dashed line mesh
  61650. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61651. */
  61652. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61653. if (scene === void 0) { scene = null; }
  61654. var points = options.points;
  61655. var instance = options.instance;
  61656. var gapSize = options.gapSize || 1;
  61657. var dashSize = options.dashSize || 3;
  61658. if (instance) { // dashed lines update
  61659. var positionFunction = function (positions) {
  61660. var curvect = BABYLON.Vector3.Zero();
  61661. var nbSeg = positions.length / 6;
  61662. var lg = 0;
  61663. var nb = 0;
  61664. var shft = 0;
  61665. var dashshft = 0;
  61666. var curshft = 0;
  61667. var p = 0;
  61668. var i = 0;
  61669. var j = 0;
  61670. for (i = 0; i < points.length - 1; i++) {
  61671. points[i + 1].subtractToRef(points[i], curvect);
  61672. lg += curvect.length();
  61673. }
  61674. shft = lg / nbSeg;
  61675. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61676. for (i = 0; i < points.length - 1; i++) {
  61677. points[i + 1].subtractToRef(points[i], curvect);
  61678. nb = Math.floor(curvect.length() / shft);
  61679. curvect.normalize();
  61680. j = 0;
  61681. while (j < nb && p < positions.length) {
  61682. curshft = shft * j;
  61683. positions[p] = points[i].x + curshft * curvect.x;
  61684. positions[p + 1] = points[i].y + curshft * curvect.y;
  61685. positions[p + 2] = points[i].z + curshft * curvect.z;
  61686. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61687. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61688. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61689. p += 6;
  61690. j++;
  61691. }
  61692. }
  61693. while (p < positions.length) {
  61694. positions[p] = points[i].x;
  61695. positions[p + 1] = points[i].y;
  61696. positions[p + 2] = points[i].z;
  61697. p += 3;
  61698. }
  61699. };
  61700. instance.updateMeshPositions(positionFunction, false);
  61701. return instance;
  61702. }
  61703. // dashed lines creation
  61704. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61705. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61706. vertexData.applyToMesh(dashedLines, options.updatable);
  61707. dashedLines.dashSize = dashSize;
  61708. dashedLines.gapSize = gapSize;
  61709. return dashedLines;
  61710. };
  61711. /**
  61712. * 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.
  61713. * * 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.
  61714. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61715. * * 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.
  61716. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61717. * * 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
  61718. * * 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
  61719. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61720. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61721. * * 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
  61722. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61723. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61724. * @param name defines the name of the mesh
  61725. * @param options defines the options used to create the mesh
  61726. * @param scene defines the hosting scene
  61727. * @returns the extruded shape mesh
  61728. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61729. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61730. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61731. */
  61732. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61733. if (scene === void 0) { scene = null; }
  61734. var path = options.path;
  61735. var shape = options.shape;
  61736. var scale = options.scale || 1;
  61737. var rotation = options.rotation || 0;
  61738. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61739. var updatable = options.updatable;
  61740. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61741. var instance = options.instance || null;
  61742. var invertUV = options.invertUV || false;
  61743. 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);
  61744. };
  61745. /**
  61746. * Creates an custom extruded shape mesh.
  61747. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61748. * * 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.
  61749. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61750. * * 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
  61751. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61752. * * 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
  61753. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61754. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61755. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61756. * * 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
  61757. * * 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
  61758. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61759. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61760. * * 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
  61761. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61762. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61763. * @param name defines the name of the mesh
  61764. * @param options defines the options used to create the mesh
  61765. * @param scene defines the hosting scene
  61766. * @returns the custom extruded shape mesh
  61767. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61768. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61769. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61770. */
  61771. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61772. var path = options.path;
  61773. var shape = options.shape;
  61774. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61775. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61776. var ribbonCloseArray = options.ribbonCloseArray || false;
  61777. var ribbonClosePath = options.ribbonClosePath || false;
  61778. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61779. var updatable = options.updatable;
  61780. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61781. var instance = options.instance;
  61782. var invertUV = options.invertUV || false;
  61783. 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);
  61784. };
  61785. /**
  61786. * Creates lathe mesh.
  61787. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61788. * * 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
  61789. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61790. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61791. * * 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
  61792. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61793. * * 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
  61794. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61795. * * 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
  61796. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61797. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61798. * @param name defines the name of the mesh
  61799. * @param options defines the options used to create the mesh
  61800. * @param scene defines the hosting scene
  61801. * @returns the lathe mesh
  61802. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61803. */
  61804. MeshBuilder.CreateLathe = function (name, options, scene) {
  61805. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61806. var closed = (options.closed === undefined) ? true : options.closed;
  61807. var shape = options.shape;
  61808. var radius = options.radius || 1;
  61809. var tessellation = options.tessellation || 64;
  61810. var updatable = options.updatable;
  61811. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61812. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61813. var pi2 = Math.PI * 2;
  61814. var paths = new Array();
  61815. var invertUV = options.invertUV || false;
  61816. var i = 0;
  61817. var p = 0;
  61818. var step = pi2 / tessellation * arc;
  61819. var rotated;
  61820. var path = new Array();
  61821. for (i = 0; i <= tessellation; i++) {
  61822. var path = [];
  61823. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61824. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61825. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61826. }
  61827. for (p = 0; p < shape.length; p++) {
  61828. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61829. path.push(rotated);
  61830. }
  61831. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61832. 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));
  61833. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61834. }
  61835. paths.push(path);
  61836. }
  61837. // lathe ribbon
  61838. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61839. return lathe;
  61840. };
  61841. /**
  61842. * Creates a plane mesh
  61843. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61844. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61845. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61846. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61847. * * 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
  61848. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61849. * @param name defines the name of the mesh
  61850. * @param options defines the options used to create the mesh
  61851. * @param scene defines the hosting scene
  61852. * @returns the plane mesh
  61853. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61854. */
  61855. MeshBuilder.CreatePlane = function (name, options, scene) {
  61856. var plane = new BABYLON.Mesh(name, scene);
  61857. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61858. plane._originalBuilderSideOrientation = options.sideOrientation;
  61859. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61860. vertexData.applyToMesh(plane, options.updatable);
  61861. if (options.sourcePlane) {
  61862. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61863. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61864. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61865. plane.rotate(vectorProduct, product);
  61866. }
  61867. return plane;
  61868. };
  61869. /**
  61870. * Creates a ground mesh
  61871. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61872. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61873. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61874. * @param name defines the name of the mesh
  61875. * @param options defines the options used to create the mesh
  61876. * @param scene defines the hosting scene
  61877. * @returns the ground mesh
  61878. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61879. */
  61880. MeshBuilder.CreateGround = function (name, options, scene) {
  61881. var ground = new BABYLON.GroundMesh(name, scene);
  61882. ground._setReady(false);
  61883. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61884. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61885. ground._width = options.width || 1;
  61886. ground._height = options.height || 1;
  61887. ground._maxX = ground._width / 2;
  61888. ground._maxZ = ground._height / 2;
  61889. ground._minX = -ground._maxX;
  61890. ground._minZ = -ground._maxZ;
  61891. var vertexData = BABYLON.VertexData.CreateGround(options);
  61892. vertexData.applyToMesh(ground, options.updatable);
  61893. ground._setReady(true);
  61894. return ground;
  61895. };
  61896. /**
  61897. * Creates a tiled ground mesh
  61898. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61899. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61900. * * 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
  61901. * * 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
  61902. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61903. * @param name defines the name of the mesh
  61904. * @param options defines the options used to create the mesh
  61905. * @param scene defines the hosting scene
  61906. * @returns the tiled ground mesh
  61907. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61908. */
  61909. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61910. var tiledGround = new BABYLON.Mesh(name, scene);
  61911. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61912. vertexData.applyToMesh(tiledGround, options.updatable);
  61913. return tiledGround;
  61914. };
  61915. /**
  61916. * Creates a ground mesh from a height map
  61917. * * The parameter `url` sets the URL of the height map image resource.
  61918. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61919. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61920. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61921. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61922. * * 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.
  61923. * * 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).
  61924. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61925. * @param name defines the name of the mesh
  61926. * @param url defines the url to the height map
  61927. * @param options defines the options used to create the mesh
  61928. * @param scene defines the hosting scene
  61929. * @returns the ground mesh
  61930. * @see http://doc.babylonjs.com/babylon101/height_map
  61931. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61932. */
  61933. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61934. var width = options.width || 10.0;
  61935. var height = options.height || 10.0;
  61936. var subdivisions = options.subdivisions || 1 | 0;
  61937. var minHeight = options.minHeight || 0.0;
  61938. var maxHeight = options.maxHeight || 1.0;
  61939. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61940. var updatable = options.updatable;
  61941. var onReady = options.onReady;
  61942. var ground = new BABYLON.GroundMesh(name, scene);
  61943. ground._subdivisionsX = subdivisions;
  61944. ground._subdivisionsY = subdivisions;
  61945. ground._width = width;
  61946. ground._height = height;
  61947. ground._maxX = ground._width / 2.0;
  61948. ground._maxZ = ground._height / 2.0;
  61949. ground._minX = -ground._maxX;
  61950. ground._minZ = -ground._maxZ;
  61951. ground._setReady(false);
  61952. var onload = function (img) {
  61953. // Getting height map data
  61954. var canvas = document.createElement("canvas");
  61955. var context = canvas.getContext("2d");
  61956. if (!context) {
  61957. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61958. }
  61959. if (scene.isDisposed) {
  61960. return;
  61961. }
  61962. var bufferWidth = img.width;
  61963. var bufferHeight = img.height;
  61964. canvas.width = bufferWidth;
  61965. canvas.height = bufferHeight;
  61966. context.drawImage(img, 0, 0);
  61967. // Create VertexData from map data
  61968. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61969. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61970. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61971. width: width, height: height,
  61972. subdivisions: subdivisions,
  61973. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61974. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61975. });
  61976. vertexData.applyToMesh(ground, updatable);
  61977. //execute ready callback, if set
  61978. if (onReady) {
  61979. onReady(ground);
  61980. }
  61981. ground._setReady(true);
  61982. };
  61983. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61984. return ground;
  61985. };
  61986. /**
  61987. * Creates a polygon mesh
  61988. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61989. * * 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
  61990. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61991. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61992. * * 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)
  61993. * * Remember you can only change the shape positions, not their number when updating a polygon
  61994. * @param name defines the name of the mesh
  61995. * @param options defines the options used to create the mesh
  61996. * @param scene defines the hosting scene
  61997. * @returns the polygon mesh
  61998. */
  61999. MeshBuilder.CreatePolygon = function (name, options, scene) {
  62000. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62001. var shape = options.shape;
  62002. var holes = options.holes || [];
  62003. var depth = options.depth || 0;
  62004. var contours = [];
  62005. var hole = [];
  62006. for (var i = 0; i < shape.length; i++) {
  62007. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  62008. }
  62009. var epsilon = 0.00000001;
  62010. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  62011. contours.pop();
  62012. }
  62013. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  62014. for (var hNb = 0; hNb < holes.length; hNb++) {
  62015. hole = [];
  62016. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  62017. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  62018. }
  62019. polygonTriangulation.addHole(hole);
  62020. }
  62021. var polygon = polygonTriangulation.build(options.updatable, depth);
  62022. polygon._originalBuilderSideOrientation = options.sideOrientation;
  62023. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  62024. vertexData.applyToMesh(polygon, options.updatable);
  62025. return polygon;
  62026. };
  62027. ;
  62028. /**
  62029. * Creates an extruded polygon mesh, with depth in the Y direction.
  62030. * * 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)
  62031. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  62032. * @param name defines the name of the mesh
  62033. * @param options defines the options used to create the mesh
  62034. * @param scene defines the hosting scene
  62035. * @returns the polygon mesh
  62036. */
  62037. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  62038. return MeshBuilder.CreatePolygon(name, options, scene);
  62039. };
  62040. ;
  62041. /**
  62042. * Creates a tube mesh.
  62043. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  62044. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  62045. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  62046. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  62047. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  62048. * * 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)
  62049. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  62050. * * 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
  62051. * * 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
  62052. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62053. * * 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
  62054. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62055. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62056. * @param name defines the name of the mesh
  62057. * @param options defines the options used to create the mesh
  62058. * @param scene defines the hosting scene
  62059. * @returns the tube mesh
  62060. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62061. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  62062. */
  62063. MeshBuilder.CreateTube = function (name, options, scene) {
  62064. var path = options.path;
  62065. var instance = options.instance;
  62066. var radius = 1.0;
  62067. if (instance) {
  62068. radius = instance.radius;
  62069. }
  62070. if (options.radius !== undefined) {
  62071. radius = options.radius;
  62072. }
  62073. ;
  62074. var tessellation = options.tessellation || 64 | 0;
  62075. var radiusFunction = options.radiusFunction || null;
  62076. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  62077. var invertUV = options.invertUV || false;
  62078. var updatable = options.updatable;
  62079. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62080. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  62081. // tube geometry
  62082. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  62083. var tangents = path3D.getTangents();
  62084. var normals = path3D.getNormals();
  62085. var distances = path3D.getDistances();
  62086. var pi2 = Math.PI * 2;
  62087. var step = pi2 / tessellation * arc;
  62088. var returnRadius = function () { return radius; };
  62089. var radiusFunctionFinal = radiusFunction || returnRadius;
  62090. var circlePath;
  62091. var rad;
  62092. var normal;
  62093. var rotated;
  62094. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62095. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62096. for (var i = 0; i < path.length; i++) {
  62097. rad = radiusFunctionFinal(i, distances[i]); // current radius
  62098. circlePath = Array(); // current circle array
  62099. normal = normals[i]; // current normal
  62100. for (var t = 0; t < tessellation; t++) {
  62101. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  62102. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  62103. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  62104. rotated.scaleInPlace(rad).addInPlace(path[i]);
  62105. circlePath[t] = rotated;
  62106. }
  62107. circlePaths[index] = circlePath;
  62108. index++;
  62109. }
  62110. // cap
  62111. var capPath = function (nbPoints, pathIndex) {
  62112. var pointCap = Array();
  62113. for (var i = 0; i < nbPoints; i++) {
  62114. pointCap.push(path[pathIndex]);
  62115. }
  62116. return pointCap;
  62117. };
  62118. switch (cap) {
  62119. case BABYLON.Mesh.NO_CAP:
  62120. break;
  62121. case BABYLON.Mesh.CAP_START:
  62122. circlePaths[0] = capPath(tessellation, 0);
  62123. circlePaths[1] = circlePaths[2].slice(0);
  62124. break;
  62125. case BABYLON.Mesh.CAP_END:
  62126. circlePaths[index] = circlePaths[index - 1].slice(0);
  62127. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  62128. break;
  62129. case BABYLON.Mesh.CAP_ALL:
  62130. circlePaths[0] = capPath(tessellation, 0);
  62131. circlePaths[1] = circlePaths[2].slice(0);
  62132. circlePaths[index] = circlePaths[index - 1].slice(0);
  62133. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  62134. break;
  62135. default:
  62136. break;
  62137. }
  62138. return circlePaths;
  62139. };
  62140. var path3D;
  62141. var pathArray;
  62142. if (instance) { // tube update
  62143. var arc = options.arc || instance.arc;
  62144. path3D = (instance.path3D).update(path);
  62145. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  62146. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  62147. instance.path3D = path3D;
  62148. instance.pathArray = pathArray;
  62149. instance.arc = arc;
  62150. instance.radius = radius;
  62151. return instance;
  62152. }
  62153. // tube creation
  62154. path3D = new BABYLON.Path3D(path);
  62155. var newPathArray = new Array();
  62156. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62157. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  62158. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  62159. tube.pathArray = pathArray;
  62160. tube.path3D = path3D;
  62161. tube.tessellation = tessellation;
  62162. tube.cap = cap;
  62163. tube.arc = options.arc;
  62164. tube.radius = radius;
  62165. return tube;
  62166. };
  62167. /**
  62168. * Creates a polyhedron mesh
  62169. * * 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
  62170. * * The parameter `size` (positive float, default 1) sets the polygon size
  62171. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  62172. * * 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`
  62173. * * 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
  62174. * * 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)`)
  62175. * * 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
  62176. * * 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
  62177. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62178. * * 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
  62179. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62180. * @param name defines the name of the mesh
  62181. * @param options defines the options used to create the mesh
  62182. * @param scene defines the hosting scene
  62183. * @returns the polyhedron mesh
  62184. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  62185. */
  62186. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  62187. var polyhedron = new BABYLON.Mesh(name, scene);
  62188. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62189. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  62190. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  62191. vertexData.applyToMesh(polyhedron, options.updatable);
  62192. return polyhedron;
  62193. };
  62194. /**
  62195. * Creates a decal mesh.
  62196. * 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
  62197. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  62198. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  62199. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  62200. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  62201. * @param name defines the name of the mesh
  62202. * @param sourceMesh defines the mesh where the decal must be applied
  62203. * @param options defines the options used to create the mesh
  62204. * @param scene defines the hosting scene
  62205. * @returns the decal mesh
  62206. * @see http://doc.babylonjs.com/how_to/decals
  62207. */
  62208. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  62209. var indices = sourceMesh.getIndices();
  62210. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62211. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62212. var position = options.position || BABYLON.Vector3.Zero();
  62213. var normal = options.normal || BABYLON.Vector3.Up();
  62214. var size = options.size || BABYLON.Vector3.One();
  62215. var angle = options.angle || 0;
  62216. // Getting correct rotation
  62217. if (!normal) {
  62218. var target = new BABYLON.Vector3(0, 0, 1);
  62219. var camera = sourceMesh.getScene().activeCamera;
  62220. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  62221. normal = camera.globalPosition.subtract(cameraWorldTarget);
  62222. }
  62223. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  62224. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  62225. var pitch = Math.atan2(normal.y, len);
  62226. // Matrix
  62227. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  62228. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  62229. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  62230. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  62231. var vertexData = new BABYLON.VertexData();
  62232. vertexData.indices = [];
  62233. vertexData.positions = [];
  62234. vertexData.normals = [];
  62235. vertexData.uvs = [];
  62236. var currentVertexDataIndex = 0;
  62237. var extractDecalVector3 = function (indexId) {
  62238. var result = new BABYLON.PositionNormalVertex();
  62239. if (!indices || !positions || !normals) {
  62240. return result;
  62241. }
  62242. var vertexId = indices[indexId];
  62243. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  62244. // Send vector to decal local world
  62245. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  62246. // Get normal
  62247. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  62248. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  62249. return result;
  62250. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  62251. var clip = function (vertices, axis) {
  62252. if (vertices.length === 0) {
  62253. return vertices;
  62254. }
  62255. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  62256. var clipVertices = function (v0, v1) {
  62257. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  62258. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  62259. };
  62260. var result = new Array();
  62261. for (var index = 0; index < vertices.length; index += 3) {
  62262. var v1Out;
  62263. var v2Out;
  62264. var v3Out;
  62265. var total = 0;
  62266. var nV1 = null;
  62267. var nV2 = null;
  62268. var nV3 = null;
  62269. var nV4 = null;
  62270. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  62271. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  62272. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  62273. v1Out = d1 > 0;
  62274. v2Out = d2 > 0;
  62275. v3Out = d3 > 0;
  62276. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  62277. switch (total) {
  62278. case 0:
  62279. result.push(vertices[index]);
  62280. result.push(vertices[index + 1]);
  62281. result.push(vertices[index + 2]);
  62282. break;
  62283. case 1:
  62284. if (v1Out) {
  62285. nV1 = vertices[index + 1];
  62286. nV2 = vertices[index + 2];
  62287. nV3 = clipVertices(vertices[index], nV1);
  62288. nV4 = clipVertices(vertices[index], nV2);
  62289. }
  62290. if (v2Out) {
  62291. nV1 = vertices[index];
  62292. nV2 = vertices[index + 2];
  62293. nV3 = clipVertices(vertices[index + 1], nV1);
  62294. nV4 = clipVertices(vertices[index + 1], nV2);
  62295. result.push(nV3);
  62296. result.push(nV2.clone());
  62297. result.push(nV1.clone());
  62298. result.push(nV2.clone());
  62299. result.push(nV3.clone());
  62300. result.push(nV4);
  62301. break;
  62302. }
  62303. if (v3Out) {
  62304. nV1 = vertices[index];
  62305. nV2 = vertices[index + 1];
  62306. nV3 = clipVertices(vertices[index + 2], nV1);
  62307. nV4 = clipVertices(vertices[index + 2], nV2);
  62308. }
  62309. if (nV1 && nV2 && nV3 && nV4) {
  62310. result.push(nV1.clone());
  62311. result.push(nV2.clone());
  62312. result.push(nV3);
  62313. result.push(nV4);
  62314. result.push(nV3.clone());
  62315. result.push(nV2.clone());
  62316. }
  62317. break;
  62318. case 2:
  62319. if (!v1Out) {
  62320. nV1 = vertices[index].clone();
  62321. nV2 = clipVertices(nV1, vertices[index + 1]);
  62322. nV3 = clipVertices(nV1, vertices[index + 2]);
  62323. result.push(nV1);
  62324. result.push(nV2);
  62325. result.push(nV3);
  62326. }
  62327. if (!v2Out) {
  62328. nV1 = vertices[index + 1].clone();
  62329. nV2 = clipVertices(nV1, vertices[index + 2]);
  62330. nV3 = clipVertices(nV1, vertices[index]);
  62331. result.push(nV1);
  62332. result.push(nV2);
  62333. result.push(nV3);
  62334. }
  62335. if (!v3Out) {
  62336. nV1 = vertices[index + 2].clone();
  62337. nV2 = clipVertices(nV1, vertices[index]);
  62338. nV3 = clipVertices(nV1, vertices[index + 1]);
  62339. result.push(nV1);
  62340. result.push(nV2);
  62341. result.push(nV3);
  62342. }
  62343. break;
  62344. case 3:
  62345. break;
  62346. }
  62347. }
  62348. return result;
  62349. };
  62350. for (var index = 0; index < indices.length; index += 3) {
  62351. var faceVertices = new Array();
  62352. faceVertices.push(extractDecalVector3(index));
  62353. faceVertices.push(extractDecalVector3(index + 1));
  62354. faceVertices.push(extractDecalVector3(index + 2));
  62355. // Clip
  62356. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  62357. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  62358. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  62359. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  62360. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  62361. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  62362. if (faceVertices.length === 0) {
  62363. continue;
  62364. }
  62365. // Add UVs and get back to world
  62366. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  62367. var vertex = faceVertices[vIndex];
  62368. //TODO check for Int32Array | Uint32Array | Uint16Array
  62369. vertexData.indices.push(currentVertexDataIndex);
  62370. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  62371. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  62372. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  62373. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  62374. currentVertexDataIndex++;
  62375. }
  62376. }
  62377. // Return mesh
  62378. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  62379. vertexData.applyToMesh(decal);
  62380. decal.position = position.clone();
  62381. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  62382. return decal;
  62383. };
  62384. // Privates
  62385. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  62386. // extrusion geometry
  62387. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  62388. var tangents = path3D.getTangents();
  62389. var normals = path3D.getNormals();
  62390. var binormals = path3D.getBinormals();
  62391. var distances = path3D.getDistances();
  62392. var angle = 0;
  62393. var returnScale = function () { return scale !== null ? scale : 1; };
  62394. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  62395. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  62396. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  62397. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62398. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62399. for (var i = 0; i < curve.length; i++) {
  62400. var shapePath = new Array();
  62401. var angleStep = rotate(i, distances[i]);
  62402. var scaleRatio = scl(i, distances[i]);
  62403. for (var p = 0; p < shape.length; p++) {
  62404. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  62405. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  62406. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  62407. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  62408. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  62409. shapePath[p] = rotated;
  62410. }
  62411. shapePaths[index] = shapePath;
  62412. angle += angleStep;
  62413. index++;
  62414. }
  62415. // cap
  62416. var capPath = function (shapePath) {
  62417. var pointCap = Array();
  62418. var barycenter = BABYLON.Vector3.Zero();
  62419. var i;
  62420. for (i = 0; i < shapePath.length; i++) {
  62421. barycenter.addInPlace(shapePath[i]);
  62422. }
  62423. barycenter.scaleInPlace(1.0 / shapePath.length);
  62424. for (i = 0; i < shapePath.length; i++) {
  62425. pointCap.push(barycenter);
  62426. }
  62427. return pointCap;
  62428. };
  62429. switch (cap) {
  62430. case BABYLON.Mesh.NO_CAP:
  62431. break;
  62432. case BABYLON.Mesh.CAP_START:
  62433. shapePaths[0] = capPath(shapePaths[2]);
  62434. shapePaths[1] = shapePaths[2];
  62435. break;
  62436. case BABYLON.Mesh.CAP_END:
  62437. shapePaths[index] = shapePaths[index - 1];
  62438. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62439. break;
  62440. case BABYLON.Mesh.CAP_ALL:
  62441. shapePaths[0] = capPath(shapePaths[2]);
  62442. shapePaths[1] = shapePaths[2];
  62443. shapePaths[index] = shapePaths[index - 1];
  62444. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62445. break;
  62446. default:
  62447. break;
  62448. }
  62449. return shapePaths;
  62450. };
  62451. var path3D;
  62452. var pathArray;
  62453. if (instance) { // instance update
  62454. path3D = (instance.path3D).update(curve);
  62455. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  62456. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  62457. return instance;
  62458. }
  62459. // extruded shape creation
  62460. path3D = new BABYLON.Path3D(curve);
  62461. var newShapePaths = new Array();
  62462. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62463. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  62464. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  62465. extrudedGeneric.pathArray = pathArray;
  62466. extrudedGeneric.path3D = path3D;
  62467. extrudedGeneric.cap = cap;
  62468. return extrudedGeneric;
  62469. };
  62470. return MeshBuilder;
  62471. }());
  62472. BABYLON.MeshBuilder = MeshBuilder;
  62473. })(BABYLON || (BABYLON = {}));
  62474. //# sourceMappingURL=babylon.meshBuilder.js.map
  62475. var BABYLON;
  62476. (function (BABYLON) {
  62477. /**
  62478. * Draco compression (https://google.github.io/draco/)
  62479. *
  62480. * This class wraps the Draco module.
  62481. *
  62482. * **Encoder**
  62483. *
  62484. * The encoder is not currently implemented.
  62485. *
  62486. * **Decoder**
  62487. *
  62488. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62489. *
  62490. * To update the configuration, use the following code:
  62491. * ```javascript
  62492. * BABYLON.DracoCompression.Configuration = {
  62493. * decoder: {
  62494. * wasmUrl: "<url to the WebAssembly library>",
  62495. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62496. * fallbackUrl: "<url to the fallback JavaScript library>",
  62497. * }
  62498. * };
  62499. * ```
  62500. *
  62501. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  62502. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62503. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62504. *
  62505. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62506. * ```javascript
  62507. * var dracoCompression = new BABYLON.DracoCompression();
  62508. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62509. * [BABYLON.VertexBuffer.PositionKind]: 0
  62510. * });
  62511. * ```
  62512. *
  62513. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62514. */
  62515. var DracoCompression = /** @class */ (function () {
  62516. /**
  62517. * Constructor
  62518. */
  62519. function DracoCompression() {
  62520. }
  62521. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62522. /**
  62523. * Returns true if the decoder is available.
  62524. */
  62525. get: function () {
  62526. if (typeof DracoDecoderModule !== "undefined") {
  62527. return true;
  62528. }
  62529. var decoder = DracoCompression.Configuration.decoder;
  62530. if (decoder) {
  62531. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62532. return true;
  62533. }
  62534. if (decoder.fallbackUrl) {
  62535. return true;
  62536. }
  62537. }
  62538. return false;
  62539. },
  62540. enumerable: true,
  62541. configurable: true
  62542. });
  62543. /**
  62544. * Stop all async operations and release resources.
  62545. */
  62546. DracoCompression.prototype.dispose = function () {
  62547. };
  62548. /**
  62549. * Decode Draco compressed mesh data to vertex data.
  62550. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  62551. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  62552. * @returns A promise that resolves with the decoded vertex data
  62553. */
  62554. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  62555. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  62556. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  62557. var module = wrappedModule.module;
  62558. var vertexData = new BABYLON.VertexData();
  62559. var buffer = new module.DecoderBuffer();
  62560. buffer.Init(dataView, dataView.byteLength);
  62561. var decoder = new module.Decoder();
  62562. var geometry;
  62563. var status;
  62564. try {
  62565. var type = decoder.GetEncodedGeometryType(buffer);
  62566. switch (type) {
  62567. case module.TRIANGULAR_MESH:
  62568. geometry = new module.Mesh();
  62569. status = decoder.DecodeBufferToMesh(buffer, geometry);
  62570. break;
  62571. case module.POINT_CLOUD:
  62572. geometry = new module.PointCloud();
  62573. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  62574. break;
  62575. default:
  62576. throw new Error("Invalid geometry type " + type);
  62577. }
  62578. if (!status.ok() || !geometry.ptr) {
  62579. throw new Error(status.error_msg());
  62580. }
  62581. var numPoints = geometry.num_points();
  62582. if (type === module.TRIANGULAR_MESH) {
  62583. var numFaces = geometry.num_faces();
  62584. var faceIndices = new module.DracoInt32Array();
  62585. try {
  62586. var indices = new Uint32Array(numFaces * 3);
  62587. for (var i = 0; i < numFaces; i++) {
  62588. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62589. var offset = i * 3;
  62590. indices[offset + 0] = faceIndices.GetValue(0);
  62591. indices[offset + 1] = faceIndices.GetValue(1);
  62592. indices[offset + 2] = faceIndices.GetValue(2);
  62593. }
  62594. vertexData.indices = indices;
  62595. }
  62596. finally {
  62597. module.destroy(faceIndices);
  62598. }
  62599. }
  62600. for (var kind in attributes) {
  62601. var uniqueId = attributes[kind];
  62602. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62603. var dracoData = new module.DracoFloat32Array();
  62604. try {
  62605. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62606. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62607. for (var i = 0; i < babylonData.length; i++) {
  62608. babylonData[i] = dracoData.GetValue(i);
  62609. }
  62610. vertexData.set(babylonData, kind);
  62611. }
  62612. finally {
  62613. module.destroy(dracoData);
  62614. }
  62615. }
  62616. }
  62617. finally {
  62618. if (geometry) {
  62619. module.destroy(geometry);
  62620. }
  62621. module.destroy(decoder);
  62622. module.destroy(buffer);
  62623. }
  62624. return vertexData;
  62625. });
  62626. };
  62627. DracoCompression._GetDecoderModule = function () {
  62628. if (!DracoCompression._DecoderModulePromise) {
  62629. var promise = null;
  62630. var config_1 = {};
  62631. if (typeof DracoDecoderModule !== "undefined") {
  62632. promise = Promise.resolve();
  62633. }
  62634. else {
  62635. var decoder = DracoCompression.Configuration.decoder;
  62636. if (decoder) {
  62637. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62638. promise = Promise.all([
  62639. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62640. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62641. config_1.wasmBinary = data;
  62642. })
  62643. ]);
  62644. }
  62645. else if (decoder.fallbackUrl) {
  62646. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62647. }
  62648. }
  62649. }
  62650. if (!promise) {
  62651. throw new Error("Draco decoder module is not available");
  62652. }
  62653. DracoCompression._DecoderModulePromise = promise.then(function () {
  62654. return new Promise(function (resolve) {
  62655. config_1.onModuleLoaded = function (decoderModule) {
  62656. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62657. resolve({ module: decoderModule });
  62658. };
  62659. DracoDecoderModule(config_1);
  62660. });
  62661. });
  62662. }
  62663. return DracoCompression._DecoderModulePromise;
  62664. };
  62665. DracoCompression._LoadScriptAsync = function (url) {
  62666. return new Promise(function (resolve, reject) {
  62667. BABYLON.Tools.LoadScript(url, function () {
  62668. resolve();
  62669. }, function (message) {
  62670. reject(new Error(message));
  62671. });
  62672. });
  62673. };
  62674. DracoCompression._LoadFileAsync = function (url) {
  62675. return new Promise(function (resolve, reject) {
  62676. BABYLON.Tools.LoadFile(url, function (data) {
  62677. resolve(data);
  62678. }, undefined, undefined, true, function (request, exception) {
  62679. reject(exception);
  62680. });
  62681. });
  62682. };
  62683. /**
  62684. * The configuration. Defaults to the following urls:
  62685. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62686. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62687. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62688. */
  62689. DracoCompression.Configuration = {
  62690. decoder: {
  62691. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62692. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62693. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62694. }
  62695. };
  62696. return DracoCompression;
  62697. }());
  62698. BABYLON.DracoCompression = DracoCompression;
  62699. })(BABYLON || (BABYLON = {}));
  62700. //# sourceMappingURL=babylon.dracoCompression.js.map
  62701. var BABYLON;
  62702. (function (BABYLON) {
  62703. var AudioEngine = /** @class */ (function () {
  62704. function AudioEngine() {
  62705. this._audioContext = null;
  62706. this._audioContextInitialized = false;
  62707. this.canUseWebAudio = false;
  62708. this.WarnedWebAudioUnsupported = false;
  62709. this.unlocked = false;
  62710. this.isMP3supported = false;
  62711. this.isOGGsupported = false;
  62712. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62713. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62714. this.canUseWebAudio = true;
  62715. }
  62716. var audioElem = document.createElement('audio');
  62717. try {
  62718. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62719. this.isMP3supported = true;
  62720. }
  62721. }
  62722. catch (e) {
  62723. // protect error during capability check.
  62724. }
  62725. try {
  62726. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62727. this.isOGGsupported = true;
  62728. }
  62729. }
  62730. catch (e) {
  62731. // protect error during capability check.
  62732. }
  62733. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62734. this._unlockiOSaudio();
  62735. }
  62736. else {
  62737. this.unlocked = true;
  62738. }
  62739. }
  62740. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62741. get: function () {
  62742. if (!this._audioContextInitialized) {
  62743. this._initializeAudioContext();
  62744. }
  62745. return this._audioContext;
  62746. },
  62747. enumerable: true,
  62748. configurable: true
  62749. });
  62750. AudioEngine.prototype._unlockiOSaudio = function () {
  62751. var _this = this;
  62752. var unlockaudio = function () {
  62753. if (!_this.audioContext) {
  62754. return;
  62755. }
  62756. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62757. var source = _this.audioContext.createBufferSource();
  62758. source.buffer = buffer;
  62759. source.connect(_this.audioContext.destination);
  62760. source.start(0);
  62761. setTimeout(function () {
  62762. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62763. _this.unlocked = true;
  62764. window.removeEventListener('touchend', unlockaudio, false);
  62765. if (_this.onAudioUnlocked) {
  62766. _this.onAudioUnlocked();
  62767. }
  62768. }
  62769. }, 0);
  62770. };
  62771. window.addEventListener('touchend', unlockaudio, false);
  62772. };
  62773. AudioEngine.prototype._initializeAudioContext = function () {
  62774. try {
  62775. if (this.canUseWebAudio) {
  62776. this._audioContext = new AudioContext();
  62777. // create a global volume gain node
  62778. this.masterGain = this._audioContext.createGain();
  62779. this.masterGain.gain.value = 1;
  62780. this.masterGain.connect(this._audioContext.destination);
  62781. this._audioContextInitialized = true;
  62782. }
  62783. }
  62784. catch (e) {
  62785. this.canUseWebAudio = false;
  62786. BABYLON.Tools.Error("Web Audio: " + e.message);
  62787. }
  62788. };
  62789. AudioEngine.prototype.dispose = function () {
  62790. if (this.canUseWebAudio && this._audioContextInitialized) {
  62791. if (this._connectedAnalyser && this._audioContext) {
  62792. this._connectedAnalyser.stopDebugCanvas();
  62793. this._connectedAnalyser.dispose();
  62794. this.masterGain.disconnect();
  62795. this.masterGain.connect(this._audioContext.destination);
  62796. this._connectedAnalyser = null;
  62797. }
  62798. this.masterGain.gain.value = 1;
  62799. }
  62800. this.WarnedWebAudioUnsupported = false;
  62801. };
  62802. AudioEngine.prototype.getGlobalVolume = function () {
  62803. if (this.canUseWebAudio && this._audioContextInitialized) {
  62804. return this.masterGain.gain.value;
  62805. }
  62806. else {
  62807. return -1;
  62808. }
  62809. };
  62810. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62811. if (this.canUseWebAudio && this._audioContextInitialized) {
  62812. this.masterGain.gain.value = newVolume;
  62813. }
  62814. };
  62815. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62816. if (this._connectedAnalyser) {
  62817. this._connectedAnalyser.stopDebugCanvas();
  62818. }
  62819. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62820. this._connectedAnalyser = analyser;
  62821. this.masterGain.disconnect();
  62822. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62823. }
  62824. };
  62825. return AudioEngine;
  62826. }());
  62827. BABYLON.AudioEngine = AudioEngine;
  62828. })(BABYLON || (BABYLON = {}));
  62829. //# sourceMappingURL=babylon.audioEngine.js.map
  62830. var BABYLON;
  62831. (function (BABYLON) {
  62832. var Sound = /** @class */ (function () {
  62833. /**
  62834. * Create a sound and attach it to a scene
  62835. * @param name Name of your sound
  62836. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62837. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62838. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62839. */
  62840. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62841. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62842. var _this = this;
  62843. this.autoplay = false;
  62844. this.loop = false;
  62845. this.useCustomAttenuation = false;
  62846. this.spatialSound = false;
  62847. this.refDistance = 1;
  62848. this.rolloffFactor = 1;
  62849. this.maxDistance = 100;
  62850. this.distanceModel = "linear";
  62851. this._panningModel = "equalpower";
  62852. this._playbackRate = 1;
  62853. this._streaming = false;
  62854. this._startTime = 0;
  62855. this._startOffset = 0;
  62856. this._position = BABYLON.Vector3.Zero();
  62857. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62858. this._volume = 1;
  62859. this._isReadyToPlay = false;
  62860. this.isPlaying = false;
  62861. this.isPaused = false;
  62862. this._isDirectional = false;
  62863. // Used if you'd like to create a directional sound.
  62864. // If not set, the sound will be omnidirectional
  62865. this._coneInnerAngle = 360;
  62866. this._coneOuterAngle = 360;
  62867. this._coneOuterGain = 0;
  62868. this._isOutputConnected = false;
  62869. this._urlType = "Unknown";
  62870. this.name = name;
  62871. this._scene = scene;
  62872. this._readyToPlayCallback = readyToPlayCallback;
  62873. // Default custom attenuation function is a linear attenuation
  62874. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62875. if (currentDistance < maxDistance) {
  62876. return currentVolume * (1 - currentDistance / maxDistance);
  62877. }
  62878. else {
  62879. return 0;
  62880. }
  62881. };
  62882. if (options) {
  62883. this.autoplay = options.autoplay || false;
  62884. this.loop = options.loop || false;
  62885. // if volume === 0, we need another way to check this option
  62886. if (options.volume !== undefined) {
  62887. this._volume = options.volume;
  62888. }
  62889. this.spatialSound = options.spatialSound || false;
  62890. this.maxDistance = options.maxDistance || 100;
  62891. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62892. this.rolloffFactor = options.rolloffFactor || 1;
  62893. this.refDistance = options.refDistance || 1;
  62894. this.distanceModel = options.distanceModel || "linear";
  62895. this._playbackRate = options.playbackRate || 1;
  62896. this._streaming = options.streaming || false;
  62897. }
  62898. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62899. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62900. this._soundGain.gain.value = this._volume;
  62901. this._inputAudioNode = this._soundGain;
  62902. this._ouputAudioNode = this._soundGain;
  62903. if (this.spatialSound) {
  62904. this._createSpatialParameters();
  62905. }
  62906. this._scene.mainSoundTrack.AddSound(this);
  62907. var validParameter = true;
  62908. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62909. if (urlOrArrayBuffer) {
  62910. try {
  62911. if (typeof (urlOrArrayBuffer) === "string")
  62912. this._urlType = "String";
  62913. if (Array.isArray(urlOrArrayBuffer))
  62914. this._urlType = "Array";
  62915. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62916. this._urlType = "ArrayBuffer";
  62917. var urls = [];
  62918. var codecSupportedFound = false;
  62919. switch (this._urlType) {
  62920. case "ArrayBuffer":
  62921. if (urlOrArrayBuffer.byteLength > 0) {
  62922. codecSupportedFound = true;
  62923. this._soundLoaded(urlOrArrayBuffer);
  62924. }
  62925. break;
  62926. case "String":
  62927. urls.push(urlOrArrayBuffer);
  62928. case "Array":
  62929. if (urls.length === 0)
  62930. urls = urlOrArrayBuffer;
  62931. // If we found a supported format, we load it immediately and stop the loop
  62932. for (var i = 0; i < urls.length; i++) {
  62933. var url = urls[i];
  62934. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62935. codecSupportedFound = true;
  62936. }
  62937. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62938. codecSupportedFound = true;
  62939. }
  62940. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62941. codecSupportedFound = true;
  62942. }
  62943. if (url.indexOf("blob:") !== -1) {
  62944. codecSupportedFound = true;
  62945. }
  62946. if (codecSupportedFound) {
  62947. // Loading sound using XHR2
  62948. if (!this._streaming) {
  62949. this._scene._loadFile(url, function (data) {
  62950. _this._soundLoaded(data);
  62951. }, undefined, true, true, function (exception) {
  62952. if (exception) {
  62953. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62954. }
  62955. BABYLON.Tools.Error("Sound creation aborted.");
  62956. _this._scene.mainSoundTrack.RemoveSound(_this);
  62957. });
  62958. }
  62959. // Streaming sound using HTML5 Audio tag
  62960. else {
  62961. this._htmlAudioElement = new Audio(url);
  62962. this._htmlAudioElement.controls = false;
  62963. this._htmlAudioElement.loop = this.loop;
  62964. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62965. this._htmlAudioElement.preload = "auto";
  62966. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62967. _this._isReadyToPlay = true;
  62968. if (_this.autoplay) {
  62969. _this.play();
  62970. }
  62971. if (_this._readyToPlayCallback) {
  62972. _this._readyToPlayCallback();
  62973. }
  62974. });
  62975. document.body.appendChild(this._htmlAudioElement);
  62976. }
  62977. break;
  62978. }
  62979. }
  62980. break;
  62981. default:
  62982. validParameter = false;
  62983. break;
  62984. }
  62985. if (!validParameter) {
  62986. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62987. }
  62988. else {
  62989. if (!codecSupportedFound) {
  62990. this._isReadyToPlay = true;
  62991. // Simulating a ready to play event to avoid breaking code path
  62992. if (this._readyToPlayCallback) {
  62993. window.setTimeout(function () {
  62994. if (_this._readyToPlayCallback) {
  62995. _this._readyToPlayCallback();
  62996. }
  62997. }, 1000);
  62998. }
  62999. }
  63000. }
  63001. }
  63002. catch (ex) {
  63003. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  63004. this._scene.mainSoundTrack.RemoveSound(this);
  63005. }
  63006. }
  63007. }
  63008. else {
  63009. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  63010. this._scene.mainSoundTrack.AddSound(this);
  63011. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  63012. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  63013. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  63014. }
  63015. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  63016. if (this._readyToPlayCallback) {
  63017. window.setTimeout(function () {
  63018. if (_this._readyToPlayCallback) {
  63019. _this._readyToPlayCallback();
  63020. }
  63021. }, 1000);
  63022. }
  63023. }
  63024. }
  63025. Sound.prototype.dispose = function () {
  63026. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63027. if (this.isPlaying) {
  63028. this.stop();
  63029. }
  63030. this._isReadyToPlay = false;
  63031. if (this.soundTrackId === -1) {
  63032. this._scene.mainSoundTrack.RemoveSound(this);
  63033. }
  63034. else {
  63035. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  63036. }
  63037. if (this._soundGain) {
  63038. this._soundGain.disconnect();
  63039. this._soundGain = null;
  63040. }
  63041. if (this._soundPanner) {
  63042. this._soundPanner.disconnect();
  63043. this._soundPanner = null;
  63044. }
  63045. if (this._soundSource) {
  63046. this._soundSource.disconnect();
  63047. this._soundSource = null;
  63048. }
  63049. this._audioBuffer = null;
  63050. if (this._htmlAudioElement) {
  63051. this._htmlAudioElement.pause();
  63052. this._htmlAudioElement.src = "";
  63053. document.body.removeChild(this._htmlAudioElement);
  63054. }
  63055. if (this._connectedMesh && this._registerFunc) {
  63056. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63057. this._connectedMesh = null;
  63058. }
  63059. }
  63060. };
  63061. Sound.prototype.isReady = function () {
  63062. return this._isReadyToPlay;
  63063. };
  63064. Sound.prototype._soundLoaded = function (audioData) {
  63065. var _this = this;
  63066. if (!BABYLON.Engine.audioEngine.audioContext) {
  63067. return;
  63068. }
  63069. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  63070. _this._audioBuffer = buffer;
  63071. _this._isReadyToPlay = true;
  63072. if (_this.autoplay) {
  63073. _this.play();
  63074. }
  63075. if (_this._readyToPlayCallback) {
  63076. _this._readyToPlayCallback();
  63077. }
  63078. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  63079. };
  63080. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  63081. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63082. this._audioBuffer = audioBuffer;
  63083. this._isReadyToPlay = true;
  63084. }
  63085. };
  63086. Sound.prototype.updateOptions = function (options) {
  63087. if (options) {
  63088. this.loop = options.loop || this.loop;
  63089. this.maxDistance = options.maxDistance || this.maxDistance;
  63090. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  63091. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  63092. this.refDistance = options.refDistance || this.refDistance;
  63093. this.distanceModel = options.distanceModel || this.distanceModel;
  63094. this._playbackRate = options.playbackRate || this._playbackRate;
  63095. this._updateSpatialParameters();
  63096. if (this.isPlaying) {
  63097. if (this._streaming) {
  63098. this._htmlAudioElement.playbackRate = this._playbackRate;
  63099. }
  63100. else {
  63101. if (this._soundSource) {
  63102. this._soundSource.playbackRate.value = this._playbackRate;
  63103. }
  63104. }
  63105. }
  63106. }
  63107. };
  63108. Sound.prototype._createSpatialParameters = function () {
  63109. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63110. if (this._scene.headphone) {
  63111. this._panningModel = "HRTF";
  63112. }
  63113. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  63114. this._updateSpatialParameters();
  63115. this._soundPanner.connect(this._ouputAudioNode);
  63116. this._inputAudioNode = this._soundPanner;
  63117. }
  63118. };
  63119. Sound.prototype._updateSpatialParameters = function () {
  63120. if (this.spatialSound && this._soundPanner) {
  63121. if (this.useCustomAttenuation) {
  63122. // Tricks to disable in a way embedded Web Audio attenuation
  63123. this._soundPanner.distanceModel = "linear";
  63124. this._soundPanner.maxDistance = Number.MAX_VALUE;
  63125. this._soundPanner.refDistance = 1;
  63126. this._soundPanner.rolloffFactor = 1;
  63127. this._soundPanner.panningModel = this._panningModel;
  63128. }
  63129. else {
  63130. this._soundPanner.distanceModel = this.distanceModel;
  63131. this._soundPanner.maxDistance = this.maxDistance;
  63132. this._soundPanner.refDistance = this.refDistance;
  63133. this._soundPanner.rolloffFactor = this.rolloffFactor;
  63134. this._soundPanner.panningModel = this._panningModel;
  63135. }
  63136. }
  63137. };
  63138. Sound.prototype.switchPanningModelToHRTF = function () {
  63139. this._panningModel = "HRTF";
  63140. this._switchPanningModel();
  63141. };
  63142. Sound.prototype.switchPanningModelToEqualPower = function () {
  63143. this._panningModel = "equalpower";
  63144. this._switchPanningModel();
  63145. };
  63146. Sound.prototype._switchPanningModel = function () {
  63147. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  63148. this._soundPanner.panningModel = this._panningModel;
  63149. }
  63150. };
  63151. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  63152. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63153. if (this._isOutputConnected) {
  63154. this._ouputAudioNode.disconnect();
  63155. }
  63156. this._ouputAudioNode.connect(soundTrackAudioNode);
  63157. this._isOutputConnected = true;
  63158. }
  63159. };
  63160. /**
  63161. * Transform this sound into a directional source
  63162. * @param coneInnerAngle Size of the inner cone in degree
  63163. * @param coneOuterAngle Size of the outer cone in degree
  63164. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  63165. */
  63166. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  63167. if (coneOuterAngle < coneInnerAngle) {
  63168. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  63169. return;
  63170. }
  63171. this._coneInnerAngle = coneInnerAngle;
  63172. this._coneOuterAngle = coneOuterAngle;
  63173. this._coneOuterGain = coneOuterGain;
  63174. this._isDirectional = true;
  63175. if (this.isPlaying && this.loop) {
  63176. this.stop();
  63177. this.play();
  63178. }
  63179. };
  63180. Sound.prototype.setPosition = function (newPosition) {
  63181. this._position = newPosition;
  63182. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  63183. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  63184. }
  63185. };
  63186. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  63187. this._localDirection = newLocalDirection;
  63188. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  63189. this._updateDirection();
  63190. }
  63191. };
  63192. Sound.prototype._updateDirection = function () {
  63193. if (!this._connectedMesh || !this._soundPanner) {
  63194. return;
  63195. }
  63196. var mat = this._connectedMesh.getWorldMatrix();
  63197. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  63198. direction.normalize();
  63199. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  63200. };
  63201. Sound.prototype.updateDistanceFromListener = function () {
  63202. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  63203. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  63204. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  63205. }
  63206. };
  63207. Sound.prototype.setAttenuationFunction = function (callback) {
  63208. this._customAttenuationFunction = callback;
  63209. };
  63210. /**
  63211. * Play the sound
  63212. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  63213. * @param offset (optional) Start the sound setting it at a specific time
  63214. */
  63215. Sound.prototype.play = function (time, offset) {
  63216. var _this = this;
  63217. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  63218. try {
  63219. if (this._startOffset < 0) {
  63220. time = -this._startOffset;
  63221. this._startOffset = 0;
  63222. }
  63223. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  63224. if (!this._soundSource || !this._streamingSource) {
  63225. if (this.spatialSound && this._soundPanner) {
  63226. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  63227. if (this._isDirectional) {
  63228. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  63229. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  63230. this._soundPanner.coneOuterGain = this._coneOuterGain;
  63231. if (this._connectedMesh) {
  63232. this._updateDirection();
  63233. }
  63234. else {
  63235. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  63236. }
  63237. }
  63238. }
  63239. }
  63240. if (this._streaming) {
  63241. if (!this._streamingSource) {
  63242. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  63243. this._htmlAudioElement.onended = function () { _this._onended(); };
  63244. this._htmlAudioElement.playbackRate = this._playbackRate;
  63245. }
  63246. this._streamingSource.disconnect();
  63247. this._streamingSource.connect(this._inputAudioNode);
  63248. this._htmlAudioElement.play();
  63249. }
  63250. else {
  63251. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  63252. this._soundSource.buffer = this._audioBuffer;
  63253. this._soundSource.connect(this._inputAudioNode);
  63254. this._soundSource.loop = this.loop;
  63255. this._soundSource.playbackRate.value = this._playbackRate;
  63256. this._soundSource.onended = function () { _this._onended(); };
  63257. if (this._soundSource.buffer) {
  63258. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  63259. }
  63260. }
  63261. this._startTime = startTime;
  63262. this.isPlaying = true;
  63263. this.isPaused = false;
  63264. }
  63265. catch (ex) {
  63266. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  63267. }
  63268. }
  63269. };
  63270. Sound.prototype._onended = function () {
  63271. this.isPlaying = false;
  63272. if (this.onended) {
  63273. this.onended();
  63274. }
  63275. };
  63276. /**
  63277. * Stop the sound
  63278. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  63279. */
  63280. Sound.prototype.stop = function (time) {
  63281. if (this.isPlaying) {
  63282. if (this._streaming) {
  63283. this._htmlAudioElement.pause();
  63284. // Test needed for Firefox or it will generate an Invalid State Error
  63285. if (this._htmlAudioElement.currentTime > 0) {
  63286. this._htmlAudioElement.currentTime = 0;
  63287. }
  63288. }
  63289. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  63290. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  63291. this._soundSource.stop(stopTime);
  63292. this._soundSource.onended = function () { };
  63293. if (!this.isPaused) {
  63294. this._startOffset = 0;
  63295. }
  63296. }
  63297. this.isPlaying = false;
  63298. }
  63299. };
  63300. Sound.prototype.pause = function () {
  63301. if (this.isPlaying) {
  63302. this.isPaused = true;
  63303. if (this._streaming) {
  63304. this._htmlAudioElement.pause();
  63305. }
  63306. else if (BABYLON.Engine.audioEngine.audioContext) {
  63307. this.stop(0);
  63308. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  63309. }
  63310. }
  63311. };
  63312. Sound.prototype.setVolume = function (newVolume, time) {
  63313. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  63314. if (time && BABYLON.Engine.audioEngine.audioContext) {
  63315. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  63316. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  63317. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  63318. }
  63319. else {
  63320. this._soundGain.gain.value = newVolume;
  63321. }
  63322. }
  63323. this._volume = newVolume;
  63324. };
  63325. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  63326. this._playbackRate = newPlaybackRate;
  63327. if (this.isPlaying) {
  63328. if (this._streaming) {
  63329. this._htmlAudioElement.playbackRate = this._playbackRate;
  63330. }
  63331. else if (this._soundSource) {
  63332. this._soundSource.playbackRate.value = this._playbackRate;
  63333. }
  63334. }
  63335. };
  63336. Sound.prototype.getVolume = function () {
  63337. return this._volume;
  63338. };
  63339. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  63340. var _this = this;
  63341. if (this._connectedMesh && this._registerFunc) {
  63342. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63343. this._registerFunc = null;
  63344. }
  63345. this._connectedMesh = meshToConnectTo;
  63346. if (!this.spatialSound) {
  63347. this.spatialSound = true;
  63348. this._createSpatialParameters();
  63349. if (this.isPlaying && this.loop) {
  63350. this.stop();
  63351. this.play();
  63352. }
  63353. }
  63354. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  63355. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  63356. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  63357. };
  63358. Sound.prototype.detachFromMesh = function () {
  63359. if (this._connectedMesh && this._registerFunc) {
  63360. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63361. this._registerFunc = null;
  63362. this._connectedMesh = null;
  63363. }
  63364. };
  63365. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  63366. if (!node.getBoundingInfo) {
  63367. return;
  63368. }
  63369. var mesh = node;
  63370. var boundingInfo = mesh.getBoundingInfo();
  63371. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  63372. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  63373. this._updateDirection();
  63374. }
  63375. };
  63376. Sound.prototype.clone = function () {
  63377. var _this = this;
  63378. if (!this._streaming) {
  63379. var setBufferAndRun = function () {
  63380. if (_this._isReadyToPlay) {
  63381. clonedSound._audioBuffer = _this.getAudioBuffer();
  63382. clonedSound._isReadyToPlay = true;
  63383. if (clonedSound.autoplay) {
  63384. clonedSound.play();
  63385. }
  63386. }
  63387. else {
  63388. window.setTimeout(setBufferAndRun, 300);
  63389. }
  63390. };
  63391. var currentOptions = {
  63392. autoplay: this.autoplay, loop: this.loop,
  63393. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  63394. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  63395. refDistance: this.refDistance, distanceModel: this.distanceModel
  63396. };
  63397. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  63398. if (this.useCustomAttenuation) {
  63399. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  63400. }
  63401. clonedSound.setPosition(this._position);
  63402. clonedSound.setPlaybackRate(this._playbackRate);
  63403. setBufferAndRun();
  63404. return clonedSound;
  63405. }
  63406. // Can't clone a streaming sound
  63407. else {
  63408. return null;
  63409. }
  63410. };
  63411. Sound.prototype.getAudioBuffer = function () {
  63412. return this._audioBuffer;
  63413. };
  63414. Sound.prototype.serialize = function () {
  63415. var serializationObject = {
  63416. name: this.name,
  63417. url: this.name,
  63418. autoplay: this.autoplay,
  63419. loop: this.loop,
  63420. volume: this._volume,
  63421. spatialSound: this.spatialSound,
  63422. maxDistance: this.maxDistance,
  63423. rolloffFactor: this.rolloffFactor,
  63424. refDistance: this.refDistance,
  63425. distanceModel: this.distanceModel,
  63426. playbackRate: this._playbackRate,
  63427. panningModel: this._panningModel,
  63428. soundTrackId: this.soundTrackId
  63429. };
  63430. if (this.spatialSound) {
  63431. if (this._connectedMesh)
  63432. serializationObject.connectedMeshId = this._connectedMesh.id;
  63433. serializationObject.position = this._position.asArray();
  63434. serializationObject.refDistance = this.refDistance;
  63435. serializationObject.distanceModel = this.distanceModel;
  63436. serializationObject.isDirectional = this._isDirectional;
  63437. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  63438. serializationObject.coneInnerAngle = this._coneInnerAngle;
  63439. serializationObject.coneOuterAngle = this._coneOuterAngle;
  63440. serializationObject.coneOuterGain = this._coneOuterGain;
  63441. }
  63442. return serializationObject;
  63443. };
  63444. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  63445. var soundName = parsedSound.name;
  63446. var soundUrl;
  63447. if (parsedSound.url) {
  63448. soundUrl = rootUrl + parsedSound.url;
  63449. }
  63450. else {
  63451. soundUrl = rootUrl + soundName;
  63452. }
  63453. var options = {
  63454. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  63455. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  63456. rolloffFactor: parsedSound.rolloffFactor,
  63457. refDistance: parsedSound.refDistance,
  63458. distanceModel: parsedSound.distanceModel,
  63459. playbackRate: parsedSound.playbackRate
  63460. };
  63461. var newSound;
  63462. if (!sourceSound) {
  63463. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  63464. scene._addPendingData(newSound);
  63465. }
  63466. else {
  63467. var setBufferAndRun = function () {
  63468. if (sourceSound._isReadyToPlay) {
  63469. newSound._audioBuffer = sourceSound.getAudioBuffer();
  63470. newSound._isReadyToPlay = true;
  63471. if (newSound.autoplay) {
  63472. newSound.play();
  63473. }
  63474. }
  63475. else {
  63476. window.setTimeout(setBufferAndRun, 300);
  63477. }
  63478. };
  63479. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  63480. setBufferAndRun();
  63481. }
  63482. if (parsedSound.position) {
  63483. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  63484. newSound.setPosition(soundPosition);
  63485. }
  63486. if (parsedSound.isDirectional) {
  63487. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63488. if (parsedSound.localDirectionToMesh) {
  63489. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63490. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63491. }
  63492. }
  63493. if (parsedSound.connectedMeshId) {
  63494. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63495. if (connectedMesh) {
  63496. newSound.attachToMesh(connectedMesh);
  63497. }
  63498. }
  63499. return newSound;
  63500. };
  63501. return Sound;
  63502. }());
  63503. BABYLON.Sound = Sound;
  63504. })(BABYLON || (BABYLON = {}));
  63505. //# sourceMappingURL=babylon.sound.js.map
  63506. var BABYLON;
  63507. (function (BABYLON) {
  63508. var SoundTrack = /** @class */ (function () {
  63509. function SoundTrack(scene, options) {
  63510. this.id = -1;
  63511. this._isMainTrack = false;
  63512. this._isInitialized = false;
  63513. this._scene = scene;
  63514. this.soundCollection = new Array();
  63515. this._options = options;
  63516. if (!this._isMainTrack) {
  63517. this._scene.soundTracks.push(this);
  63518. this.id = this._scene.soundTracks.length - 1;
  63519. }
  63520. }
  63521. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  63522. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63523. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  63524. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  63525. if (this._options) {
  63526. if (this._options.volume) {
  63527. this._outputAudioNode.gain.value = this._options.volume;
  63528. }
  63529. if (this._options.mainTrack) {
  63530. this._isMainTrack = this._options.mainTrack;
  63531. }
  63532. }
  63533. this._isInitialized = true;
  63534. }
  63535. };
  63536. SoundTrack.prototype.dispose = function () {
  63537. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63538. if (this._connectedAnalyser) {
  63539. this._connectedAnalyser.stopDebugCanvas();
  63540. }
  63541. while (this.soundCollection.length) {
  63542. this.soundCollection[0].dispose();
  63543. }
  63544. if (this._outputAudioNode) {
  63545. this._outputAudioNode.disconnect();
  63546. }
  63547. this._outputAudioNode = null;
  63548. }
  63549. };
  63550. SoundTrack.prototype.AddSound = function (sound) {
  63551. if (!this._isInitialized) {
  63552. this._initializeSoundTrackAudioGraph();
  63553. }
  63554. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63555. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  63556. }
  63557. if (sound.soundTrackId) {
  63558. if (sound.soundTrackId === -1) {
  63559. this._scene.mainSoundTrack.RemoveSound(sound);
  63560. }
  63561. else {
  63562. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  63563. }
  63564. }
  63565. this.soundCollection.push(sound);
  63566. sound.soundTrackId = this.id;
  63567. };
  63568. SoundTrack.prototype.RemoveSound = function (sound) {
  63569. var index = this.soundCollection.indexOf(sound);
  63570. if (index !== -1) {
  63571. this.soundCollection.splice(index, 1);
  63572. }
  63573. };
  63574. SoundTrack.prototype.setVolume = function (newVolume) {
  63575. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63576. this._outputAudioNode.gain.value = newVolume;
  63577. }
  63578. };
  63579. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63580. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63581. for (var i = 0; i < this.soundCollection.length; i++) {
  63582. this.soundCollection[i].switchPanningModelToHRTF();
  63583. }
  63584. }
  63585. };
  63586. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63587. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63588. for (var i = 0; i < this.soundCollection.length; i++) {
  63589. this.soundCollection[i].switchPanningModelToEqualPower();
  63590. }
  63591. }
  63592. };
  63593. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63594. if (this._connectedAnalyser) {
  63595. this._connectedAnalyser.stopDebugCanvas();
  63596. }
  63597. this._connectedAnalyser = analyser;
  63598. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63599. this._outputAudioNode.disconnect();
  63600. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63601. }
  63602. };
  63603. return SoundTrack;
  63604. }());
  63605. BABYLON.SoundTrack = SoundTrack;
  63606. })(BABYLON || (BABYLON = {}));
  63607. //# sourceMappingURL=babylon.soundtrack.js.map
  63608. var BABYLON;
  63609. (function (BABYLON) {
  63610. /**
  63611. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63612. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63613. */
  63614. var Analyser = /** @class */ (function () {
  63615. /**
  63616. * Creates a new analyser
  63617. * @param scene defines hosting scene
  63618. */
  63619. function Analyser(scene) {
  63620. /**
  63621. * Gets or sets the smoothing
  63622. * @ignorenaming
  63623. */
  63624. this.SMOOTHING = 0.75;
  63625. /**
  63626. * Gets or sets the FFT table size
  63627. * @ignorenaming
  63628. */
  63629. this.FFT_SIZE = 512;
  63630. /**
  63631. * Gets or sets the bar graph amplitude
  63632. * @ignorenaming
  63633. */
  63634. this.BARGRAPHAMPLITUDE = 256;
  63635. /**
  63636. * Gets or sets the position of the debug canvas
  63637. * @ignorenaming
  63638. */
  63639. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63640. /**
  63641. * Gets or sets the debug canvas size
  63642. * @ignorenaming
  63643. */
  63644. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63645. this._scene = scene;
  63646. this._audioEngine = BABYLON.Engine.audioEngine;
  63647. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63648. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63649. this._webAudioAnalyser.minDecibels = -140;
  63650. this._webAudioAnalyser.maxDecibels = 0;
  63651. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63652. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63653. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63654. }
  63655. }
  63656. /**
  63657. * Get the number of data values you will have to play with for the visualization
  63658. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63659. * @returns a number
  63660. */
  63661. Analyser.prototype.getFrequencyBinCount = function () {
  63662. if (this._audioEngine.canUseWebAudio) {
  63663. return this._webAudioAnalyser.frequencyBinCount;
  63664. }
  63665. else {
  63666. return 0;
  63667. }
  63668. };
  63669. /**
  63670. * Gets the current frequency data as a byte array
  63671. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63672. * @returns a Uint8Array
  63673. */
  63674. Analyser.prototype.getByteFrequencyData = function () {
  63675. if (this._audioEngine.canUseWebAudio) {
  63676. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63677. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63678. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63679. }
  63680. return this._byteFreqs;
  63681. };
  63682. /**
  63683. * Gets the current waveform as a byte array
  63684. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63685. * @returns a Uint8Array
  63686. */
  63687. Analyser.prototype.getByteTimeDomainData = function () {
  63688. if (this._audioEngine.canUseWebAudio) {
  63689. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63690. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63691. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63692. }
  63693. return this._byteTime;
  63694. };
  63695. /**
  63696. * Gets the current frequency data as a float array
  63697. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63698. * @returns a Float32Array
  63699. */
  63700. Analyser.prototype.getFloatFrequencyData = function () {
  63701. if (this._audioEngine.canUseWebAudio) {
  63702. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63703. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63704. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63705. }
  63706. return this._floatFreqs;
  63707. };
  63708. /**
  63709. * Renders the debug canvas
  63710. */
  63711. Analyser.prototype.drawDebugCanvas = function () {
  63712. var _this = this;
  63713. if (this._audioEngine.canUseWebAudio) {
  63714. if (!this._debugCanvas) {
  63715. this._debugCanvas = document.createElement("canvas");
  63716. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63717. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63718. this._debugCanvas.style.position = "absolute";
  63719. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63720. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63721. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63722. document.body.appendChild(this._debugCanvas);
  63723. this._registerFunc = function () {
  63724. _this.drawDebugCanvas();
  63725. };
  63726. this._scene.registerBeforeRender(this._registerFunc);
  63727. }
  63728. if (this._registerFunc && this._debugCanvasContext) {
  63729. var workingArray = this.getByteFrequencyData();
  63730. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63731. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63732. // Draw the frequency domain chart.
  63733. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63734. var value = workingArray[i];
  63735. var percent = value / this.BARGRAPHAMPLITUDE;
  63736. var height = this.DEBUGCANVASSIZE.height * percent;
  63737. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63738. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63739. var hue = i / this.getFrequencyBinCount() * 360;
  63740. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63741. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63742. }
  63743. }
  63744. }
  63745. };
  63746. /**
  63747. * Stops rendering the debug canvas and removes it
  63748. */
  63749. Analyser.prototype.stopDebugCanvas = function () {
  63750. if (this._debugCanvas) {
  63751. if (this._registerFunc) {
  63752. this._scene.unregisterBeforeRender(this._registerFunc);
  63753. this._registerFunc = null;
  63754. }
  63755. document.body.removeChild(this._debugCanvas);
  63756. this._debugCanvas = null;
  63757. this._debugCanvasContext = null;
  63758. }
  63759. };
  63760. /**
  63761. * Connects two audio nodes
  63762. * @param inputAudioNode defines first node to connect
  63763. * @param outputAudioNode defines second node to connect
  63764. */
  63765. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63766. if (this._audioEngine.canUseWebAudio) {
  63767. inputAudioNode.connect(this._webAudioAnalyser);
  63768. this._webAudioAnalyser.connect(outputAudioNode);
  63769. }
  63770. };
  63771. /**
  63772. * Releases all associated resources
  63773. */
  63774. Analyser.prototype.dispose = function () {
  63775. if (this._audioEngine.canUseWebAudio) {
  63776. this._webAudioAnalyser.disconnect();
  63777. }
  63778. };
  63779. return Analyser;
  63780. }());
  63781. BABYLON.Analyser = Analyser;
  63782. })(BABYLON || (BABYLON = {}));
  63783. //# sourceMappingURL=babylon.analyser.js.map
  63784. var BABYLON;
  63785. (function (BABYLON) {
  63786. var CubeTexture = /** @class */ (function (_super) {
  63787. __extends(CubeTexture, _super);
  63788. /**
  63789. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63790. * as prefiltered data.
  63791. * @param rootUrl defines the url of the texture or the root name of the six images
  63792. * @param scene defines the scene the texture is attached to
  63793. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63794. * @param noMipmap defines if mipmaps should be created or not
  63795. * @param files defines the six files to load for the different faces
  63796. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63797. * @param onError defines a callback triggered in case of error during load
  63798. * @param format defines the internal format to use for the texture once loaded
  63799. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63800. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63801. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63802. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63803. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63804. * @return the cube texture
  63805. */
  63806. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  63807. if (extensions === void 0) { extensions = null; }
  63808. if (noMipmap === void 0) { noMipmap = false; }
  63809. if (files === void 0) { files = null; }
  63810. if (onLoad === void 0) { onLoad = null; }
  63811. if (onError === void 0) { onError = null; }
  63812. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63813. if (prefiltered === void 0) { prefiltered = false; }
  63814. if (forcedExtension === void 0) { forcedExtension = null; }
  63815. if (createPolynomials === void 0) { createPolynomials = false; }
  63816. if (lodScale === void 0) { lodScale = 0.8; }
  63817. if (lodOffset === void 0) { lodOffset = 0; }
  63818. var _this = _super.call(this, scene) || this;
  63819. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63820. /**
  63821. * Gets or sets the center of the bounding box associated with the cube texture
  63822. * It must define where the camera used to render the texture was set
  63823. */
  63824. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63825. _this._rotationY = 0;
  63826. /** @hidden */
  63827. _this._prefiltered = false;
  63828. _this.name = rootUrl;
  63829. _this.url = rootUrl;
  63830. _this._noMipmap = noMipmap;
  63831. _this.hasAlpha = false;
  63832. _this._format = format;
  63833. _this.isCube = true;
  63834. _this._textureMatrix = BABYLON.Matrix.Identity();
  63835. _this._createPolynomials = createPolynomials;
  63836. if (!rootUrl && !files) {
  63837. return _this;
  63838. }
  63839. var lastDot = rootUrl.lastIndexOf(".");
  63840. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63841. var isDDS = (extension === ".dds");
  63842. var isEnv = (extension === ".env");
  63843. if (isEnv) {
  63844. _this.gammaSpace = false;
  63845. _this._prefiltered = false;
  63846. }
  63847. else {
  63848. _this._prefiltered = prefiltered;
  63849. if (prefiltered) {
  63850. _this.gammaSpace = false;
  63851. }
  63852. }
  63853. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63854. if (!files) {
  63855. if (!isEnv && !isDDS && !extensions) {
  63856. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63857. }
  63858. files = [];
  63859. if (extensions) {
  63860. for (var index = 0; index < extensions.length; index++) {
  63861. files.push(rootUrl + extensions[index]);
  63862. }
  63863. }
  63864. }
  63865. _this._files = files;
  63866. if (!_this._texture) {
  63867. if (!scene.useDelayedTextureLoading) {
  63868. if (prefiltered) {
  63869. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63870. }
  63871. else {
  63872. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  63873. }
  63874. }
  63875. else {
  63876. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63877. }
  63878. }
  63879. else if (onLoad) {
  63880. if (_this._texture.isReady) {
  63881. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63882. }
  63883. else {
  63884. _this._texture.onLoadedObservable.add(onLoad);
  63885. }
  63886. }
  63887. return _this;
  63888. }
  63889. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63890. get: function () {
  63891. return this._boundingBoxSize;
  63892. },
  63893. /**
  63894. * Gets or sets the size of the bounding box associated with the cube texture
  63895. * When defined, the cubemap will switch to local mode
  63896. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63897. * @example https://www.babylonjs-playground.com/#RNASML
  63898. */
  63899. set: function (value) {
  63900. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63901. return;
  63902. }
  63903. this._boundingBoxSize = value;
  63904. var scene = this.getScene();
  63905. if (scene) {
  63906. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63907. }
  63908. },
  63909. enumerable: true,
  63910. configurable: true
  63911. });
  63912. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63913. /**
  63914. * Gets texture matrix rotation angle around Y axis radians.
  63915. */
  63916. get: function () {
  63917. return this._rotationY;
  63918. },
  63919. /**
  63920. * Sets texture matrix rotation angle around Y axis in radians.
  63921. */
  63922. set: function (value) {
  63923. this._rotationY = value;
  63924. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63925. },
  63926. enumerable: true,
  63927. configurable: true
  63928. });
  63929. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63930. var rootUrlKey = "";
  63931. files.forEach(function (url) { return rootUrlKey += url; });
  63932. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63933. };
  63934. /**
  63935. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63936. * @param url defines the url of the prefiltered texture
  63937. * @param scene defines the scene the texture is attached to
  63938. * @param forcedExtension defines the extension of the file if different from the url
  63939. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63940. * @return the prefiltered texture
  63941. */
  63942. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63943. if (forcedExtension === void 0) { forcedExtension = null; }
  63944. if (createPolynomials === void 0) { createPolynomials = true; }
  63945. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63946. };
  63947. // Methods
  63948. CubeTexture.prototype.delayLoad = function () {
  63949. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63950. return;
  63951. }
  63952. var scene = this.getScene();
  63953. if (!scene) {
  63954. return;
  63955. }
  63956. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63957. this._texture = this._getFromCache(this.url, this._noMipmap);
  63958. if (!this._texture) {
  63959. if (this._prefiltered) {
  63960. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63961. }
  63962. else {
  63963. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63964. }
  63965. }
  63966. };
  63967. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63968. return this._textureMatrix;
  63969. };
  63970. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63971. this._textureMatrix = value;
  63972. };
  63973. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63974. var texture = BABYLON.SerializationHelper.Parse(function () {
  63975. var prefiltered = false;
  63976. if (parsedTexture.prefiltered) {
  63977. prefiltered = parsedTexture.prefiltered;
  63978. }
  63979. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63980. }, parsedTexture, scene);
  63981. // Local Cubemaps
  63982. if (parsedTexture.boundingBoxPosition) {
  63983. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63984. }
  63985. if (parsedTexture.boundingBoxSize) {
  63986. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63987. }
  63988. // Animations
  63989. if (parsedTexture.animations) {
  63990. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63991. var parsedAnimation = parsedTexture.animations[animationIndex];
  63992. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63993. }
  63994. }
  63995. return texture;
  63996. };
  63997. CubeTexture.prototype.clone = function () {
  63998. var _this = this;
  63999. return BABYLON.SerializationHelper.Clone(function () {
  64000. var scene = _this.getScene();
  64001. if (!scene) {
  64002. return _this;
  64003. }
  64004. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  64005. }, this);
  64006. };
  64007. __decorate([
  64008. BABYLON.serialize("rotationY")
  64009. ], CubeTexture.prototype, "_rotationY", void 0);
  64010. return CubeTexture;
  64011. }(BABYLON.BaseTexture));
  64012. BABYLON.CubeTexture = CubeTexture;
  64013. })(BABYLON || (BABYLON = {}));
  64014. //# sourceMappingURL=babylon.cubeTexture.js.map
  64015. var BABYLON;
  64016. (function (BABYLON) {
  64017. var RenderTargetTexture = /** @class */ (function (_super) {
  64018. __extends(RenderTargetTexture, _super);
  64019. /**
  64020. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  64021. * or used a shadow, depth texture...
  64022. * @param name The friendly name of the texture
  64023. * @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)
  64024. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  64025. * @param generateMipMaps True if mip maps need to be generated after render.
  64026. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  64027. * @param type The type of the buffer in the RTT (int, half float, float...)
  64028. * @param isCube True if a cube texture needs to be created
  64029. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  64030. * @param generateDepthBuffer True to generate a depth buffer
  64031. * @param generateStencilBuffer True to generate a stencil buffer
  64032. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  64033. */
  64034. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  64035. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  64036. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64037. if (isCube === void 0) { isCube = false; }
  64038. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64039. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64040. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  64041. if (isMulti === void 0) { isMulti = false; }
  64042. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  64043. _this.isCube = isCube;
  64044. /**
  64045. * Use this list to define the list of mesh you want to render.
  64046. */
  64047. _this.renderList = new Array();
  64048. _this.renderParticles = true;
  64049. _this.renderSprites = false;
  64050. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  64051. _this.ignoreCameraViewport = false;
  64052. // Events
  64053. /**
  64054. * An event triggered when the texture is unbind.
  64055. */
  64056. _this.onBeforeBindObservable = new BABYLON.Observable();
  64057. /**
  64058. * An event triggered when the texture is unbind.
  64059. */
  64060. _this.onAfterUnbindObservable = new BABYLON.Observable();
  64061. /**
  64062. * An event triggered before rendering the texture
  64063. */
  64064. _this.onBeforeRenderObservable = new BABYLON.Observable();
  64065. /**
  64066. * An event triggered after rendering the texture
  64067. */
  64068. _this.onAfterRenderObservable = new BABYLON.Observable();
  64069. /**
  64070. * An event triggered after the texture clear
  64071. */
  64072. _this.onClearObservable = new BABYLON.Observable();
  64073. _this._currentRefreshId = -1;
  64074. _this._refreshRate = 1;
  64075. _this._samples = 1;
  64076. /**
  64077. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  64078. * It must define where the camera used to render the texture is set
  64079. */
  64080. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  64081. scene = _this.getScene();
  64082. if (!scene) {
  64083. return _this;
  64084. }
  64085. _this._engine = scene.getEngine();
  64086. _this.name = name;
  64087. _this.isRenderTarget = true;
  64088. _this._initialSizeParameter = size;
  64089. _this._processSizeParameter(size);
  64090. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  64091. });
  64092. _this._generateMipMaps = generateMipMaps ? true : false;
  64093. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  64094. // Rendering groups
  64095. _this._renderingManager = new BABYLON.RenderingManager(scene);
  64096. if (isMulti) {
  64097. return _this;
  64098. }
  64099. _this._renderTargetOptions = {
  64100. generateMipMaps: generateMipMaps,
  64101. type: type,
  64102. samplingMode: samplingMode,
  64103. generateDepthBuffer: generateDepthBuffer,
  64104. generateStencilBuffer: generateStencilBuffer
  64105. };
  64106. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  64107. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64108. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64109. }
  64110. if (isCube) {
  64111. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  64112. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  64113. _this._textureMatrix = BABYLON.Matrix.Identity();
  64114. }
  64115. else {
  64116. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  64117. }
  64118. return _this;
  64119. }
  64120. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  64121. get: function () {
  64122. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  64123. },
  64124. enumerable: true,
  64125. configurable: true
  64126. });
  64127. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  64128. get: function () {
  64129. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  64130. },
  64131. enumerable: true,
  64132. configurable: true
  64133. });
  64134. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  64135. get: function () {
  64136. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  64137. },
  64138. enumerable: true,
  64139. configurable: true
  64140. });
  64141. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  64142. set: function (callback) {
  64143. if (this._onAfterUnbindObserver) {
  64144. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  64145. }
  64146. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  64147. },
  64148. enumerable: true,
  64149. configurable: true
  64150. });
  64151. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  64152. set: function (callback) {
  64153. if (this._onBeforeRenderObserver) {
  64154. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64155. }
  64156. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64157. },
  64158. enumerable: true,
  64159. configurable: true
  64160. });
  64161. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  64162. set: function (callback) {
  64163. if (this._onAfterRenderObserver) {
  64164. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64165. }
  64166. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64167. },
  64168. enumerable: true,
  64169. configurable: true
  64170. });
  64171. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  64172. set: function (callback) {
  64173. if (this._onClearObserver) {
  64174. this.onClearObservable.remove(this._onClearObserver);
  64175. }
  64176. this._onClearObserver = this.onClearObservable.add(callback);
  64177. },
  64178. enumerable: true,
  64179. configurable: true
  64180. });
  64181. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  64182. get: function () {
  64183. return this._renderTargetOptions;
  64184. },
  64185. enumerable: true,
  64186. configurable: true
  64187. });
  64188. RenderTargetTexture.prototype._onRatioRescale = function () {
  64189. if (this._sizeRatio) {
  64190. this.resize(this._initialSizeParameter);
  64191. }
  64192. };
  64193. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  64194. get: function () {
  64195. return this._boundingBoxSize;
  64196. },
  64197. /**
  64198. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  64199. * When defined, the cubemap will switch to local mode
  64200. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  64201. * @example https://www.babylonjs-playground.com/#RNASML
  64202. */
  64203. set: function (value) {
  64204. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  64205. return;
  64206. }
  64207. this._boundingBoxSize = value;
  64208. var scene = this.getScene();
  64209. if (scene) {
  64210. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  64211. }
  64212. },
  64213. enumerable: true,
  64214. configurable: true
  64215. });
  64216. /**
  64217. * Creates a depth stencil texture.
  64218. * This is only available in WebGL 2 or with the depth texture extension available.
  64219. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  64220. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  64221. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  64222. */
  64223. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  64224. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  64225. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  64226. if (generateStencil === void 0) { generateStencil = false; }
  64227. if (!this.getScene()) {
  64228. return;
  64229. }
  64230. var engine = this.getScene().getEngine();
  64231. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  64232. bilinearFiltering: bilinearFiltering,
  64233. comparisonFunction: comparisonFunction,
  64234. generateStencil: generateStencil,
  64235. isCube: this.isCube
  64236. });
  64237. engine.setFrameBufferDepthStencilTexture(this);
  64238. };
  64239. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  64240. if (size.ratio) {
  64241. this._sizeRatio = size.ratio;
  64242. this._size = {
  64243. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  64244. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  64245. };
  64246. }
  64247. else {
  64248. this._size = size;
  64249. }
  64250. };
  64251. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  64252. get: function () {
  64253. return this._samples;
  64254. },
  64255. set: function (value) {
  64256. if (this._samples === value) {
  64257. return;
  64258. }
  64259. var scene = this.getScene();
  64260. if (!scene) {
  64261. return;
  64262. }
  64263. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  64264. },
  64265. enumerable: true,
  64266. configurable: true
  64267. });
  64268. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  64269. this._currentRefreshId = -1;
  64270. };
  64271. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  64272. get: function () {
  64273. return this._refreshRate;
  64274. },
  64275. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64276. set: function (value) {
  64277. this._refreshRate = value;
  64278. this.resetRefreshCounter();
  64279. },
  64280. enumerable: true,
  64281. configurable: true
  64282. });
  64283. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  64284. if (!this._postProcessManager) {
  64285. var scene = this.getScene();
  64286. if (!scene) {
  64287. return;
  64288. }
  64289. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  64290. this._postProcesses = new Array();
  64291. }
  64292. this._postProcesses.push(postProcess);
  64293. this._postProcesses[0].autoClear = false;
  64294. };
  64295. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  64296. if (!this._postProcesses) {
  64297. return;
  64298. }
  64299. if (dispose) {
  64300. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  64301. var postProcess = _a[_i];
  64302. postProcess.dispose();
  64303. }
  64304. }
  64305. this._postProcesses = [];
  64306. };
  64307. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  64308. if (!this._postProcesses) {
  64309. return;
  64310. }
  64311. var index = this._postProcesses.indexOf(postProcess);
  64312. if (index === -1) {
  64313. return;
  64314. }
  64315. this._postProcesses.splice(index, 1);
  64316. if (this._postProcesses.length > 0) {
  64317. this._postProcesses[0].autoClear = false;
  64318. }
  64319. };
  64320. RenderTargetTexture.prototype._shouldRender = function () {
  64321. if (this._currentRefreshId === -1) { // At least render once
  64322. this._currentRefreshId = 1;
  64323. return true;
  64324. }
  64325. if (this.refreshRate === this._currentRefreshId) {
  64326. this._currentRefreshId = 1;
  64327. return true;
  64328. }
  64329. this._currentRefreshId++;
  64330. return false;
  64331. };
  64332. RenderTargetTexture.prototype.getRenderSize = function () {
  64333. if (this._size.width) {
  64334. return this._size.width;
  64335. }
  64336. return this._size;
  64337. };
  64338. RenderTargetTexture.prototype.getRenderWidth = function () {
  64339. if (this._size.width) {
  64340. return this._size.width;
  64341. }
  64342. return this._size;
  64343. };
  64344. RenderTargetTexture.prototype.getRenderHeight = function () {
  64345. if (this._size.width) {
  64346. return this._size.height;
  64347. }
  64348. return this._size;
  64349. };
  64350. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  64351. get: function () {
  64352. return true;
  64353. },
  64354. enumerable: true,
  64355. configurable: true
  64356. });
  64357. RenderTargetTexture.prototype.scale = function (ratio) {
  64358. var newSize = this.getRenderSize() * ratio;
  64359. this.resize(newSize);
  64360. };
  64361. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  64362. if (this.isCube) {
  64363. return this._textureMatrix;
  64364. }
  64365. return _super.prototype.getReflectionTextureMatrix.call(this);
  64366. };
  64367. RenderTargetTexture.prototype.resize = function (size) {
  64368. this.releaseInternalTexture();
  64369. var scene = this.getScene();
  64370. if (!scene) {
  64371. return;
  64372. }
  64373. this._processSizeParameter(size);
  64374. if (this.isCube) {
  64375. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  64376. }
  64377. else {
  64378. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  64379. }
  64380. };
  64381. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  64382. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  64383. if (dumpForDebug === void 0) { dumpForDebug = false; }
  64384. var scene = this.getScene();
  64385. if (!scene) {
  64386. return;
  64387. }
  64388. var engine = scene.getEngine();
  64389. if (this.useCameraPostProcesses !== undefined) {
  64390. useCameraPostProcess = this.useCameraPostProcesses;
  64391. }
  64392. if (this._waitingRenderList) {
  64393. this.renderList = [];
  64394. for (var index = 0; index < this._waitingRenderList.length; index++) {
  64395. var id = this._waitingRenderList[index];
  64396. var mesh_1 = scene.getMeshByID(id);
  64397. if (mesh_1) {
  64398. this.renderList.push(mesh_1);
  64399. }
  64400. }
  64401. delete this._waitingRenderList;
  64402. }
  64403. // Is predicate defined?
  64404. if (this.renderListPredicate) {
  64405. if (this.renderList) {
  64406. this.renderList.splice(0); // Clear previous renderList
  64407. }
  64408. else {
  64409. this.renderList = [];
  64410. }
  64411. var scene = this.getScene();
  64412. if (!scene) {
  64413. return;
  64414. }
  64415. var sceneMeshes = scene.meshes;
  64416. for (var index = 0; index < sceneMeshes.length; index++) {
  64417. var mesh = sceneMeshes[index];
  64418. if (this.renderListPredicate(mesh)) {
  64419. this.renderList.push(mesh);
  64420. }
  64421. }
  64422. }
  64423. this.onBeforeBindObservable.notifyObservers(this);
  64424. // Set custom projection.
  64425. // Needs to be before binding to prevent changing the aspect ratio.
  64426. var camera;
  64427. if (this.activeCamera) {
  64428. camera = this.activeCamera;
  64429. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64430. if (this.activeCamera !== scene.activeCamera) {
  64431. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  64432. }
  64433. }
  64434. else {
  64435. camera = scene.activeCamera;
  64436. if (camera) {
  64437. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64438. }
  64439. }
  64440. // Prepare renderingManager
  64441. this._renderingManager.reset();
  64442. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  64443. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  64444. var sceneRenderId = scene.getRenderId();
  64445. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  64446. var mesh = currentRenderList[meshIndex];
  64447. if (mesh) {
  64448. if (!mesh.isReady(this.refreshRate === 0)) {
  64449. this.resetRefreshCounter();
  64450. continue;
  64451. }
  64452. mesh._preActivateForIntermediateRendering(sceneRenderId);
  64453. var isMasked = void 0;
  64454. if (!this.renderList && camera) {
  64455. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  64456. }
  64457. else {
  64458. isMasked = false;
  64459. }
  64460. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  64461. mesh._activate(sceneRenderId);
  64462. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  64463. var subMesh = mesh.subMeshes[subIndex];
  64464. scene._activeIndices.addCount(subMesh.indexCount, false);
  64465. this._renderingManager.dispatch(subMesh, mesh);
  64466. }
  64467. }
  64468. }
  64469. }
  64470. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  64471. var particleSystem = scene.particleSystems[particleIndex];
  64472. var emitter = particleSystem.emitter;
  64473. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  64474. continue;
  64475. }
  64476. if (currentRenderList.indexOf(emitter) >= 0) {
  64477. this._renderingManager.dispatchParticles(particleSystem);
  64478. }
  64479. }
  64480. if (this.isCube) {
  64481. for (var face = 0; face < 6; face++) {
  64482. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64483. scene.incrementRenderId();
  64484. scene.resetCachedMaterial();
  64485. }
  64486. }
  64487. else {
  64488. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64489. }
  64490. this.onAfterUnbindObservable.notifyObservers(this);
  64491. if (scene.activeCamera) {
  64492. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  64493. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  64494. }
  64495. engine.setViewport(scene.activeCamera.viewport);
  64496. }
  64497. scene.resetCachedMaterial();
  64498. };
  64499. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  64500. var minimum = 128;
  64501. var x = renderDimension * scale;
  64502. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  64503. // Ensure we don't exceed the render dimension (while staying POT)
  64504. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  64505. };
  64506. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64507. var _this = this;
  64508. if (!this._texture) {
  64509. return;
  64510. }
  64511. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  64512. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64513. });
  64514. };
  64515. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  64516. var scene = this.getScene();
  64517. if (!scene) {
  64518. return;
  64519. }
  64520. var engine = scene.getEngine();
  64521. if (!this._texture) {
  64522. return;
  64523. }
  64524. // Bind
  64525. if (this._postProcessManager) {
  64526. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  64527. }
  64528. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  64529. if (this._texture) {
  64530. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  64531. }
  64532. }
  64533. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  64534. // Clear
  64535. if (this.onClearObservable.hasObservers()) {
  64536. this.onClearObservable.notifyObservers(engine);
  64537. }
  64538. else {
  64539. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  64540. }
  64541. if (!this._doNotChangeAspectRatio) {
  64542. scene.updateTransformMatrix(true);
  64543. }
  64544. // Render
  64545. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  64546. if (this._postProcessManager) {
  64547. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  64548. }
  64549. else if (useCameraPostProcess) {
  64550. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  64551. }
  64552. if (!this._doNotChangeAspectRatio) {
  64553. scene.updateTransformMatrix(true);
  64554. }
  64555. // Dump ?
  64556. if (dumpForDebug) {
  64557. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  64558. }
  64559. // Unbind
  64560. if (!this.isCube || faceIndex === 5) {
  64561. if (this.isCube) {
  64562. if (faceIndex === 5) {
  64563. engine.generateMipMapsForCubemap(this._texture);
  64564. }
  64565. }
  64566. this.unbindFrameBuffer(engine, faceIndex);
  64567. }
  64568. else {
  64569. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64570. }
  64571. };
  64572. /**
  64573. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64574. * This allowed control for front to back rendering or reversly depending of the special needs.
  64575. *
  64576. * @param renderingGroupId The rendering group id corresponding to its index
  64577. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64578. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64579. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64580. */
  64581. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64582. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64583. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64584. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64585. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64586. };
  64587. /**
  64588. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64589. *
  64590. * @param renderingGroupId The rendering group id corresponding to its index
  64591. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64592. */
  64593. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64594. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64595. };
  64596. RenderTargetTexture.prototype.clone = function () {
  64597. var textureSize = this.getSize();
  64598. 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);
  64599. // Base texture
  64600. newTexture.hasAlpha = this.hasAlpha;
  64601. newTexture.level = this.level;
  64602. // RenderTarget Texture
  64603. newTexture.coordinatesMode = this.coordinatesMode;
  64604. if (this.renderList) {
  64605. newTexture.renderList = this.renderList.slice(0);
  64606. }
  64607. return newTexture;
  64608. };
  64609. RenderTargetTexture.prototype.serialize = function () {
  64610. if (!this.name) {
  64611. return null;
  64612. }
  64613. var serializationObject = _super.prototype.serialize.call(this);
  64614. serializationObject.renderTargetSize = this.getRenderSize();
  64615. serializationObject.renderList = [];
  64616. if (this.renderList) {
  64617. for (var index = 0; index < this.renderList.length; index++) {
  64618. serializationObject.renderList.push(this.renderList[index].id);
  64619. }
  64620. }
  64621. return serializationObject;
  64622. };
  64623. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64624. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64625. var objBuffer = this.getInternalTexture();
  64626. var scene = this.getScene();
  64627. if (objBuffer && scene) {
  64628. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64629. }
  64630. };
  64631. RenderTargetTexture.prototype.dispose = function () {
  64632. if (this._postProcessManager) {
  64633. this._postProcessManager.dispose();
  64634. this._postProcessManager = null;
  64635. }
  64636. this.clearPostProcesses(true);
  64637. if (this._resizeObserver) {
  64638. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64639. this._resizeObserver = null;
  64640. }
  64641. this.renderList = null;
  64642. // Remove from custom render targets
  64643. var scene = this.getScene();
  64644. if (!scene) {
  64645. return;
  64646. }
  64647. var index = scene.customRenderTargets.indexOf(this);
  64648. if (index >= 0) {
  64649. scene.customRenderTargets.splice(index, 1);
  64650. }
  64651. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64652. var camera = _a[_i];
  64653. index = camera.customRenderTargets.indexOf(this);
  64654. if (index >= 0) {
  64655. camera.customRenderTargets.splice(index, 1);
  64656. }
  64657. }
  64658. _super.prototype.dispose.call(this);
  64659. };
  64660. RenderTargetTexture.prototype._rebuild = function () {
  64661. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64662. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64663. }
  64664. if (this._postProcessManager) {
  64665. this._postProcessManager._rebuild();
  64666. }
  64667. };
  64668. /**
  64669. * Clear the info related to rendering groups preventing retention point in material dispose.
  64670. */
  64671. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64672. if (this._renderingManager) {
  64673. this._renderingManager.freeRenderingGroups();
  64674. }
  64675. };
  64676. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64677. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64678. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64679. return RenderTargetTexture;
  64680. }(BABYLON.Texture));
  64681. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64682. })(BABYLON || (BABYLON = {}));
  64683. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64684. var BABYLON;
  64685. (function (BABYLON) {
  64686. ;
  64687. var MultiRenderTarget = /** @class */ (function (_super) {
  64688. __extends(MultiRenderTarget, _super);
  64689. function MultiRenderTarget(name, size, count, scene, options) {
  64690. var _this = this;
  64691. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64692. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64693. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64694. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64695. _this._engine = scene.getEngine();
  64696. if (!_this.isSupported) {
  64697. _this.dispose();
  64698. return;
  64699. }
  64700. var types = [];
  64701. var samplingModes = [];
  64702. for (var i = 0; i < count; i++) {
  64703. if (options && options.types && options.types[i] !== undefined) {
  64704. types.push(options.types[i]);
  64705. }
  64706. else {
  64707. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64708. }
  64709. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64710. samplingModes.push(options.samplingModes[i]);
  64711. }
  64712. else {
  64713. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64714. }
  64715. }
  64716. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64717. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64718. _this._size = size;
  64719. _this._multiRenderTargetOptions = {
  64720. samplingModes: samplingModes,
  64721. generateMipMaps: generateMipMaps,
  64722. generateDepthBuffer: generateDepthBuffer,
  64723. generateStencilBuffer: generateStencilBuffer,
  64724. generateDepthTexture: generateDepthTexture,
  64725. types: types,
  64726. textureCount: count
  64727. };
  64728. _this._createInternalTextures();
  64729. _this._createTextures();
  64730. return _this;
  64731. }
  64732. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64733. get: function () {
  64734. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64735. },
  64736. enumerable: true,
  64737. configurable: true
  64738. });
  64739. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64740. get: function () {
  64741. return this._textures;
  64742. },
  64743. enumerable: true,
  64744. configurable: true
  64745. });
  64746. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64747. get: function () {
  64748. return this._textures[this._textures.length - 1];
  64749. },
  64750. enumerable: true,
  64751. configurable: true
  64752. });
  64753. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64754. set: function (wrap) {
  64755. if (this._textures) {
  64756. for (var i = 0; i < this._textures.length; i++) {
  64757. this._textures[i].wrapU = wrap;
  64758. }
  64759. }
  64760. },
  64761. enumerable: true,
  64762. configurable: true
  64763. });
  64764. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64765. set: function (wrap) {
  64766. if (this._textures) {
  64767. for (var i = 0; i < this._textures.length; i++) {
  64768. this._textures[i].wrapV = wrap;
  64769. }
  64770. }
  64771. },
  64772. enumerable: true,
  64773. configurable: true
  64774. });
  64775. MultiRenderTarget.prototype._rebuild = function () {
  64776. this.releaseInternalTextures();
  64777. this._createInternalTextures();
  64778. for (var i = 0; i < this._internalTextures.length; i++) {
  64779. var texture = this._textures[i];
  64780. texture._texture = this._internalTextures[i];
  64781. }
  64782. // Keeps references to frame buffer and stencil/depth buffer
  64783. this._texture = this._internalTextures[0];
  64784. };
  64785. MultiRenderTarget.prototype._createInternalTextures = function () {
  64786. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64787. };
  64788. MultiRenderTarget.prototype._createTextures = function () {
  64789. this._textures = [];
  64790. for (var i = 0; i < this._internalTextures.length; i++) {
  64791. var texture = new BABYLON.Texture(null, this.getScene());
  64792. texture._texture = this._internalTextures[i];
  64793. this._textures.push(texture);
  64794. }
  64795. // Keeps references to frame buffer and stencil/depth buffer
  64796. this._texture = this._internalTextures[0];
  64797. };
  64798. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64799. get: function () {
  64800. return this._samples;
  64801. },
  64802. set: function (value) {
  64803. if (this._samples === value) {
  64804. return;
  64805. }
  64806. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64807. },
  64808. enumerable: true,
  64809. configurable: true
  64810. });
  64811. MultiRenderTarget.prototype.resize = function (size) {
  64812. this.releaseInternalTextures();
  64813. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64814. this._createInternalTextures();
  64815. };
  64816. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64817. var _this = this;
  64818. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64819. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64820. });
  64821. };
  64822. MultiRenderTarget.prototype.dispose = function () {
  64823. this.releaseInternalTextures();
  64824. _super.prototype.dispose.call(this);
  64825. };
  64826. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64827. if (!this._internalTextures) {
  64828. return;
  64829. }
  64830. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64831. if (this._internalTextures[i] !== undefined) {
  64832. this._internalTextures[i].dispose();
  64833. this._internalTextures.splice(i, 1);
  64834. }
  64835. }
  64836. };
  64837. return MultiRenderTarget;
  64838. }(BABYLON.RenderTargetTexture));
  64839. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64840. })(BABYLON || (BABYLON = {}));
  64841. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64842. var BABYLON;
  64843. (function (BABYLON) {
  64844. var MirrorTexture = /** @class */ (function (_super) {
  64845. __extends(MirrorTexture, _super);
  64846. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64847. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64848. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64849. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64850. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64851. _this.scene = scene;
  64852. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64853. _this._transformMatrix = BABYLON.Matrix.Zero();
  64854. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64855. _this._adaptiveBlurKernel = 0;
  64856. _this._blurKernelX = 0;
  64857. _this._blurKernelY = 0;
  64858. _this._blurRatio = 1.0;
  64859. _this.ignoreCameraViewport = true;
  64860. _this._updateGammaSpace();
  64861. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64862. _this._updateGammaSpace;
  64863. });
  64864. _this.onBeforeRenderObservable.add(function () {
  64865. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64866. _this._savedViewMatrix = scene.getViewMatrix();
  64867. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64868. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64869. scene.clipPlane = _this.mirrorPlane;
  64870. scene.getEngine().cullBackFaces = false;
  64871. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64872. });
  64873. _this.onAfterRenderObservable.add(function () {
  64874. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64875. scene.getEngine().cullBackFaces = true;
  64876. scene._mirroredCameraPosition = null;
  64877. delete scene.clipPlane;
  64878. });
  64879. return _this;
  64880. }
  64881. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64882. get: function () {
  64883. return this._blurRatio;
  64884. },
  64885. set: function (value) {
  64886. if (this._blurRatio === value) {
  64887. return;
  64888. }
  64889. this._blurRatio = value;
  64890. this._preparePostProcesses();
  64891. },
  64892. enumerable: true,
  64893. configurable: true
  64894. });
  64895. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64896. set: function (value) {
  64897. this._adaptiveBlurKernel = value;
  64898. this._autoComputeBlurKernel();
  64899. },
  64900. enumerable: true,
  64901. configurable: true
  64902. });
  64903. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64904. set: function (value) {
  64905. this.blurKernelX = value;
  64906. this.blurKernelY = value;
  64907. },
  64908. enumerable: true,
  64909. configurable: true
  64910. });
  64911. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64912. get: function () {
  64913. return this._blurKernelX;
  64914. },
  64915. set: function (value) {
  64916. if (this._blurKernelX === value) {
  64917. return;
  64918. }
  64919. this._blurKernelX = value;
  64920. this._preparePostProcesses();
  64921. },
  64922. enumerable: true,
  64923. configurable: true
  64924. });
  64925. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64926. get: function () {
  64927. return this._blurKernelY;
  64928. },
  64929. set: function (value) {
  64930. if (this._blurKernelY === value) {
  64931. return;
  64932. }
  64933. this._blurKernelY = value;
  64934. this._preparePostProcesses();
  64935. },
  64936. enumerable: true,
  64937. configurable: true
  64938. });
  64939. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64940. var engine = this.getScene().getEngine();
  64941. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64942. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64943. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64944. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64945. };
  64946. MirrorTexture.prototype._onRatioRescale = function () {
  64947. if (this._sizeRatio) {
  64948. this.resize(this._initialSizeParameter);
  64949. if (!this._adaptiveBlurKernel) {
  64950. this._preparePostProcesses();
  64951. }
  64952. }
  64953. if (this._adaptiveBlurKernel) {
  64954. this._autoComputeBlurKernel();
  64955. }
  64956. };
  64957. MirrorTexture.prototype._updateGammaSpace = function () {
  64958. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64959. };
  64960. MirrorTexture.prototype._preparePostProcesses = function () {
  64961. this.clearPostProcesses(true);
  64962. if (this._blurKernelX && this._blurKernelY) {
  64963. var engine = this.getScene().getEngine();
  64964. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64965. 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);
  64966. this._blurX.autoClear = false;
  64967. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64968. this._blurX.inputTexture = this._texture;
  64969. }
  64970. else {
  64971. this._blurX.alwaysForcePOT = true;
  64972. }
  64973. 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);
  64974. this._blurY.autoClear = false;
  64975. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64976. this.addPostProcess(this._blurX);
  64977. this.addPostProcess(this._blurY);
  64978. }
  64979. else {
  64980. if (this._blurY) {
  64981. this.removePostProcess(this._blurY);
  64982. this._blurY.dispose();
  64983. this._blurY = null;
  64984. }
  64985. if (this._blurX) {
  64986. this.removePostProcess(this._blurX);
  64987. this._blurX.dispose();
  64988. this._blurX = null;
  64989. }
  64990. }
  64991. };
  64992. MirrorTexture.prototype.clone = function () {
  64993. var scene = this.getScene();
  64994. if (!scene) {
  64995. return this;
  64996. }
  64997. var textureSize = this.getSize();
  64998. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64999. // Base texture
  65000. newTexture.hasAlpha = this.hasAlpha;
  65001. newTexture.level = this.level;
  65002. // Mirror Texture
  65003. newTexture.mirrorPlane = this.mirrorPlane.clone();
  65004. if (this.renderList) {
  65005. newTexture.renderList = this.renderList.slice(0);
  65006. }
  65007. return newTexture;
  65008. };
  65009. MirrorTexture.prototype.serialize = function () {
  65010. if (!this.name) {
  65011. return null;
  65012. }
  65013. var serializationObject = _super.prototype.serialize.call(this);
  65014. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  65015. return serializationObject;
  65016. };
  65017. MirrorTexture.prototype.dispose = function () {
  65018. _super.prototype.dispose.call(this);
  65019. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  65020. };
  65021. return MirrorTexture;
  65022. }(BABYLON.RenderTargetTexture));
  65023. BABYLON.MirrorTexture = MirrorTexture;
  65024. })(BABYLON || (BABYLON = {}));
  65025. //# sourceMappingURL=babylon.mirrorTexture.js.map
  65026. var BABYLON;
  65027. (function (BABYLON) {
  65028. /**
  65029. * Creates a refraction texture used by refraction channel of the standard material.
  65030. * @param name the texture name
  65031. * @param size size of the underlying texture
  65032. * @param scene root scene
  65033. */
  65034. var RefractionTexture = /** @class */ (function (_super) {
  65035. __extends(RefractionTexture, _super);
  65036. function RefractionTexture(name, size, scene, generateMipMaps) {
  65037. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  65038. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  65039. _this.depth = 2.0;
  65040. _this.onBeforeRenderObservable.add(function () {
  65041. scene.clipPlane = _this.refractionPlane;
  65042. });
  65043. _this.onAfterRenderObservable.add(function () {
  65044. delete scene.clipPlane;
  65045. });
  65046. return _this;
  65047. }
  65048. RefractionTexture.prototype.clone = function () {
  65049. var scene = this.getScene();
  65050. if (!scene) {
  65051. return this;
  65052. }
  65053. var textureSize = this.getSize();
  65054. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  65055. // Base texture
  65056. newTexture.hasAlpha = this.hasAlpha;
  65057. newTexture.level = this.level;
  65058. // Refraction Texture
  65059. newTexture.refractionPlane = this.refractionPlane.clone();
  65060. if (this.renderList) {
  65061. newTexture.renderList = this.renderList.slice(0);
  65062. }
  65063. newTexture.depth = this.depth;
  65064. return newTexture;
  65065. };
  65066. RefractionTexture.prototype.serialize = function () {
  65067. if (!this.name) {
  65068. return null;
  65069. }
  65070. var serializationObject = _super.prototype.serialize.call(this);
  65071. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  65072. serializationObject.depth = this.depth;
  65073. return serializationObject;
  65074. };
  65075. return RefractionTexture;
  65076. }(BABYLON.RenderTargetTexture));
  65077. BABYLON.RefractionTexture = RefractionTexture;
  65078. })(BABYLON || (BABYLON = {}));
  65079. //# sourceMappingURL=babylon.refractionTexture.js.map
  65080. var BABYLON;
  65081. (function (BABYLON) {
  65082. /**
  65083. * A class extending {BABYLON.Texture} allowing drawing on a texture
  65084. * @see http://doc.babylonjs.com/how_to/dynamictexture
  65085. */
  65086. var DynamicTexture = /** @class */ (function (_super) {
  65087. __extends(DynamicTexture, _super);
  65088. /**
  65089. * Creates a {BABYLON.DynamicTexture}
  65090. * @param name defines the name of the texture
  65091. * @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
  65092. * @param scene defines the scene where you want the texture
  65093. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  65094. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  65095. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  65096. */
  65097. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  65098. if (scene === void 0) { scene = null; }
  65099. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65100. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  65101. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  65102. _this.name = name;
  65103. _this._engine = _this.getScene().getEngine();
  65104. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65105. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65106. _this._generateMipMaps = generateMipMaps;
  65107. if (options.getContext) {
  65108. _this._canvas = options;
  65109. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  65110. }
  65111. else {
  65112. _this._canvas = document.createElement("canvas");
  65113. if (options.width || options.width === 0) {
  65114. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  65115. }
  65116. else {
  65117. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  65118. }
  65119. }
  65120. var textureSize = _this.getSize();
  65121. _this._canvas.width = textureSize.width;
  65122. _this._canvas.height = textureSize.height;
  65123. _this._context = _this._canvas.getContext("2d");
  65124. return _this;
  65125. }
  65126. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  65127. /**
  65128. * Gets the current state of canRescale
  65129. */
  65130. get: function () {
  65131. return true;
  65132. },
  65133. enumerable: true,
  65134. configurable: true
  65135. });
  65136. DynamicTexture.prototype._recreate = function (textureSize) {
  65137. this._canvas.width = textureSize.width;
  65138. this._canvas.height = textureSize.height;
  65139. this.releaseInternalTexture();
  65140. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  65141. };
  65142. /**
  65143. * Scales the texture
  65144. * @param ratio the scale factor to apply to both width and height
  65145. */
  65146. DynamicTexture.prototype.scale = function (ratio) {
  65147. var textureSize = this.getSize();
  65148. textureSize.width *= ratio;
  65149. textureSize.height *= ratio;
  65150. this._recreate(textureSize);
  65151. };
  65152. /**
  65153. * Resizes the texture
  65154. * @param width the new width
  65155. * @param height the new height
  65156. */
  65157. DynamicTexture.prototype.scaleTo = function (width, height) {
  65158. var textureSize = this.getSize();
  65159. textureSize.width = width;
  65160. textureSize.height = height;
  65161. this._recreate(textureSize);
  65162. };
  65163. /**
  65164. * Gets the context of the canvas used by the texture
  65165. * @returns the canvas context of the dynamic texture
  65166. */
  65167. DynamicTexture.prototype.getContext = function () {
  65168. return this._context;
  65169. };
  65170. /**
  65171. * Clears the texture
  65172. */
  65173. DynamicTexture.prototype.clear = function () {
  65174. var size = this.getSize();
  65175. this._context.fillRect(0, 0, size.width, size.height);
  65176. };
  65177. /**
  65178. * Updates the texture
  65179. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  65180. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  65181. */
  65182. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  65183. if (premulAlpha === void 0) { premulAlpha = false; }
  65184. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  65185. };
  65186. /**
  65187. * Draws text onto the texture
  65188. * @param text defines the text to be drawn
  65189. * @param x defines the placement of the text from the left
  65190. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  65191. * @param font defines the font to be used with font-style, font-size, font-name
  65192. * @param color defines the color used for the text
  65193. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  65194. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  65195. * @param update defines whether texture is immediately update (default is true)
  65196. */
  65197. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  65198. if (update === void 0) { update = true; }
  65199. var size = this.getSize();
  65200. if (clearColor) {
  65201. this._context.fillStyle = clearColor;
  65202. this._context.fillRect(0, 0, size.width, size.height);
  65203. }
  65204. this._context.font = font;
  65205. if (x === null || x === undefined) {
  65206. var textSize = this._context.measureText(text);
  65207. x = (size.width - textSize.width) / 2;
  65208. }
  65209. if (y === null || y === undefined) {
  65210. var fontSize = parseInt((font.replace(/\D/g, '')));
  65211. y = (size.height / 2) + (fontSize / 3.65);
  65212. }
  65213. this._context.fillStyle = color;
  65214. this._context.fillText(text, x, y);
  65215. if (update) {
  65216. this.update(invertY);
  65217. }
  65218. };
  65219. /**
  65220. * Clones the texture
  65221. * @returns the clone of the texture.
  65222. */
  65223. DynamicTexture.prototype.clone = function () {
  65224. var scene = this.getScene();
  65225. if (!scene) {
  65226. return this;
  65227. }
  65228. var textureSize = this.getSize();
  65229. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  65230. // Base texture
  65231. newTexture.hasAlpha = this.hasAlpha;
  65232. newTexture.level = this.level;
  65233. // Dynamic Texture
  65234. newTexture.wrapU = this.wrapU;
  65235. newTexture.wrapV = this.wrapV;
  65236. return newTexture;
  65237. };
  65238. /** @hidden */
  65239. DynamicTexture.prototype._rebuild = function () {
  65240. this.update();
  65241. };
  65242. return DynamicTexture;
  65243. }(BABYLON.Texture));
  65244. BABYLON.DynamicTexture = DynamicTexture;
  65245. })(BABYLON || (BABYLON = {}));
  65246. //# sourceMappingURL=babylon.dynamicTexture.js.map
  65247. var BABYLON;
  65248. (function (BABYLON) {
  65249. var VideoTexture = /** @class */ (function (_super) {
  65250. __extends(VideoTexture, _super);
  65251. /**
  65252. * Creates a video texture.
  65253. * Sample : https://doc.babylonjs.com/how_to/video_texture
  65254. * @param {string | null} name optional name, will detect from video source, if not defined
  65255. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  65256. * @param {BABYLON.Scene} scene is obviously the current scene.
  65257. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  65258. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  65259. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  65260. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  65261. */
  65262. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  65263. if (generateMipMaps === void 0) { generateMipMaps = false; }
  65264. if (invertY === void 0) { invertY = false; }
  65265. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65266. if (settings === void 0) { settings = {
  65267. autoPlay: true,
  65268. loop: true,
  65269. autoUpdateTexture: true,
  65270. }; }
  65271. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65272. _this._stillImageCaptured = false;
  65273. _this._createInternalTexture = function () {
  65274. if (_this._texture != null) {
  65275. return;
  65276. }
  65277. if (!_this._engine.needPOTTextures ||
  65278. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  65279. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65280. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65281. }
  65282. else {
  65283. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65284. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65285. _this._generateMipMaps = false;
  65286. }
  65287. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  65288. if (!_this.video.autoplay) {
  65289. var oldHandler_1 = _this.video.onplaying;
  65290. _this.video.onplaying = function () {
  65291. _this.video.onplaying = oldHandler_1;
  65292. _this._texture.isReady = true;
  65293. _this._updateInternalTexture();
  65294. _this.video.pause();
  65295. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65296. _this.onLoadObservable.notifyObservers(_this);
  65297. }
  65298. };
  65299. _this.video.play();
  65300. }
  65301. else {
  65302. _this._texture.isReady = true;
  65303. _this._updateInternalTexture();
  65304. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65305. _this.onLoadObservable.notifyObservers(_this);
  65306. }
  65307. }
  65308. };
  65309. _this.reset = function () {
  65310. if (_this._texture == null) {
  65311. return;
  65312. }
  65313. _this._texture.dispose();
  65314. _this._texture = null;
  65315. };
  65316. _this._updateInternalTexture = function (e) {
  65317. if (_this._texture == null || !_this._texture.isReady) {
  65318. return;
  65319. }
  65320. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  65321. return;
  65322. }
  65323. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  65324. };
  65325. _this._engine = _this.getScene().getEngine();
  65326. _this._generateMipMaps = generateMipMaps;
  65327. _this._samplingMode = samplingMode;
  65328. _this.autoUpdateTexture = settings.autoUpdateTexture;
  65329. _this.name = name || _this._getName(src);
  65330. _this.video = _this._getVideo(src);
  65331. if (settings.autoPlay !== undefined) {
  65332. _this.video.autoplay = settings.autoPlay;
  65333. }
  65334. if (settings.loop !== undefined) {
  65335. _this.video.loop = settings.loop;
  65336. }
  65337. _this.video.addEventListener("canplay", _this._createInternalTexture);
  65338. _this.video.addEventListener("paused", _this._updateInternalTexture);
  65339. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  65340. _this.video.addEventListener("emptied", _this.reset);
  65341. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  65342. _this._createInternalTexture();
  65343. }
  65344. return _this;
  65345. }
  65346. VideoTexture.prototype._getName = function (src) {
  65347. if (src instanceof HTMLVideoElement) {
  65348. return src.currentSrc;
  65349. }
  65350. if (typeof src === "object") {
  65351. return src.toString();
  65352. }
  65353. return src;
  65354. };
  65355. ;
  65356. VideoTexture.prototype._getVideo = function (src) {
  65357. if (src instanceof HTMLVideoElement) {
  65358. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  65359. return src;
  65360. }
  65361. var video = document.createElement("video");
  65362. if (typeof src === "string") {
  65363. BABYLON.Tools.SetCorsBehavior(src, video);
  65364. video.src = src;
  65365. }
  65366. else {
  65367. BABYLON.Tools.SetCorsBehavior(src[0], video);
  65368. src.forEach(function (url) {
  65369. var source = document.createElement("source");
  65370. source.src = url;
  65371. video.appendChild(source);
  65372. });
  65373. }
  65374. return video;
  65375. };
  65376. ;
  65377. /**
  65378. * Internal method to initiate `update`.
  65379. */
  65380. VideoTexture.prototype._rebuild = function () {
  65381. this.update();
  65382. };
  65383. /**
  65384. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  65385. */
  65386. VideoTexture.prototype.update = function () {
  65387. if (!this.autoUpdateTexture) {
  65388. // Expecting user to call `updateTexture` manually
  65389. return;
  65390. }
  65391. this.updateTexture(true);
  65392. };
  65393. /**
  65394. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  65395. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  65396. */
  65397. VideoTexture.prototype.updateTexture = function (isVisible) {
  65398. if (!isVisible) {
  65399. return;
  65400. }
  65401. if (this.video.paused && this._stillImageCaptured) {
  65402. return;
  65403. }
  65404. this._stillImageCaptured = true;
  65405. this._updateInternalTexture();
  65406. };
  65407. /**
  65408. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  65409. * @param url New url.
  65410. */
  65411. VideoTexture.prototype.updateURL = function (url) {
  65412. this.video.src = url;
  65413. };
  65414. VideoTexture.prototype.dispose = function () {
  65415. _super.prototype.dispose.call(this);
  65416. this.video.removeEventListener("canplay", this._createInternalTexture);
  65417. this.video.removeEventListener("paused", this._updateInternalTexture);
  65418. this.video.removeEventListener("seeked", this._updateInternalTexture);
  65419. this.video.removeEventListener("emptied", this.reset);
  65420. this.video.pause();
  65421. };
  65422. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  65423. var video = document.createElement("video");
  65424. var constraintsDeviceId;
  65425. if (constraints && constraints.deviceId) {
  65426. constraintsDeviceId = {
  65427. exact: constraints.deviceId,
  65428. };
  65429. }
  65430. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  65431. if (navigator.mediaDevices) {
  65432. navigator.mediaDevices.getUserMedia({ video: constraints })
  65433. .then(function (stream) {
  65434. if (video.mozSrcObject !== undefined) {
  65435. // hack for Firefox < 19
  65436. video.mozSrcObject = stream;
  65437. }
  65438. else {
  65439. video.srcObject = stream;
  65440. }
  65441. var onPlaying = function () {
  65442. if (onReady) {
  65443. onReady(new VideoTexture("video", video, scene, true, true));
  65444. }
  65445. video.removeEventListener("playing", onPlaying);
  65446. };
  65447. video.addEventListener("playing", onPlaying);
  65448. video.play();
  65449. })
  65450. .catch(function (err) {
  65451. BABYLON.Tools.Error(err.name);
  65452. });
  65453. }
  65454. else {
  65455. navigator.getUserMedia =
  65456. navigator.getUserMedia ||
  65457. navigator.webkitGetUserMedia ||
  65458. navigator.mozGetUserMedia ||
  65459. navigator.msGetUserMedia;
  65460. if (navigator.getUserMedia) {
  65461. navigator.getUserMedia({
  65462. video: {
  65463. deviceId: constraintsDeviceId,
  65464. width: {
  65465. min: (constraints && constraints.minWidth) || 256,
  65466. max: (constraints && constraints.maxWidth) || 640,
  65467. },
  65468. height: {
  65469. min: (constraints && constraints.minHeight) || 256,
  65470. max: (constraints && constraints.maxHeight) || 480,
  65471. },
  65472. },
  65473. }, function (stream) {
  65474. if (video.mozSrcObject !== undefined) {
  65475. // hack for Firefox < 19
  65476. video.mozSrcObject = stream;
  65477. }
  65478. else {
  65479. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  65480. }
  65481. video.play();
  65482. if (onReady) {
  65483. onReady(new VideoTexture("video", video, scene, true, true));
  65484. }
  65485. }, function (e) {
  65486. BABYLON.Tools.Error(e.name);
  65487. });
  65488. }
  65489. }
  65490. };
  65491. return VideoTexture;
  65492. }(BABYLON.Texture));
  65493. BABYLON.VideoTexture = VideoTexture;
  65494. })(BABYLON || (BABYLON = {}));
  65495. //# sourceMappingURL=babylon.videoTexture.js.map
  65496. var BABYLON;
  65497. (function (BABYLON) {
  65498. var RawTexture = /** @class */ (function (_super) {
  65499. __extends(RawTexture, _super);
  65500. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  65501. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65502. if (invertY === void 0) { invertY = false; }
  65503. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65504. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65505. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65506. _this.format = format;
  65507. _this._engine = scene.getEngine();
  65508. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65509. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65510. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65511. return _this;
  65512. }
  65513. RawTexture.prototype.update = function (data) {
  65514. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65515. };
  65516. // Statics
  65517. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65518. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65519. if (invertY === void 0) { invertY = false; }
  65520. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65521. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65522. };
  65523. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65524. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65525. if (invertY === void 0) { invertY = false; }
  65526. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65527. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65528. };
  65529. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65530. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65531. if (invertY === void 0) { invertY = false; }
  65532. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65533. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65534. };
  65535. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65536. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65537. if (invertY === void 0) { invertY = false; }
  65538. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65539. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65540. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65541. };
  65542. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65543. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65544. if (invertY === void 0) { invertY = false; }
  65545. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65546. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65547. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65548. };
  65549. return RawTexture;
  65550. }(BABYLON.Texture));
  65551. BABYLON.RawTexture = RawTexture;
  65552. })(BABYLON || (BABYLON = {}));
  65553. //# sourceMappingURL=babylon.rawTexture.js.map
  65554. var BABYLON;
  65555. (function (BABYLON) {
  65556. /**
  65557. * Class used to store 3D textures containing user data
  65558. */
  65559. var RawTexture3D = /** @class */ (function (_super) {
  65560. __extends(RawTexture3D, _super);
  65561. /**
  65562. * Create a new RawTexture3D
  65563. * @param data defines the data of the texture
  65564. * @param width defines the width of the texture
  65565. * @param height defines the height of the texture
  65566. * @param depth defines the depth of the texture
  65567. * @param format defines the texture format to use
  65568. * @param scene defines the hosting scene
  65569. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65570. * @param invertY defines if texture must be stored with Y axis inverted
  65571. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65572. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  65573. */
  65574. function RawTexture3D(data, width, height, depth,
  65575. /** Gets or sets the texture format to use */
  65576. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  65577. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65578. if (invertY === void 0) { invertY = false; }
  65579. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65580. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65581. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65582. _this.format = format;
  65583. _this._engine = scene.getEngine();
  65584. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  65585. _this.is3D = true;
  65586. return _this;
  65587. }
  65588. /**
  65589. * Update the texture with new data
  65590. * @param data defines the data to store in the texture
  65591. */
  65592. RawTexture3D.prototype.update = function (data) {
  65593. if (!this._texture) {
  65594. return;
  65595. }
  65596. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65597. };
  65598. return RawTexture3D;
  65599. }(BABYLON.Texture));
  65600. BABYLON.RawTexture3D = RawTexture3D;
  65601. })(BABYLON || (BABYLON = {}));
  65602. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65603. var BABYLON;
  65604. (function (BABYLON) {
  65605. /**
  65606. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65607. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65608. */
  65609. var PostProcess = /** @class */ (function () {
  65610. /**
  65611. * Creates a new instance PostProcess
  65612. * @param name The name of the PostProcess.
  65613. * @param fragmentUrl The url of the fragment shader to be used.
  65614. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65615. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65616. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65617. * @param camera The camera to apply the render pass to.
  65618. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65619. * @param engine The engine which the post process will be applied. (default: current engine)
  65620. * @param reusable If the post process can be reused on the same frame. (default: false)
  65621. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65622. * @param textureType Type of textures used when performing the post process. (default: 0)
  65623. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65624. * @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
  65625. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65626. */
  65627. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65628. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65629. if (defines === void 0) { defines = null; }
  65630. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65631. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65632. if (blockCompilation === void 0) { blockCompilation = false; }
  65633. this.name = name;
  65634. /**
  65635. * Width of the texture to apply the post process on
  65636. */
  65637. this.width = -1;
  65638. /**
  65639. * Height of the texture to apply the post process on
  65640. */
  65641. this.height = -1;
  65642. /**
  65643. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65644. */
  65645. this._outputTexture = null;
  65646. /**
  65647. * If the buffer needs to be cleared before applying the post process. (default: true)
  65648. * Should be set to false if shader will overwrite all previous pixels.
  65649. */
  65650. this.autoClear = true;
  65651. /**
  65652. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65653. */
  65654. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65655. /**
  65656. * Animations to be used for the post processing
  65657. */
  65658. this.animations = new Array();
  65659. /**
  65660. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65661. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65662. */
  65663. this.enablePixelPerfectMode = false;
  65664. /**
  65665. * Force the postprocess to be applied without taking in account viewport
  65666. */
  65667. this.forceFullscreenViewport = true;
  65668. /**
  65669. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65670. *
  65671. * | Value | Type | Description |
  65672. * | ----- | ----------------------------------- | ----------- |
  65673. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65674. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65675. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65676. *
  65677. */
  65678. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65679. /**
  65680. * Force textures to be a power of two (default: false)
  65681. */
  65682. this.alwaysForcePOT = false;
  65683. /**
  65684. * Number of sample textures (default: 1)
  65685. */
  65686. this.samples = 1;
  65687. /**
  65688. * Modify the scale of the post process to be the same as the viewport (default: false)
  65689. */
  65690. this.adaptScaleToCurrentViewport = false;
  65691. this._reusable = false;
  65692. /**
  65693. * Smart array of input and output textures for the post process.
  65694. */
  65695. this._textures = new BABYLON.SmartArray(2);
  65696. /**
  65697. * The index in _textures that corresponds to the output texture.
  65698. */
  65699. this._currentRenderTextureInd = 0;
  65700. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65701. this._texelSize = BABYLON.Vector2.Zero();
  65702. // Events
  65703. /**
  65704. * An event triggered when the postprocess is activated.
  65705. */
  65706. this.onActivateObservable = new BABYLON.Observable();
  65707. /**
  65708. * An event triggered when the postprocess changes its size.
  65709. */
  65710. this.onSizeChangedObservable = new BABYLON.Observable();
  65711. /**
  65712. * An event triggered when the postprocess applies its effect.
  65713. */
  65714. this.onApplyObservable = new BABYLON.Observable();
  65715. /**
  65716. * An event triggered before rendering the postprocess
  65717. */
  65718. this.onBeforeRenderObservable = new BABYLON.Observable();
  65719. /**
  65720. * An event triggered after rendering the postprocess
  65721. */
  65722. this.onAfterRenderObservable = new BABYLON.Observable();
  65723. if (camera != null) {
  65724. this._camera = camera;
  65725. this._scene = camera.getScene();
  65726. camera.attachPostProcess(this);
  65727. this._engine = this._scene.getEngine();
  65728. this._scene.postProcesses.push(this);
  65729. }
  65730. else if (engine) {
  65731. this._engine = engine;
  65732. this._engine.postProcesses.push(this);
  65733. }
  65734. this._options = options;
  65735. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65736. this._reusable = reusable || false;
  65737. this._textureType = textureType;
  65738. this._samplers = samplers || [];
  65739. this._samplers.push("textureSampler");
  65740. this._fragmentUrl = fragmentUrl;
  65741. this._vertexUrl = vertexUrl;
  65742. this._parameters = parameters || [];
  65743. this._parameters.push("scale");
  65744. this._indexParameters = indexParameters;
  65745. if (!blockCompilation) {
  65746. this.updateEffect(defines);
  65747. }
  65748. }
  65749. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65750. /**
  65751. * A function that is added to the onActivateObservable
  65752. */
  65753. set: function (callback) {
  65754. if (this._onActivateObserver) {
  65755. this.onActivateObservable.remove(this._onActivateObserver);
  65756. }
  65757. if (callback) {
  65758. this._onActivateObserver = this.onActivateObservable.add(callback);
  65759. }
  65760. },
  65761. enumerable: true,
  65762. configurable: true
  65763. });
  65764. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65765. /**
  65766. * A function that is added to the onSizeChangedObservable
  65767. */
  65768. set: function (callback) {
  65769. if (this._onSizeChangedObserver) {
  65770. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65771. }
  65772. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65773. },
  65774. enumerable: true,
  65775. configurable: true
  65776. });
  65777. Object.defineProperty(PostProcess.prototype, "onApply", {
  65778. /**
  65779. * A function that is added to the onApplyObservable
  65780. */
  65781. set: function (callback) {
  65782. if (this._onApplyObserver) {
  65783. this.onApplyObservable.remove(this._onApplyObserver);
  65784. }
  65785. this._onApplyObserver = this.onApplyObservable.add(callback);
  65786. },
  65787. enumerable: true,
  65788. configurable: true
  65789. });
  65790. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65791. /**
  65792. * A function that is added to the onBeforeRenderObservable
  65793. */
  65794. set: function (callback) {
  65795. if (this._onBeforeRenderObserver) {
  65796. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65797. }
  65798. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65799. },
  65800. enumerable: true,
  65801. configurable: true
  65802. });
  65803. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65804. /**
  65805. * A function that is added to the onAfterRenderObservable
  65806. */
  65807. set: function (callback) {
  65808. if (this._onAfterRenderObserver) {
  65809. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65810. }
  65811. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65812. },
  65813. enumerable: true,
  65814. configurable: true
  65815. });
  65816. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65817. /**
  65818. * 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
  65819. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65820. */
  65821. get: function () {
  65822. return this._textures.data[this._currentRenderTextureInd];
  65823. },
  65824. set: function (value) {
  65825. this._forcedOutputTexture = value;
  65826. },
  65827. enumerable: true,
  65828. configurable: true
  65829. });
  65830. /**
  65831. * Gets the camera which post process is applied to.
  65832. * @returns The camera the post process is applied to.
  65833. */
  65834. PostProcess.prototype.getCamera = function () {
  65835. return this._camera;
  65836. };
  65837. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65838. /**
  65839. * Gets the texel size of the postprocess.
  65840. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65841. */
  65842. get: function () {
  65843. if (this._shareOutputWithPostProcess) {
  65844. return this._shareOutputWithPostProcess.texelSize;
  65845. }
  65846. if (this._forcedOutputTexture) {
  65847. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65848. }
  65849. return this._texelSize;
  65850. },
  65851. enumerable: true,
  65852. configurable: true
  65853. });
  65854. /**
  65855. * Gets the engine which this post process belongs to.
  65856. * @returns The engine the post process was enabled with.
  65857. */
  65858. PostProcess.prototype.getEngine = function () {
  65859. return this._engine;
  65860. };
  65861. /**
  65862. * The effect that is created when initializing the post process.
  65863. * @returns The created effect corrisponding the the postprocess.
  65864. */
  65865. PostProcess.prototype.getEffect = function () {
  65866. return this._effect;
  65867. };
  65868. /**
  65869. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65870. * @param postProcess The post process to share the output with.
  65871. * @returns This post process.
  65872. */
  65873. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65874. this._disposeTextures();
  65875. this._shareOutputWithPostProcess = postProcess;
  65876. return this;
  65877. };
  65878. /**
  65879. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65880. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65881. */
  65882. PostProcess.prototype.useOwnOutput = function () {
  65883. if (this._textures.length == 0) {
  65884. this._textures = new BABYLON.SmartArray(2);
  65885. }
  65886. this._shareOutputWithPostProcess = null;
  65887. };
  65888. /**
  65889. * Updates the effect with the current post process compile time values and recompiles the shader.
  65890. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65891. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65892. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65893. * @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
  65894. * @param onCompiled Called when the shader has been compiled.
  65895. * @param onError Called if there is an error when compiling a shader.
  65896. */
  65897. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65898. if (defines === void 0) { defines = null; }
  65899. if (uniforms === void 0) { uniforms = null; }
  65900. if (samplers === void 0) { samplers = null; }
  65901. 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);
  65902. };
  65903. /**
  65904. * The post process is reusable if it can be used multiple times within one frame.
  65905. * @returns If the post process is reusable
  65906. */
  65907. PostProcess.prototype.isReusable = function () {
  65908. return this._reusable;
  65909. };
  65910. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65911. PostProcess.prototype.markTextureDirty = function () {
  65912. this.width = -1;
  65913. };
  65914. /**
  65915. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65916. * 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.
  65917. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65918. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65919. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65920. * @returns The target texture that was bound to be written to.
  65921. */
  65922. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65923. var _this = this;
  65924. if (sourceTexture === void 0) { sourceTexture = null; }
  65925. camera = camera || this._camera;
  65926. var scene = camera.getScene();
  65927. var engine = scene.getEngine();
  65928. var maxSize = engine.getCaps().maxTextureSize;
  65929. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65930. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65931. // 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
  65932. var webVRCamera = camera.parent;
  65933. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65934. requiredWidth /= 2;
  65935. }
  65936. var desiredWidth = (this._options.width || requiredWidth);
  65937. var desiredHeight = this._options.height || requiredHeight;
  65938. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65939. if (this.adaptScaleToCurrentViewport) {
  65940. var currentViewport = engine.currentViewport;
  65941. if (currentViewport) {
  65942. desiredWidth *= currentViewport.width;
  65943. desiredHeight *= currentViewport.height;
  65944. }
  65945. }
  65946. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65947. if (!this._options.width) {
  65948. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65949. }
  65950. if (!this._options.height) {
  65951. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65952. }
  65953. }
  65954. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65955. if (this._textures.length > 0) {
  65956. for (var i = 0; i < this._textures.length; i++) {
  65957. this._engine._releaseTexture(this._textures.data[i]);
  65958. }
  65959. this._textures.reset();
  65960. }
  65961. this.width = desiredWidth;
  65962. this.height = desiredHeight;
  65963. var textureSize = { width: this.width, height: this.height };
  65964. var textureOptions = {
  65965. generateMipMaps: false,
  65966. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65967. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65968. samplingMode: this.renderTargetSamplingMode,
  65969. type: this._textureType
  65970. };
  65971. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65972. if (this._reusable) {
  65973. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65974. }
  65975. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65976. this.onSizeChangedObservable.notifyObservers(this);
  65977. }
  65978. this._textures.forEach(function (texture) {
  65979. if (texture.samples !== _this.samples) {
  65980. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65981. }
  65982. });
  65983. }
  65984. var target;
  65985. if (this._shareOutputWithPostProcess) {
  65986. target = this._shareOutputWithPostProcess.inputTexture;
  65987. }
  65988. else if (this._forcedOutputTexture) {
  65989. target = this._forcedOutputTexture;
  65990. this.width = this._forcedOutputTexture.width;
  65991. this.height = this._forcedOutputTexture.height;
  65992. }
  65993. else {
  65994. target = this.inputTexture;
  65995. }
  65996. // Bind the input of this post process to be used as the output of the previous post process.
  65997. if (this.enablePixelPerfectMode) {
  65998. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65999. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  66000. }
  66001. else {
  66002. this._scaleRatio.copyFromFloats(1, 1);
  66003. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  66004. }
  66005. this.onActivateObservable.notifyObservers(camera);
  66006. // Clear
  66007. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  66008. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  66009. }
  66010. if (this._reusable) {
  66011. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  66012. }
  66013. return target;
  66014. };
  66015. Object.defineProperty(PostProcess.prototype, "isSupported", {
  66016. /**
  66017. * If the post process is supported.
  66018. */
  66019. get: function () {
  66020. return this._effect.isSupported;
  66021. },
  66022. enumerable: true,
  66023. configurable: true
  66024. });
  66025. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  66026. /**
  66027. * The aspect ratio of the output texture.
  66028. */
  66029. get: function () {
  66030. if (this._shareOutputWithPostProcess) {
  66031. return this._shareOutputWithPostProcess.aspectRatio;
  66032. }
  66033. if (this._forcedOutputTexture) {
  66034. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  66035. }
  66036. return this.width / this.height;
  66037. },
  66038. enumerable: true,
  66039. configurable: true
  66040. });
  66041. /**
  66042. * Get a value indicating if the post-process is ready to be used
  66043. * @returns true if the post-process is ready (shader is compiled)
  66044. */
  66045. PostProcess.prototype.isReady = function () {
  66046. return this._effect && this._effect.isReady();
  66047. };
  66048. /**
  66049. * Binds all textures and uniforms to the shader, this will be run on every pass.
  66050. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  66051. */
  66052. PostProcess.prototype.apply = function () {
  66053. // Check
  66054. if (!this._effect || !this._effect.isReady())
  66055. return null;
  66056. // States
  66057. this._engine.enableEffect(this._effect);
  66058. this._engine.setState(false);
  66059. this._engine.setDepthBuffer(false);
  66060. this._engine.setDepthWrite(false);
  66061. // Alpha
  66062. this._engine.setAlphaMode(this.alphaMode);
  66063. if (this.alphaConstants) {
  66064. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  66065. }
  66066. // Bind the output texture of the preivous post process as the input to this post process.
  66067. var source;
  66068. if (this._shareOutputWithPostProcess) {
  66069. source = this._shareOutputWithPostProcess.inputTexture;
  66070. }
  66071. else if (this._forcedOutputTexture) {
  66072. source = this._forcedOutputTexture;
  66073. }
  66074. else {
  66075. source = this.inputTexture;
  66076. }
  66077. this._effect._bindTexture("textureSampler", source);
  66078. // Parameters
  66079. this._effect.setVector2("scale", this._scaleRatio);
  66080. this.onApplyObservable.notifyObservers(this._effect);
  66081. return this._effect;
  66082. };
  66083. PostProcess.prototype._disposeTextures = function () {
  66084. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  66085. return;
  66086. }
  66087. if (this._textures.length > 0) {
  66088. for (var i = 0; i < this._textures.length; i++) {
  66089. this._engine._releaseTexture(this._textures.data[i]);
  66090. }
  66091. }
  66092. this._textures.dispose();
  66093. };
  66094. /**
  66095. * Disposes the post process.
  66096. * @param camera The camera to dispose the post process on.
  66097. */
  66098. PostProcess.prototype.dispose = function (camera) {
  66099. camera = camera || this._camera;
  66100. this._disposeTextures();
  66101. if (this._scene) {
  66102. var index_1 = this._scene.postProcesses.indexOf(this);
  66103. if (index_1 !== -1) {
  66104. this._scene.postProcesses.splice(index_1, 1);
  66105. }
  66106. }
  66107. else {
  66108. var index_2 = this._engine.postProcesses.indexOf(this);
  66109. if (index_2 !== -1) {
  66110. this._engine.postProcesses.splice(index_2, 1);
  66111. }
  66112. }
  66113. if (!camera) {
  66114. return;
  66115. }
  66116. camera.detachPostProcess(this);
  66117. var index = camera._postProcesses.indexOf(this);
  66118. if (index === 0 && camera._postProcesses.length > 0) {
  66119. var firstPostProcess = this._camera._getFirstPostProcess();
  66120. if (firstPostProcess) {
  66121. firstPostProcess.markTextureDirty();
  66122. }
  66123. }
  66124. this.onActivateObservable.clear();
  66125. this.onAfterRenderObservable.clear();
  66126. this.onApplyObservable.clear();
  66127. this.onBeforeRenderObservable.clear();
  66128. this.onSizeChangedObservable.clear();
  66129. };
  66130. return PostProcess;
  66131. }());
  66132. BABYLON.PostProcess = PostProcess;
  66133. })(BABYLON || (BABYLON = {}));
  66134. //# sourceMappingURL=babylon.postProcess.js.map
  66135. var BABYLON;
  66136. (function (BABYLON) {
  66137. var PassPostProcess = /** @class */ (function (_super) {
  66138. __extends(PassPostProcess, _super);
  66139. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  66140. if (camera === void 0) { camera = null; }
  66141. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66142. if (blockCompilation === void 0) { blockCompilation = false; }
  66143. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  66144. }
  66145. return PassPostProcess;
  66146. }(BABYLON.PostProcess));
  66147. BABYLON.PassPostProcess = PassPostProcess;
  66148. })(BABYLON || (BABYLON = {}));
  66149. //# sourceMappingURL=babylon.passPostProcess.js.map
  66150. var __assign = (this && this.__assign) || Object.assign || function(t) {
  66151. for (var s, i = 1, n = arguments.length; i < n; i++) {
  66152. s = arguments[i];
  66153. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  66154. t[p] = s[p];
  66155. }
  66156. return t;
  66157. };
  66158. var BABYLON;
  66159. (function (BABYLON) {
  66160. /**
  66161. * Default implementation IShadowGenerator.
  66162. * This is the main object responsible of generating shadows in the framework.
  66163. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  66164. */
  66165. var ShadowGenerator = /** @class */ (function () {
  66166. /**
  66167. * Creates a ShadowGenerator object.
  66168. * A ShadowGenerator is the required tool to use the shadows.
  66169. * Each light casting shadows needs to use its own ShadowGenerator.
  66170. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  66171. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  66172. * @param light The light object generating the shadows.
  66173. * @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.
  66174. */
  66175. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  66176. this._bias = 0.00005;
  66177. this._normalBias = 0;
  66178. this._blurBoxOffset = 1;
  66179. this._blurScale = 2;
  66180. this._blurKernel = 1;
  66181. this._useKernelBlur = false;
  66182. this._filter = ShadowGenerator.FILTER_NONE;
  66183. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  66184. this._contactHardeningLightSizeUVRatio = 0.1;
  66185. this._darkness = 0;
  66186. this._transparencyShadow = false;
  66187. /**
  66188. * Controls the extent to which the shadows fade out at the edge of the frustum
  66189. * Used only by directionals and spots
  66190. */
  66191. this.frustumEdgeFalloff = 0;
  66192. /**
  66193. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  66194. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  66195. * It might on the other hand introduce peter panning.
  66196. */
  66197. this.forceBackFacesOnly = false;
  66198. this._lightDirection = BABYLON.Vector3.Zero();
  66199. this._viewMatrix = BABYLON.Matrix.Zero();
  66200. this._projectionMatrix = BABYLON.Matrix.Zero();
  66201. this._transformMatrix = BABYLON.Matrix.Zero();
  66202. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66203. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66204. this._currentFaceIndex = 0;
  66205. this._currentFaceIndexCache = 0;
  66206. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  66207. this._mapSize = mapSize;
  66208. this._light = light;
  66209. this._scene = light.getScene();
  66210. light._shadowGenerator = this;
  66211. // Texture type fallback from float to int if not supported.
  66212. var caps = this._scene.getEngine().getCaps();
  66213. if (!useFullFloatFirst) {
  66214. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66215. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66216. }
  66217. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66218. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66219. }
  66220. else {
  66221. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66222. }
  66223. }
  66224. else {
  66225. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66226. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66227. }
  66228. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66229. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66230. }
  66231. else {
  66232. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66233. }
  66234. }
  66235. this._initializeGenerator();
  66236. this._applyFilterValues();
  66237. }
  66238. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  66239. /**
  66240. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  66241. */
  66242. get: function () {
  66243. return this._bias;
  66244. },
  66245. /**
  66246. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  66247. */
  66248. set: function (bias) {
  66249. this._bias = bias;
  66250. },
  66251. enumerable: true,
  66252. configurable: true
  66253. });
  66254. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  66255. /**
  66256. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66257. */
  66258. get: function () {
  66259. return this._normalBias;
  66260. },
  66261. /**
  66262. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66263. */
  66264. set: function (normalBias) {
  66265. this._normalBias = normalBias;
  66266. },
  66267. enumerable: true,
  66268. configurable: true
  66269. });
  66270. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  66271. /**
  66272. * Gets the blur box offset: offset applied during the blur pass.
  66273. * Only usefull if useKernelBlur = false
  66274. */
  66275. get: function () {
  66276. return this._blurBoxOffset;
  66277. },
  66278. /**
  66279. * Sets the blur box offset: offset applied during the blur pass.
  66280. * Only usefull if useKernelBlur = false
  66281. */
  66282. set: function (value) {
  66283. if (this._blurBoxOffset === value) {
  66284. return;
  66285. }
  66286. this._blurBoxOffset = value;
  66287. this._disposeBlurPostProcesses();
  66288. },
  66289. enumerable: true,
  66290. configurable: true
  66291. });
  66292. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  66293. /**
  66294. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  66295. * 2 means half of the size.
  66296. */
  66297. get: function () {
  66298. return this._blurScale;
  66299. },
  66300. /**
  66301. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  66302. * 2 means half of the size.
  66303. */
  66304. set: function (value) {
  66305. if (this._blurScale === value) {
  66306. return;
  66307. }
  66308. this._blurScale = value;
  66309. this._disposeBlurPostProcesses();
  66310. },
  66311. enumerable: true,
  66312. configurable: true
  66313. });
  66314. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  66315. /**
  66316. * Gets the blur kernel: kernel size of the blur pass.
  66317. * Only usefull if useKernelBlur = true
  66318. */
  66319. get: function () {
  66320. return this._blurKernel;
  66321. },
  66322. /**
  66323. * Sets the blur kernel: kernel size of the blur pass.
  66324. * Only usefull if useKernelBlur = true
  66325. */
  66326. set: function (value) {
  66327. if (this._blurKernel === value) {
  66328. return;
  66329. }
  66330. this._blurKernel = value;
  66331. this._disposeBlurPostProcesses();
  66332. },
  66333. enumerable: true,
  66334. configurable: true
  66335. });
  66336. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  66337. /**
  66338. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  66339. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66340. */
  66341. get: function () {
  66342. return this._useKernelBlur;
  66343. },
  66344. /**
  66345. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  66346. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66347. */
  66348. set: function (value) {
  66349. if (this._useKernelBlur === value) {
  66350. return;
  66351. }
  66352. this._useKernelBlur = value;
  66353. this._disposeBlurPostProcesses();
  66354. },
  66355. enumerable: true,
  66356. configurable: true
  66357. });
  66358. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  66359. /**
  66360. * Gets the depth scale used in ESM mode.
  66361. */
  66362. get: function () {
  66363. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  66364. },
  66365. /**
  66366. * Sets the depth scale used in ESM mode.
  66367. * This can override the scale stored on the light.
  66368. */
  66369. set: function (value) {
  66370. this._depthScale = value;
  66371. },
  66372. enumerable: true,
  66373. configurable: true
  66374. });
  66375. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66376. /**
  66377. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66378. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66379. */
  66380. get: function () {
  66381. return this._filter;
  66382. },
  66383. /**
  66384. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66385. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66386. */
  66387. set: function (value) {
  66388. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66389. if (this._light.needCube()) {
  66390. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66391. this.useExponentialShadowMap = true;
  66392. return;
  66393. }
  66394. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66395. this.useCloseExponentialShadowMap = true;
  66396. return;
  66397. }
  66398. // PCF on cubemap would also be expensive
  66399. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66400. this.usePoissonSampling = true;
  66401. return;
  66402. }
  66403. }
  66404. // Weblg1 fallback for PCF.
  66405. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66406. if (this._scene.getEngine().webGLVersion === 1) {
  66407. this.usePoissonSampling = true;
  66408. return;
  66409. }
  66410. }
  66411. if (this._filter === value) {
  66412. return;
  66413. }
  66414. this._filter = value;
  66415. this._disposeBlurPostProcesses();
  66416. this._applyFilterValues();
  66417. this._light._markMeshesAsLightDirty();
  66418. },
  66419. enumerable: true,
  66420. configurable: true
  66421. });
  66422. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66423. /**
  66424. * Gets if the current filter is set to Poisson Sampling.
  66425. */
  66426. get: function () {
  66427. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66428. },
  66429. /**
  66430. * Sets the current filter to Poisson Sampling.
  66431. */
  66432. set: function (value) {
  66433. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66434. return;
  66435. }
  66436. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66437. },
  66438. enumerable: true,
  66439. configurable: true
  66440. });
  66441. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66442. /**
  66443. * Gets if the current filter is set to VSM.
  66444. * DEPRECATED. Should use useExponentialShadowMap instead.
  66445. */
  66446. get: function () {
  66447. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66448. return this.useExponentialShadowMap;
  66449. },
  66450. /**
  66451. * Sets the current filter is to VSM.
  66452. * DEPRECATED. Should use useExponentialShadowMap instead.
  66453. */
  66454. set: function (value) {
  66455. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66456. this.useExponentialShadowMap = value;
  66457. },
  66458. enumerable: true,
  66459. configurable: true
  66460. });
  66461. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66462. /**
  66463. * Gets if the current filter is set to blurred VSM.
  66464. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66465. */
  66466. get: function () {
  66467. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66468. return this.useBlurExponentialShadowMap;
  66469. },
  66470. /**
  66471. * Sets the current filter is to blurred VSM.
  66472. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66473. */
  66474. set: function (value) {
  66475. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66476. this.useBlurExponentialShadowMap = value;
  66477. },
  66478. enumerable: true,
  66479. configurable: true
  66480. });
  66481. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66482. /**
  66483. * Gets if the current filter is set to ESM.
  66484. */
  66485. get: function () {
  66486. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66487. },
  66488. /**
  66489. * Sets the current filter is to ESM.
  66490. */
  66491. set: function (value) {
  66492. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66493. return;
  66494. }
  66495. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66496. },
  66497. enumerable: true,
  66498. configurable: true
  66499. });
  66500. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66501. /**
  66502. * Gets if the current filter is set to filtered ESM.
  66503. */
  66504. get: function () {
  66505. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66506. },
  66507. /**
  66508. * Gets if the current filter is set to filtered ESM.
  66509. */
  66510. set: function (value) {
  66511. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66512. return;
  66513. }
  66514. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66515. },
  66516. enumerable: true,
  66517. configurable: true
  66518. });
  66519. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66520. /**
  66521. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66522. * exponential to prevent steep falloff artifacts).
  66523. */
  66524. get: function () {
  66525. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66526. },
  66527. /**
  66528. * Sets the current filter to "close ESM" (using the inverse of the
  66529. * exponential to prevent steep falloff artifacts).
  66530. */
  66531. set: function (value) {
  66532. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66533. return;
  66534. }
  66535. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66536. },
  66537. enumerable: true,
  66538. configurable: true
  66539. });
  66540. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66541. /**
  66542. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66543. * exponential to prevent steep falloff artifacts).
  66544. */
  66545. get: function () {
  66546. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66547. },
  66548. /**
  66549. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66550. * exponential to prevent steep falloff artifacts).
  66551. */
  66552. set: function (value) {
  66553. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66554. return;
  66555. }
  66556. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66557. },
  66558. enumerable: true,
  66559. configurable: true
  66560. });
  66561. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66562. /**
  66563. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66564. */
  66565. get: function () {
  66566. return this.filter === ShadowGenerator.FILTER_PCF;
  66567. },
  66568. /**
  66569. * Sets the current filter to "PCF" (percentage closer filtering).
  66570. */
  66571. set: function (value) {
  66572. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66573. return;
  66574. }
  66575. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66576. },
  66577. enumerable: true,
  66578. configurable: true
  66579. });
  66580. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66581. /**
  66582. * Gets the PCF or PCSS Quality.
  66583. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66584. */
  66585. get: function () {
  66586. return this._filteringQuality;
  66587. },
  66588. /**
  66589. * Sets the PCF or PCSS Quality.
  66590. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66591. */
  66592. set: function (filteringQuality) {
  66593. this._filteringQuality = filteringQuality;
  66594. },
  66595. enumerable: true,
  66596. configurable: true
  66597. });
  66598. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66599. /**
  66600. * Gets if the current filter is set to "PCSS" (contact hardening).
  66601. */
  66602. get: function () {
  66603. return this.filter === ShadowGenerator.FILTER_PCSS;
  66604. },
  66605. /**
  66606. * Sets the current filter to "PCSS" (contact hardening).
  66607. */
  66608. set: function (value) {
  66609. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66610. return;
  66611. }
  66612. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66613. },
  66614. enumerable: true,
  66615. configurable: true
  66616. });
  66617. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66618. /**
  66619. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66620. * Using a ratio helps keeping shape stability independently of the map size.
  66621. *
  66622. * It does not account for the light projection as it was having too much
  66623. * instability during the light setup or during light position changes.
  66624. *
  66625. * Only valid if useContactHardeningShadow is true.
  66626. */
  66627. get: function () {
  66628. return this._contactHardeningLightSizeUVRatio;
  66629. },
  66630. /**
  66631. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66632. * Using a ratio helps keeping shape stability independently of the map size.
  66633. *
  66634. * It does not account for the light projection as it was having too much
  66635. * instability during the light setup or during light position changes.
  66636. *
  66637. * Only valid if useContactHardeningShadow is true.
  66638. */
  66639. set: function (contactHardeningLightSizeUVRatio) {
  66640. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66641. },
  66642. enumerable: true,
  66643. configurable: true
  66644. });
  66645. /**
  66646. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66647. * 0 means strongest and 1 would means no shadow.
  66648. * @returns the darkness.
  66649. */
  66650. ShadowGenerator.prototype.getDarkness = function () {
  66651. return this._darkness;
  66652. };
  66653. /**
  66654. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66655. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66656. * @returns the shadow generator allowing fluent coding.
  66657. */
  66658. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66659. if (darkness >= 1.0)
  66660. this._darkness = 1.0;
  66661. else if (darkness <= 0.0)
  66662. this._darkness = 0.0;
  66663. else
  66664. this._darkness = darkness;
  66665. return this;
  66666. };
  66667. /**
  66668. * Sets the ability to have transparent shadow (boolean).
  66669. * @param transparent True if transparent else False
  66670. * @returns the shadow generator allowing fluent coding
  66671. */
  66672. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66673. this._transparencyShadow = transparent;
  66674. return this;
  66675. };
  66676. /**
  66677. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66678. * @returns The render target texture if present otherwise, null
  66679. */
  66680. ShadowGenerator.prototype.getShadowMap = function () {
  66681. return this._shadowMap;
  66682. };
  66683. /**
  66684. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66685. * @returns The render target texture if the shadow map is present otherwise, null
  66686. */
  66687. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66688. if (this._shadowMap2) {
  66689. return this._shadowMap2;
  66690. }
  66691. return this._shadowMap;
  66692. };
  66693. /**
  66694. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66695. * @param mesh Mesh to add
  66696. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66697. * @returns the Shadow Generator itself
  66698. */
  66699. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66700. if (includeDescendants === void 0) { includeDescendants = true; }
  66701. if (!this._shadowMap) {
  66702. return this;
  66703. }
  66704. if (!this._shadowMap.renderList) {
  66705. this._shadowMap.renderList = [];
  66706. }
  66707. this._shadowMap.renderList.push(mesh);
  66708. if (includeDescendants) {
  66709. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66710. }
  66711. return this;
  66712. var _a;
  66713. };
  66714. /**
  66715. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66716. * @param mesh Mesh to remove
  66717. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66718. * @returns the Shadow Generator itself
  66719. */
  66720. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66721. if (includeDescendants === void 0) { includeDescendants = true; }
  66722. if (!this._shadowMap || !this._shadowMap.renderList) {
  66723. return this;
  66724. }
  66725. var index = this._shadowMap.renderList.indexOf(mesh);
  66726. if (index !== -1) {
  66727. this._shadowMap.renderList.splice(index, 1);
  66728. }
  66729. if (includeDescendants) {
  66730. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66731. var child = _a[_i];
  66732. this.removeShadowCaster(child);
  66733. }
  66734. }
  66735. return this;
  66736. };
  66737. /**
  66738. * Returns the associated light object.
  66739. * @returns the light generating the shadow
  66740. */
  66741. ShadowGenerator.prototype.getLight = function () {
  66742. return this._light;
  66743. };
  66744. ShadowGenerator.prototype._initializeGenerator = function () {
  66745. this._light._markMeshesAsLightDirty();
  66746. this._initializeShadowMap();
  66747. };
  66748. ShadowGenerator.prototype._initializeShadowMap = function () {
  66749. var _this = this;
  66750. // Render target
  66751. var engine = this._scene.getEngine();
  66752. if (engine.webGLVersion > 1) {
  66753. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66754. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66755. }
  66756. else {
  66757. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66758. }
  66759. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66760. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66761. this._shadowMap.anisotropicFilteringLevel = 1;
  66762. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66763. this._shadowMap.renderParticles = false;
  66764. this._shadowMap.ignoreCameraViewport = true;
  66765. // Record Face Index before render.
  66766. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66767. _this._currentFaceIndex = faceIndex;
  66768. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66769. engine.setColorWrite(false);
  66770. }
  66771. });
  66772. // Custom render function.
  66773. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66774. // Blur if required afer render.
  66775. this._shadowMap.onAfterUnbindObservable.add(function () {
  66776. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66777. engine.setColorWrite(true);
  66778. }
  66779. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66780. return;
  66781. }
  66782. var shadowMap = _this.getShadowMapForRendering();
  66783. if (shadowMap) {
  66784. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66785. }
  66786. });
  66787. // Clear according to the chosen filter.
  66788. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66789. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66790. this._shadowMap.onClearObservable.add(function (engine) {
  66791. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66792. engine.clear(clearOne, false, true, false);
  66793. }
  66794. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66795. engine.clear(clearZero, true, true, false);
  66796. }
  66797. else {
  66798. engine.clear(clearOne, true, true, false);
  66799. }
  66800. });
  66801. };
  66802. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66803. var _this = this;
  66804. var engine = this._scene.getEngine();
  66805. var targetSize = this._mapSize / this.blurScale;
  66806. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66807. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66808. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66809. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66810. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66811. }
  66812. if (this.useKernelBlur) {
  66813. 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);
  66814. this._kernelBlurXPostprocess.width = targetSize;
  66815. this._kernelBlurXPostprocess.height = targetSize;
  66816. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66817. effect.setTexture("textureSampler", _this._shadowMap);
  66818. });
  66819. 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);
  66820. this._kernelBlurXPostprocess.autoClear = false;
  66821. this._kernelBlurYPostprocess.autoClear = false;
  66822. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66823. this._kernelBlurXPostprocess.packedFloat = true;
  66824. this._kernelBlurYPostprocess.packedFloat = true;
  66825. }
  66826. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66827. }
  66828. else {
  66829. 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);
  66830. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66831. effect.setFloat2("screenSize", targetSize, targetSize);
  66832. effect.setTexture("textureSampler", _this._shadowMap);
  66833. });
  66834. this._boxBlurPostprocess.autoClear = false;
  66835. this._blurPostProcesses = [this._boxBlurPostprocess];
  66836. }
  66837. };
  66838. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66839. var index;
  66840. var engine = this._scene.getEngine();
  66841. if (depthOnlySubMeshes.length) {
  66842. engine.setColorWrite(false);
  66843. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66844. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66845. }
  66846. engine.setColorWrite(true);
  66847. }
  66848. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66849. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66850. }
  66851. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66852. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66853. }
  66854. if (this._transparencyShadow) {
  66855. for (index = 0; index < transparentSubMeshes.length; index++) {
  66856. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66857. }
  66858. }
  66859. };
  66860. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66861. var _this = this;
  66862. var mesh = subMesh.getRenderingMesh();
  66863. var scene = this._scene;
  66864. var engine = scene.getEngine();
  66865. var material = subMesh.getMaterial();
  66866. if (!material) {
  66867. return;
  66868. }
  66869. // Culling
  66870. engine.setState(material.backFaceCulling);
  66871. // Managing instances
  66872. var batch = mesh._getInstancesRenderList(subMesh._id);
  66873. if (batch.mustReturn) {
  66874. return;
  66875. }
  66876. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66877. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66878. engine.enableEffect(this._effect);
  66879. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66880. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66881. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66882. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66883. this._effect.setVector3("lightData", this._cachedDirection);
  66884. }
  66885. else {
  66886. this._effect.setVector3("lightData", this._cachedPosition);
  66887. }
  66888. if (scene.activeCamera) {
  66889. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66890. }
  66891. // Alpha test
  66892. if (material && material.needAlphaTesting()) {
  66893. var alphaTexture = material.getAlphaTestTexture();
  66894. if (alphaTexture) {
  66895. this._effect.setTexture("diffuseSampler", alphaTexture);
  66896. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66897. }
  66898. }
  66899. // Bones
  66900. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66901. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66902. }
  66903. // Morph targets
  66904. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66905. if (this.forceBackFacesOnly) {
  66906. engine.setState(true, 0, false, true);
  66907. }
  66908. // Draw
  66909. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66910. if (this.forceBackFacesOnly) {
  66911. engine.setState(true, 0, false, false);
  66912. }
  66913. }
  66914. else {
  66915. // Need to reset refresh rate of the shadowMap
  66916. if (this._shadowMap) {
  66917. this._shadowMap.resetRefreshCounter();
  66918. }
  66919. }
  66920. };
  66921. ShadowGenerator.prototype._applyFilterValues = function () {
  66922. if (!this._shadowMap) {
  66923. return;
  66924. }
  66925. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66926. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66927. }
  66928. else {
  66929. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66930. }
  66931. };
  66932. /**
  66933. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66934. * @param onCompiled Callback triggered at the and of the effects compilation
  66935. * @param options Sets of optional options forcing the compilation with different modes
  66936. */
  66937. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66938. var _this = this;
  66939. var localOptions = __assign({ useInstances: false }, options);
  66940. var shadowMap = this.getShadowMap();
  66941. if (!shadowMap) {
  66942. if (onCompiled) {
  66943. onCompiled(this);
  66944. }
  66945. return;
  66946. }
  66947. var renderList = shadowMap.renderList;
  66948. if (!renderList) {
  66949. if (onCompiled) {
  66950. onCompiled(this);
  66951. }
  66952. return;
  66953. }
  66954. var subMeshes = new Array();
  66955. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66956. var mesh = renderList_1[_i];
  66957. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66958. }
  66959. if (subMeshes.length === 0) {
  66960. if (onCompiled) {
  66961. onCompiled(this);
  66962. }
  66963. return;
  66964. }
  66965. var currentIndex = 0;
  66966. var checkReady = function () {
  66967. if (!_this._scene || !_this._scene.getEngine()) {
  66968. return;
  66969. }
  66970. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66971. currentIndex++;
  66972. if (currentIndex >= subMeshes.length) {
  66973. if (onCompiled) {
  66974. onCompiled(_this);
  66975. }
  66976. return;
  66977. }
  66978. }
  66979. setTimeout(checkReady, 16);
  66980. };
  66981. checkReady();
  66982. };
  66983. /**
  66984. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66985. * @param options Sets of optional options forcing the compilation with different modes
  66986. * @returns A promise that resolves when the compilation completes
  66987. */
  66988. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66989. var _this = this;
  66990. return new Promise(function (resolve) {
  66991. _this.forceCompilation(function () {
  66992. resolve();
  66993. }, options);
  66994. });
  66995. };
  66996. /**
  66997. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66998. * @param subMesh The submesh we want to render in the shadow map
  66999. * @param useInstances Defines wether will draw in the map using instances
  67000. * @returns true if ready otherwise, false
  67001. */
  67002. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  67003. var defines = [];
  67004. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  67005. defines.push("#define FLOAT");
  67006. }
  67007. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  67008. defines.push("#define ESM");
  67009. }
  67010. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  67011. defines.push("#define DEPTHTEXTURE");
  67012. }
  67013. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67014. var mesh = subMesh.getMesh();
  67015. var material = subMesh.getMaterial();
  67016. // Normal bias.
  67017. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  67018. attribs.push(BABYLON.VertexBuffer.NormalKind);
  67019. defines.push("#define NORMAL");
  67020. if (mesh.nonUniformScaling) {
  67021. defines.push("#define NONUNIFORMSCALING");
  67022. }
  67023. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  67024. defines.push("#define DIRECTIONINLIGHTDATA");
  67025. }
  67026. }
  67027. // Alpha test
  67028. if (material && material.needAlphaTesting()) {
  67029. var alphaTexture = material.getAlphaTestTexture();
  67030. if (alphaTexture) {
  67031. defines.push("#define ALPHATEST");
  67032. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67033. attribs.push(BABYLON.VertexBuffer.UVKind);
  67034. defines.push("#define UV1");
  67035. }
  67036. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67037. if (alphaTexture.coordinatesIndex === 1) {
  67038. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67039. defines.push("#define UV2");
  67040. }
  67041. }
  67042. }
  67043. }
  67044. // Bones
  67045. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67046. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67047. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67048. if (mesh.numBoneInfluencers > 4) {
  67049. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67050. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67051. }
  67052. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67053. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  67054. }
  67055. else {
  67056. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67057. }
  67058. // Morph targets
  67059. var manager = mesh.morphTargetManager;
  67060. var morphInfluencers = 0;
  67061. if (manager) {
  67062. if (manager.numInfluencers > 0) {
  67063. defines.push("#define MORPHTARGETS");
  67064. morphInfluencers = manager.numInfluencers;
  67065. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  67066. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  67067. }
  67068. }
  67069. // Instances
  67070. if (useInstances) {
  67071. defines.push("#define INSTANCES");
  67072. attribs.push("world0");
  67073. attribs.push("world1");
  67074. attribs.push("world2");
  67075. attribs.push("world3");
  67076. }
  67077. // Get correct effect
  67078. var join = defines.join("\n");
  67079. if (this._cachedDefines !== join) {
  67080. this._cachedDefines = join;
  67081. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  67082. }
  67083. if (!this._effect.isReady()) {
  67084. return false;
  67085. }
  67086. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  67087. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  67088. this._initializeBlurRTTAndPostProcesses();
  67089. }
  67090. }
  67091. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  67092. return false;
  67093. }
  67094. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  67095. return false;
  67096. }
  67097. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  67098. return false;
  67099. }
  67100. return true;
  67101. };
  67102. /**
  67103. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  67104. * @param defines Defines of the material we want to update
  67105. * @param lightIndex Index of the light in the enabled light list of the material
  67106. */
  67107. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  67108. var scene = this._scene;
  67109. var light = this._light;
  67110. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  67111. return;
  67112. }
  67113. defines["SHADOW" + lightIndex] = true;
  67114. if (this.useContactHardeningShadow) {
  67115. defines["SHADOWPCSS" + lightIndex] = true;
  67116. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  67117. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  67118. }
  67119. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  67120. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  67121. }
  67122. // else default to high.
  67123. }
  67124. if (this.usePercentageCloserFiltering) {
  67125. defines["SHADOWPCF" + lightIndex] = true;
  67126. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  67127. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  67128. }
  67129. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  67130. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  67131. }
  67132. // else default to high.
  67133. }
  67134. else if (this.usePoissonSampling) {
  67135. defines["SHADOWPOISSON" + lightIndex] = true;
  67136. }
  67137. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  67138. defines["SHADOWESM" + lightIndex] = true;
  67139. }
  67140. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  67141. defines["SHADOWCLOSEESM" + lightIndex] = true;
  67142. }
  67143. if (light.needCube()) {
  67144. defines["SHADOWCUBE" + lightIndex] = true;
  67145. }
  67146. };
  67147. /**
  67148. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  67149. * defined in the generator but impacting the effect).
  67150. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  67151. * @param effect The effect we are binfing the information for
  67152. */
  67153. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  67154. var light = this._light;
  67155. var scene = this._scene;
  67156. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  67157. return;
  67158. }
  67159. var camera = scene.activeCamera;
  67160. if (!camera) {
  67161. return;
  67162. }
  67163. var shadowMap = this.getShadowMap();
  67164. if (!shadowMap) {
  67165. return;
  67166. }
  67167. if (!light.needCube()) {
  67168. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  67169. }
  67170. // Only PCF uses depth stencil texture.
  67171. if (this._filter === ShadowGenerator.FILTER_PCF) {
  67172. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67173. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  67174. }
  67175. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  67176. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67177. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  67178. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  67179. }
  67180. else {
  67181. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67182. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  67183. }
  67184. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  67185. };
  67186. /**
  67187. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  67188. * (eq to shadow prjection matrix * light transform matrix)
  67189. * @returns The transform matrix used to create the shadow map
  67190. */
  67191. ShadowGenerator.prototype.getTransformMatrix = function () {
  67192. var scene = this._scene;
  67193. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  67194. return this._transformMatrix;
  67195. }
  67196. this._currentRenderID = scene.getRenderId();
  67197. this._currentFaceIndexCache = this._currentFaceIndex;
  67198. var lightPosition = this._light.position;
  67199. if (this._light.computeTransformedInformation()) {
  67200. lightPosition = this._light.transformedPosition;
  67201. }
  67202. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  67203. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  67204. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  67205. }
  67206. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  67207. this._cachedPosition.copyFrom(lightPosition);
  67208. this._cachedDirection.copyFrom(this._lightDirection);
  67209. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  67210. var shadowMap = this.getShadowMap();
  67211. if (shadowMap) {
  67212. var renderList = shadowMap.renderList;
  67213. if (renderList) {
  67214. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  67215. }
  67216. }
  67217. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  67218. }
  67219. return this._transformMatrix;
  67220. };
  67221. /**
  67222. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  67223. * Cube and 2D textures for instance.
  67224. */
  67225. ShadowGenerator.prototype.recreateShadowMap = function () {
  67226. var shadowMap = this._shadowMap;
  67227. if (!shadowMap) {
  67228. return;
  67229. }
  67230. // Track render list.
  67231. var renderList = shadowMap.renderList;
  67232. // Clean up existing data.
  67233. this._disposeRTTandPostProcesses();
  67234. // Reinitializes.
  67235. this._initializeGenerator();
  67236. // Reaffect the filter to ensure a correct fallback if necessary.
  67237. this.filter = this.filter;
  67238. // Reaffect the filter.
  67239. this._applyFilterValues();
  67240. // Reaffect Render List.
  67241. this._shadowMap.renderList = renderList;
  67242. };
  67243. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  67244. if (this._shadowMap2) {
  67245. this._shadowMap2.dispose();
  67246. this._shadowMap2 = null;
  67247. }
  67248. if (this._boxBlurPostprocess) {
  67249. this._boxBlurPostprocess.dispose();
  67250. this._boxBlurPostprocess = null;
  67251. }
  67252. if (this._kernelBlurXPostprocess) {
  67253. this._kernelBlurXPostprocess.dispose();
  67254. this._kernelBlurXPostprocess = null;
  67255. }
  67256. if (this._kernelBlurYPostprocess) {
  67257. this._kernelBlurYPostprocess.dispose();
  67258. this._kernelBlurYPostprocess = null;
  67259. }
  67260. this._blurPostProcesses = [];
  67261. };
  67262. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  67263. if (this._shadowMap) {
  67264. this._shadowMap.dispose();
  67265. this._shadowMap = null;
  67266. }
  67267. this._disposeBlurPostProcesses();
  67268. };
  67269. /**
  67270. * Disposes the ShadowGenerator.
  67271. * Returns nothing.
  67272. */
  67273. ShadowGenerator.prototype.dispose = function () {
  67274. this._disposeRTTandPostProcesses();
  67275. if (this._light) {
  67276. this._light._shadowGenerator = null;
  67277. this._light._markMeshesAsLightDirty();
  67278. }
  67279. };
  67280. /**
  67281. * Serializes the shadow generator setup to a json object.
  67282. * @returns The serialized JSON object
  67283. */
  67284. ShadowGenerator.prototype.serialize = function () {
  67285. var serializationObject = {};
  67286. var shadowMap = this.getShadowMap();
  67287. if (!shadowMap) {
  67288. return serializationObject;
  67289. }
  67290. serializationObject.lightId = this._light.id;
  67291. serializationObject.mapSize = shadowMap.getRenderSize();
  67292. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  67293. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  67294. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67295. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67296. serializationObject.usePoissonSampling = this.usePoissonSampling;
  67297. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  67298. serializationObject.depthScale = this.depthScale;
  67299. serializationObject.darkness = this.getDarkness();
  67300. serializationObject.blurBoxOffset = this.blurBoxOffset;
  67301. serializationObject.blurKernel = this.blurKernel;
  67302. serializationObject.blurScale = this.blurScale;
  67303. serializationObject.useKernelBlur = this.useKernelBlur;
  67304. serializationObject.transparencyShadow = this._transparencyShadow;
  67305. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  67306. serializationObject.bias = this.bias;
  67307. serializationObject.normalBias = this.normalBias;
  67308. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  67309. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  67310. serializationObject.filteringQuality = this.filteringQuality;
  67311. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  67312. serializationObject.renderList = [];
  67313. if (shadowMap.renderList) {
  67314. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  67315. var mesh = shadowMap.renderList[meshIndex];
  67316. serializationObject.renderList.push(mesh.id);
  67317. }
  67318. }
  67319. return serializationObject;
  67320. };
  67321. /**
  67322. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  67323. * @param parsedShadowGenerator The JSON object to parse
  67324. * @param scene The scene to create the shadow map for
  67325. * @returns The parsed shadow generator
  67326. */
  67327. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  67328. //casting to point light, as light is missing the position attr and typescript complains.
  67329. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  67330. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  67331. var shadowMap = shadowGenerator.getShadowMap();
  67332. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  67333. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  67334. meshes.forEach(function (mesh) {
  67335. if (!shadowMap) {
  67336. return;
  67337. }
  67338. if (!shadowMap.renderList) {
  67339. shadowMap.renderList = [];
  67340. }
  67341. shadowMap.renderList.push(mesh);
  67342. });
  67343. }
  67344. if (parsedShadowGenerator.usePoissonSampling) {
  67345. shadowGenerator.usePoissonSampling = true;
  67346. }
  67347. else if (parsedShadowGenerator.useExponentialShadowMap) {
  67348. shadowGenerator.useExponentialShadowMap = true;
  67349. }
  67350. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  67351. shadowGenerator.useBlurExponentialShadowMap = true;
  67352. }
  67353. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  67354. shadowGenerator.useCloseExponentialShadowMap = true;
  67355. }
  67356. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  67357. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  67358. }
  67359. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  67360. shadowGenerator.usePercentageCloserFiltering = true;
  67361. }
  67362. else if (parsedShadowGenerator.useContactHardeningShadow) {
  67363. shadowGenerator.useContactHardeningShadow = true;
  67364. }
  67365. if (parsedShadowGenerator.filteringQuality) {
  67366. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  67367. }
  67368. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  67369. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  67370. }
  67371. // Backward compat
  67372. else if (parsedShadowGenerator.useVarianceShadowMap) {
  67373. shadowGenerator.useExponentialShadowMap = true;
  67374. }
  67375. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67376. shadowGenerator.useBlurExponentialShadowMap = true;
  67377. }
  67378. if (parsedShadowGenerator.depthScale) {
  67379. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67380. }
  67381. if (parsedShadowGenerator.blurScale) {
  67382. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67383. }
  67384. if (parsedShadowGenerator.blurBoxOffset) {
  67385. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67386. }
  67387. if (parsedShadowGenerator.useKernelBlur) {
  67388. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67389. }
  67390. if (parsedShadowGenerator.blurKernel) {
  67391. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67392. }
  67393. if (parsedShadowGenerator.bias !== undefined) {
  67394. shadowGenerator.bias = parsedShadowGenerator.bias;
  67395. }
  67396. if (parsedShadowGenerator.normalBias !== undefined) {
  67397. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67398. }
  67399. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  67400. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  67401. }
  67402. if (parsedShadowGenerator.darkness) {
  67403. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67404. }
  67405. if (parsedShadowGenerator.transparencyShadow) {
  67406. shadowGenerator.setTransparencyShadow(true);
  67407. }
  67408. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67409. return shadowGenerator;
  67410. };
  67411. /**
  67412. * Shadow generator mode None: no filtering applied.
  67413. */
  67414. ShadowGenerator.FILTER_NONE = 0;
  67415. /**
  67416. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67417. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67418. */
  67419. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67420. /**
  67421. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67422. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67423. */
  67424. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67425. /**
  67426. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67427. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67428. */
  67429. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67430. /**
  67431. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67432. * edge artifacts on steep falloff.
  67433. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67434. */
  67435. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67436. /**
  67437. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67438. * edge artifacts on steep falloff.
  67439. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67440. */
  67441. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67442. /**
  67443. * Shadow generator mode PCF: Percentage Closer Filtering
  67444. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67445. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67446. */
  67447. ShadowGenerator.FILTER_PCF = 6;
  67448. /**
  67449. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67450. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67451. * Contact Hardening
  67452. */
  67453. ShadowGenerator.FILTER_PCSS = 7;
  67454. /**
  67455. * Reserved for PCF and PCSS
  67456. * Highest Quality.
  67457. *
  67458. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67459. *
  67460. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67461. */
  67462. ShadowGenerator.QUALITY_HIGH = 0;
  67463. /**
  67464. * Reserved for PCF and PCSS
  67465. * Good tradeoff for quality/perf cross devices
  67466. *
  67467. * Execute PCF on a 3*3 kernel.
  67468. *
  67469. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67470. */
  67471. ShadowGenerator.QUALITY_MEDIUM = 1;
  67472. /**
  67473. * Reserved for PCF and PCSS
  67474. * The lowest quality but the fastest.
  67475. *
  67476. * Execute PCF on a 1*1 kernel.
  67477. *
  67478. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67479. */
  67480. ShadowGenerator.QUALITY_LOW = 2;
  67481. return ShadowGenerator;
  67482. }());
  67483. BABYLON.ShadowGenerator = ShadowGenerator;
  67484. })(BABYLON || (BABYLON = {}));
  67485. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67486. var BABYLON;
  67487. (function (BABYLON) {
  67488. var DefaultLoadingScreen = /** @class */ (function () {
  67489. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67490. if (_loadingText === void 0) { _loadingText = ""; }
  67491. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67492. var _this = this;
  67493. this._renderingCanvas = _renderingCanvas;
  67494. this._loadingText = _loadingText;
  67495. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67496. // Resize
  67497. this._resizeLoadingUI = function () {
  67498. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67499. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67500. if (!_this._loadingDiv) {
  67501. return;
  67502. }
  67503. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67504. _this._loadingDiv.style.left = canvasRect.left + "px";
  67505. _this._loadingDiv.style.top = canvasRect.top + "px";
  67506. _this._loadingDiv.style.width = canvasRect.width + "px";
  67507. _this._loadingDiv.style.height = canvasRect.height + "px";
  67508. };
  67509. }
  67510. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67511. if (this._loadingDiv) {
  67512. // Do not add a loading screen if there is already one
  67513. return;
  67514. }
  67515. this._loadingDiv = document.createElement("div");
  67516. this._loadingDiv.id = "babylonjsLoadingDiv";
  67517. this._loadingDiv.style.opacity = "0";
  67518. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67519. this._loadingDiv.style.pointerEvents = "none";
  67520. // Loading text
  67521. this._loadingTextDiv = document.createElement("div");
  67522. this._loadingTextDiv.style.position = "absolute";
  67523. this._loadingTextDiv.style.left = "0";
  67524. this._loadingTextDiv.style.top = "50%";
  67525. this._loadingTextDiv.style.marginTop = "80px";
  67526. this._loadingTextDiv.style.width = "100%";
  67527. this._loadingTextDiv.style.height = "20px";
  67528. this._loadingTextDiv.style.fontFamily = "Arial";
  67529. this._loadingTextDiv.style.fontSize = "14px";
  67530. this._loadingTextDiv.style.color = "white";
  67531. this._loadingTextDiv.style.textAlign = "center";
  67532. this._loadingTextDiv.innerHTML = "Loading";
  67533. this._loadingDiv.appendChild(this._loadingTextDiv);
  67534. //set the predefined text
  67535. this._loadingTextDiv.innerHTML = this._loadingText;
  67536. // Generating keyframes
  67537. var style = document.createElement('style');
  67538. style.type = 'text/css';
  67539. 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 }";
  67540. style.innerHTML = keyFrames;
  67541. document.getElementsByTagName('head')[0].appendChild(style);
  67542. // Loading img
  67543. var imgBack = new Image();
  67544. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg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ynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+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";
  67545. imgBack.style.position = "absolute";
  67546. imgBack.style.left = "50%";
  67547. imgBack.style.top = "50%";
  67548. imgBack.style.marginLeft = "-60px";
  67549. imgBack.style.marginTop = "-60px";
  67550. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67551. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67552. imgBack.style.transformOrigin = "50% 50%";
  67553. imgBack.style.webkitTransformOrigin = "50% 50%";
  67554. this._loadingDiv.appendChild(imgBack);
  67555. this._resizeLoadingUI();
  67556. window.addEventListener("resize", this._resizeLoadingUI);
  67557. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67558. document.body.appendChild(this._loadingDiv);
  67559. this._loadingDiv.style.opacity = "1";
  67560. };
  67561. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67562. var _this = this;
  67563. if (!this._loadingDiv) {
  67564. return;
  67565. }
  67566. var onTransitionEnd = function () {
  67567. if (!_this._loadingDiv) {
  67568. return;
  67569. }
  67570. document.body.removeChild(_this._loadingDiv);
  67571. window.removeEventListener("resize", _this._resizeLoadingUI);
  67572. _this._loadingDiv = null;
  67573. };
  67574. this._loadingDiv.style.opacity = "0";
  67575. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67576. };
  67577. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67578. set: function (text) {
  67579. this._loadingText = text;
  67580. if (this._loadingTextDiv) {
  67581. this._loadingTextDiv.innerHTML = this._loadingText;
  67582. }
  67583. },
  67584. enumerable: true,
  67585. configurable: true
  67586. });
  67587. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67588. get: function () {
  67589. return this._loadingDivBackgroundColor;
  67590. },
  67591. set: function (color) {
  67592. this._loadingDivBackgroundColor = color;
  67593. if (!this._loadingDiv) {
  67594. return;
  67595. }
  67596. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67597. },
  67598. enumerable: true,
  67599. configurable: true
  67600. });
  67601. return DefaultLoadingScreen;
  67602. }());
  67603. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67604. })(BABYLON || (BABYLON = {}));
  67605. //# sourceMappingURL=babylon.loadingScreen.js.map
  67606. var BABYLON;
  67607. (function (BABYLON) {
  67608. var SceneLoaderProgressEvent = /** @class */ (function () {
  67609. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67610. this.lengthComputable = lengthComputable;
  67611. this.loaded = loaded;
  67612. this.total = total;
  67613. }
  67614. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67615. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67616. };
  67617. return SceneLoaderProgressEvent;
  67618. }());
  67619. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67620. var SceneLoader = /** @class */ (function () {
  67621. function SceneLoader() {
  67622. }
  67623. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67624. get: function () {
  67625. return 0;
  67626. },
  67627. enumerable: true,
  67628. configurable: true
  67629. });
  67630. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67631. get: function () {
  67632. return 1;
  67633. },
  67634. enumerable: true,
  67635. configurable: true
  67636. });
  67637. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67638. get: function () {
  67639. return 2;
  67640. },
  67641. enumerable: true,
  67642. configurable: true
  67643. });
  67644. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67645. get: function () {
  67646. return 3;
  67647. },
  67648. enumerable: true,
  67649. configurable: true
  67650. });
  67651. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67652. get: function () {
  67653. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67654. },
  67655. set: function (value) {
  67656. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67657. },
  67658. enumerable: true,
  67659. configurable: true
  67660. });
  67661. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67662. get: function () {
  67663. return SceneLoader._ShowLoadingScreen;
  67664. },
  67665. set: function (value) {
  67666. SceneLoader._ShowLoadingScreen = value;
  67667. },
  67668. enumerable: true,
  67669. configurable: true
  67670. });
  67671. Object.defineProperty(SceneLoader, "loggingLevel", {
  67672. get: function () {
  67673. return SceneLoader._loggingLevel;
  67674. },
  67675. set: function (value) {
  67676. SceneLoader._loggingLevel = value;
  67677. },
  67678. enumerable: true,
  67679. configurable: true
  67680. });
  67681. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67682. get: function () {
  67683. return SceneLoader._CleanBoneMatrixWeights;
  67684. },
  67685. set: function (value) {
  67686. SceneLoader._CleanBoneMatrixWeights = value;
  67687. },
  67688. enumerable: true,
  67689. configurable: true
  67690. });
  67691. SceneLoader._getDefaultPlugin = function () {
  67692. return SceneLoader._registeredPlugins[".babylon"];
  67693. };
  67694. SceneLoader._getPluginForExtension = function (extension) {
  67695. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67696. if (registeredPlugin) {
  67697. return registeredPlugin;
  67698. }
  67699. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  67700. return SceneLoader._getDefaultPlugin();
  67701. };
  67702. SceneLoader._getPluginForDirectLoad = function (data) {
  67703. for (var extension in SceneLoader._registeredPlugins) {
  67704. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67705. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67706. return SceneLoader._registeredPlugins[extension];
  67707. }
  67708. }
  67709. return SceneLoader._getDefaultPlugin();
  67710. };
  67711. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67712. if (sceneFilename.name) {
  67713. sceneFilename = sceneFilename.name;
  67714. }
  67715. var queryStringPosition = sceneFilename.indexOf("?");
  67716. if (queryStringPosition !== -1) {
  67717. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67718. }
  67719. var dotPosition = sceneFilename.lastIndexOf(".");
  67720. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67721. return SceneLoader._getPluginForExtension(extension);
  67722. };
  67723. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67724. SceneLoader._getDirectLoad = function (sceneFilename) {
  67725. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67726. return sceneFilename.substr(5);
  67727. }
  67728. return null;
  67729. };
  67730. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67731. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67732. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67733. var plugin;
  67734. if (registeredPlugin.plugin.createPlugin) {
  67735. plugin = registeredPlugin.plugin.createPlugin();
  67736. }
  67737. else {
  67738. plugin = registeredPlugin.plugin;
  67739. }
  67740. var useArrayBuffer = registeredPlugin.isBinary;
  67741. var database;
  67742. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67743. var dataCallback = function (data, responseURL) {
  67744. if (scene.isDisposed) {
  67745. onError("Scene has been disposed");
  67746. return;
  67747. }
  67748. scene.database = database;
  67749. onSuccess(plugin, data, responseURL);
  67750. };
  67751. var request = null;
  67752. var pluginDisposed = false;
  67753. var onDisposeObservable = plugin.onDisposeObservable;
  67754. if (onDisposeObservable) {
  67755. onDisposeObservable.add(function () {
  67756. pluginDisposed = true;
  67757. if (request) {
  67758. request.abort();
  67759. request = null;
  67760. }
  67761. onDispose();
  67762. });
  67763. }
  67764. var manifestChecked = function () {
  67765. if (pluginDisposed) {
  67766. return;
  67767. }
  67768. var url = rootUrl + sceneFilename;
  67769. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67770. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67771. } : undefined, database, useArrayBuffer, function (request, exception) {
  67772. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67773. });
  67774. };
  67775. if (directLoad) {
  67776. dataCallback(directLoad);
  67777. return plugin;
  67778. }
  67779. if (rootUrl.indexOf("file:") === -1) {
  67780. var engine = scene.getEngine();
  67781. var canUseOfflineSupport = engine.enableOfflineSupport;
  67782. if (canUseOfflineSupport) {
  67783. // Also check for exceptions
  67784. var exceptionFound = false;
  67785. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67786. var regex = _a[_i];
  67787. if (regex.test(rootUrl + sceneFilename)) {
  67788. exceptionFound = true;
  67789. break;
  67790. }
  67791. }
  67792. canUseOfflineSupport = !exceptionFound;
  67793. }
  67794. if (canUseOfflineSupport) {
  67795. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67796. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67797. }
  67798. else {
  67799. manifestChecked();
  67800. }
  67801. }
  67802. // Loading file from disk via input file or drag'n'drop
  67803. else {
  67804. var fileOrString = sceneFilename;
  67805. if (fileOrString.name) { // File
  67806. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67807. }
  67808. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67809. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67810. }
  67811. else {
  67812. onError("Unable to find file named " + sceneFilename);
  67813. }
  67814. }
  67815. return plugin;
  67816. };
  67817. // Public functions
  67818. SceneLoader.GetPluginForExtension = function (extension) {
  67819. return SceneLoader._getPluginForExtension(extension).plugin;
  67820. };
  67821. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67822. return !!SceneLoader._registeredPlugins[extension];
  67823. };
  67824. SceneLoader.RegisterPlugin = function (plugin) {
  67825. if (typeof plugin.extensions === "string") {
  67826. var extension = plugin.extensions;
  67827. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67828. plugin: plugin,
  67829. isBinary: false
  67830. };
  67831. }
  67832. else {
  67833. var extensions = plugin.extensions;
  67834. Object.keys(extensions).forEach(function (extension) {
  67835. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67836. plugin: plugin,
  67837. isBinary: extensions[extension].isBinary
  67838. };
  67839. });
  67840. }
  67841. };
  67842. /**
  67843. * Import meshes into a scene
  67844. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67845. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67846. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67847. * @param scene the instance of BABYLON.Scene to append to
  67848. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67849. * @param onProgress a callback with a progress event for each file being loaded
  67850. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67851. * @param pluginExtension the extension used to determine the plugin
  67852. * @returns The loaded plugin
  67853. */
  67854. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67855. if (sceneFilename === void 0) { sceneFilename = ""; }
  67856. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67857. if (onSuccess === void 0) { onSuccess = null; }
  67858. if (onProgress === void 0) { onProgress = null; }
  67859. if (onError === void 0) { onError = null; }
  67860. if (pluginExtension === void 0) { pluginExtension = null; }
  67861. if (!scene) {
  67862. BABYLON.Tools.Error("No scene available to import mesh to");
  67863. return null;
  67864. }
  67865. if (!sceneFilename) {
  67866. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67867. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67868. }
  67869. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67870. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67871. return null;
  67872. }
  67873. var loadingToken = {};
  67874. scene._addPendingData(loadingToken);
  67875. var disposeHandler = function () {
  67876. scene._removePendingData(loadingToken);
  67877. };
  67878. var errorHandler = function (message, exception) {
  67879. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67880. if (onError) {
  67881. onError(scene, errorMessage, exception);
  67882. }
  67883. else {
  67884. BABYLON.Tools.Error(errorMessage);
  67885. // should the exception be thrown?
  67886. }
  67887. disposeHandler();
  67888. };
  67889. var progressHandler = onProgress ? function (event) {
  67890. try {
  67891. onProgress(event);
  67892. }
  67893. catch (e) {
  67894. errorHandler("Error in onProgress callback", e);
  67895. }
  67896. } : undefined;
  67897. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67898. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67899. if (onSuccess) {
  67900. try {
  67901. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67902. }
  67903. catch (e) {
  67904. errorHandler("Error in onSuccess callback", e);
  67905. }
  67906. }
  67907. scene._removePendingData(loadingToken);
  67908. };
  67909. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67910. if (plugin.rewriteRootURL) {
  67911. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67912. }
  67913. if (sceneFilename === "") {
  67914. if (sceneFilename === "") {
  67915. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67916. }
  67917. }
  67918. if (plugin.importMesh) {
  67919. var syncedPlugin = plugin;
  67920. var meshes = new Array();
  67921. var particleSystems = new Array();
  67922. var skeletons = new Array();
  67923. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67924. return;
  67925. }
  67926. scene.loadingPluginName = plugin.name;
  67927. successHandler(meshes, particleSystems, skeletons, []);
  67928. }
  67929. else {
  67930. var asyncedPlugin = plugin;
  67931. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67932. scene.loadingPluginName = plugin.name;
  67933. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67934. }).catch(function (error) {
  67935. errorHandler(error.message, error);
  67936. });
  67937. }
  67938. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67939. };
  67940. /**
  67941. * Import meshes into a scene
  67942. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67943. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67944. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67945. * @param scene the instance of BABYLON.Scene to append to
  67946. * @param onProgress a callback with a progress event for each file being loaded
  67947. * @param pluginExtension the extension used to determine the plugin
  67948. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67949. */
  67950. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67951. if (sceneFilename === void 0) { sceneFilename = ""; }
  67952. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67953. if (onProgress === void 0) { onProgress = null; }
  67954. if (pluginExtension === void 0) { pluginExtension = null; }
  67955. return new Promise(function (resolve, reject) {
  67956. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67957. resolve({
  67958. meshes: meshes,
  67959. particleSystems: particleSystems,
  67960. skeletons: skeletons,
  67961. animationGroups: animationGroups
  67962. });
  67963. }, onProgress, function (scene, message, exception) {
  67964. reject(exception || new Error(message));
  67965. }, pluginExtension);
  67966. });
  67967. };
  67968. /**
  67969. * Load a scene
  67970. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67971. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67972. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67973. * @param onSuccess a callback with the scene when import succeeds
  67974. * @param onProgress a callback with a progress event for each file being loaded
  67975. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67976. * @param pluginExtension the extension used to determine the plugin
  67977. * @returns The loaded plugin
  67978. */
  67979. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67980. if (onSuccess === void 0) { onSuccess = null; }
  67981. if (onProgress === void 0) { onProgress = null; }
  67982. if (onError === void 0) { onError = null; }
  67983. if (pluginExtension === void 0) { pluginExtension = null; }
  67984. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67985. };
  67986. /**
  67987. * Load a scene
  67988. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67989. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67990. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67991. * @param onProgress a callback with a progress event for each file being loaded
  67992. * @param pluginExtension the extension used to determine the plugin
  67993. * @returns The loaded scene
  67994. */
  67995. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67996. if (onProgress === void 0) { onProgress = null; }
  67997. if (pluginExtension === void 0) { pluginExtension = null; }
  67998. return new Promise(function (resolve, reject) {
  67999. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  68000. resolve(scene);
  68001. }, onProgress, function (scene, message, exception) {
  68002. reject(exception || new Error(message));
  68003. }, pluginExtension);
  68004. });
  68005. };
  68006. /**
  68007. * Append a scene
  68008. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  68009. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  68010. * @param scene is the instance of BABYLON.Scene to append to
  68011. * @param onSuccess a callback with the scene when import succeeds
  68012. * @param onProgress a callback with a progress event for each file being loaded
  68013. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68014. * @param pluginExtension the extension used to determine the plugin
  68015. * @returns The loaded plugin
  68016. */
  68017. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  68018. if (sceneFilename === void 0) { sceneFilename = ""; }
  68019. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68020. if (onSuccess === void 0) { onSuccess = null; }
  68021. if (onProgress === void 0) { onProgress = null; }
  68022. if (onError === void 0) { onError = null; }
  68023. if (pluginExtension === void 0) { pluginExtension = null; }
  68024. if (!scene) {
  68025. BABYLON.Tools.Error("No scene available to append to");
  68026. return null;
  68027. }
  68028. if (!sceneFilename) {
  68029. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  68030. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  68031. }
  68032. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  68033. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  68034. return null;
  68035. }
  68036. if (SceneLoader.ShowLoadingScreen) {
  68037. scene.getEngine().displayLoadingUI();
  68038. }
  68039. var loadingToken = {};
  68040. scene._addPendingData(loadingToken);
  68041. var disposeHandler = function () {
  68042. scene._removePendingData(loadingToken);
  68043. scene.getEngine().hideLoadingUI();
  68044. };
  68045. var errorHandler = function (message, exception) {
  68046. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  68047. if (onError) {
  68048. onError(scene, errorMessage, exception);
  68049. }
  68050. else {
  68051. BABYLON.Tools.Error(errorMessage);
  68052. // should the exception be thrown?
  68053. }
  68054. disposeHandler();
  68055. };
  68056. var progressHandler = onProgress ? function (event) {
  68057. try {
  68058. onProgress(event);
  68059. }
  68060. catch (e) {
  68061. errorHandler("Error in onProgress callback", e);
  68062. }
  68063. } : undefined;
  68064. var successHandler = function () {
  68065. if (onSuccess) {
  68066. try {
  68067. onSuccess(scene);
  68068. }
  68069. catch (e) {
  68070. errorHandler("Error in onSuccess callback", e);
  68071. }
  68072. }
  68073. scene._removePendingData(loadingToken);
  68074. };
  68075. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  68076. if (sceneFilename === "") {
  68077. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  68078. }
  68079. if (plugin.load) {
  68080. var syncedPlugin = plugin;
  68081. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  68082. return;
  68083. }
  68084. scene.loadingPluginName = plugin.name;
  68085. successHandler();
  68086. }
  68087. else {
  68088. var asyncedPlugin = plugin;
  68089. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  68090. scene.loadingPluginName = plugin.name;
  68091. successHandler();
  68092. }).catch(function (error) {
  68093. errorHandler(error.message, error);
  68094. });
  68095. }
  68096. if (SceneLoader.ShowLoadingScreen) {
  68097. scene.executeWhenReady(function () {
  68098. scene.getEngine().hideLoadingUI();
  68099. });
  68100. }
  68101. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68102. };
  68103. /**
  68104. * Append a scene
  68105. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  68106. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  68107. * @param scene is the instance of BABYLON.Scene to append to
  68108. * @param onProgress a callback with a progress event for each file being loaded
  68109. * @param pluginExtension the extension used to determine the plugin
  68110. * @returns The given scene
  68111. */
  68112. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68113. if (sceneFilename === void 0) { sceneFilename = ""; }
  68114. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68115. if (onProgress === void 0) { onProgress = null; }
  68116. if (pluginExtension === void 0) { pluginExtension = null; }
  68117. return new Promise(function (resolve, reject) {
  68118. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  68119. resolve(scene);
  68120. }, onProgress, function (scene, message, exception) {
  68121. reject(exception || new Error(message));
  68122. }, pluginExtension);
  68123. });
  68124. };
  68125. /**
  68126. * Load a scene into an asset container
  68127. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  68128. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  68129. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  68130. * @param onSuccess a callback with the scene when import succeeds
  68131. * @param onProgress a callback with a progress event for each file being loaded
  68132. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68133. * @param pluginExtension the extension used to determine the plugin
  68134. * @returns The loaded plugin
  68135. */
  68136. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  68137. if (sceneFilename === void 0) { sceneFilename = ""; }
  68138. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68139. if (onSuccess === void 0) { onSuccess = null; }
  68140. if (onProgress === void 0) { onProgress = null; }
  68141. if (onError === void 0) { onError = null; }
  68142. if (pluginExtension === void 0) { pluginExtension = null; }
  68143. if (!scene) {
  68144. BABYLON.Tools.Error("No scene available to load asset container to");
  68145. return null;
  68146. }
  68147. if (!sceneFilename) {
  68148. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  68149. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  68150. }
  68151. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  68152. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  68153. return null;
  68154. }
  68155. var loadingToken = {};
  68156. scene._addPendingData(loadingToken);
  68157. var disposeHandler = function () {
  68158. scene._removePendingData(loadingToken);
  68159. };
  68160. var errorHandler = function (message, exception) {
  68161. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  68162. if (onError) {
  68163. onError(scene, errorMessage, exception);
  68164. }
  68165. else {
  68166. BABYLON.Tools.Error(errorMessage);
  68167. // should the exception be thrown?
  68168. }
  68169. disposeHandler();
  68170. };
  68171. var progressHandler = onProgress ? function (event) {
  68172. try {
  68173. onProgress(event);
  68174. }
  68175. catch (e) {
  68176. errorHandler("Error in onProgress callback", e);
  68177. }
  68178. } : undefined;
  68179. var successHandler = function (assets) {
  68180. if (onSuccess) {
  68181. try {
  68182. onSuccess(assets);
  68183. }
  68184. catch (e) {
  68185. errorHandler("Error in onSuccess callback", e);
  68186. }
  68187. }
  68188. scene._removePendingData(loadingToken);
  68189. };
  68190. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  68191. if (plugin.loadAssetContainer) {
  68192. var syncedPlugin = plugin;
  68193. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  68194. if (!assetContainer) {
  68195. return;
  68196. }
  68197. scene.loadingPluginName = plugin.name;
  68198. successHandler(assetContainer);
  68199. }
  68200. else if (plugin.loadAssetContainerAsync) {
  68201. var asyncedPlugin = plugin;
  68202. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  68203. scene.loadingPluginName = plugin.name;
  68204. successHandler(assetContainer);
  68205. }).catch(function (error) {
  68206. errorHandler(error.message, error);
  68207. });
  68208. }
  68209. else {
  68210. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  68211. }
  68212. if (SceneLoader.ShowLoadingScreen) {
  68213. scene.executeWhenReady(function () {
  68214. scene.getEngine().hideLoadingUI();
  68215. });
  68216. }
  68217. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68218. };
  68219. /**
  68220. * Load a scene into an asset container
  68221. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  68222. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  68223. * @param scene is the instance of BABYLON.Scene to append to
  68224. * @param onProgress a callback with a progress event for each file being loaded
  68225. * @param pluginExtension the extension used to determine the plugin
  68226. * @returns The loaded asset container
  68227. */
  68228. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68229. if (sceneFilename === void 0) { sceneFilename = ""; }
  68230. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68231. if (onProgress === void 0) { onProgress = null; }
  68232. if (pluginExtension === void 0) { pluginExtension = null; }
  68233. return new Promise(function (resolve, reject) {
  68234. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  68235. resolve(assetContainer);
  68236. }, onProgress, function (scene, message, exception) {
  68237. reject(exception || new Error(message));
  68238. }, pluginExtension);
  68239. });
  68240. };
  68241. // Flags
  68242. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  68243. SceneLoader._ShowLoadingScreen = true;
  68244. SceneLoader._CleanBoneMatrixWeights = false;
  68245. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  68246. // Members
  68247. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  68248. SceneLoader._registeredPlugins = {};
  68249. return SceneLoader;
  68250. }());
  68251. BABYLON.SceneLoader = SceneLoader;
  68252. ;
  68253. })(BABYLON || (BABYLON = {}));
  68254. //# sourceMappingURL=babylon.sceneLoader.js.map
  68255. var BABYLON;
  68256. (function (BABYLON) {
  68257. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  68258. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68259. var parsedMaterial = parsedData.materials[index];
  68260. if (parsedMaterial.id === id) {
  68261. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68262. }
  68263. }
  68264. return null;
  68265. };
  68266. var isDescendantOf = function (mesh, names, hierarchyIds) {
  68267. for (var i in names) {
  68268. if (mesh.name === names[i]) {
  68269. hierarchyIds.push(mesh.id);
  68270. return true;
  68271. }
  68272. }
  68273. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  68274. hierarchyIds.push(mesh.id);
  68275. return true;
  68276. }
  68277. return false;
  68278. };
  68279. var logOperation = function (operation, producer) {
  68280. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  68281. };
  68282. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  68283. if (addToScene === void 0) { addToScene = false; }
  68284. var container = new BABYLON.AssetContainer(scene);
  68285. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68286. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68287. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68288. // and avoid problems with multiple concurrent .babylon loads.
  68289. var log = "importScene has failed JSON parse";
  68290. try {
  68291. var parsedData = JSON.parse(data);
  68292. log = "";
  68293. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68294. var index;
  68295. var cache;
  68296. // Lights
  68297. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  68298. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  68299. var parsedLight = parsedData.lights[index];
  68300. var light = BABYLON.Light.Parse(parsedLight, scene);
  68301. if (light) {
  68302. container.lights.push(light);
  68303. log += (index === 0 ? "\n\tLights:" : "");
  68304. log += "\n\t\t" + light.toString(fullDetails);
  68305. }
  68306. }
  68307. }
  68308. // Animations
  68309. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  68310. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  68311. var parsedAnimation = parsedData.animations[index];
  68312. var animation = BABYLON.Animation.Parse(parsedAnimation);
  68313. scene.animations.push(animation);
  68314. container.animations.push(animation);
  68315. log += (index === 0 ? "\n\tAnimations:" : "");
  68316. log += "\n\t\t" + animation.toString(fullDetails);
  68317. }
  68318. }
  68319. // Materials
  68320. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  68321. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68322. var parsedMaterial = parsedData.materials[index];
  68323. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68324. container.materials.push(mat);
  68325. log += (index === 0 ? "\n\tMaterials:" : "");
  68326. log += "\n\t\t" + mat.toString(fullDetails);
  68327. }
  68328. }
  68329. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68330. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  68331. var parsedMultiMaterial = parsedData.multiMaterials[index];
  68332. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68333. container.multiMaterials.push(mmat);
  68334. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  68335. log += "\n\t\t" + mmat.toString(fullDetails);
  68336. }
  68337. }
  68338. // Morph targets
  68339. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68340. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68341. var managerData = _a[_i];
  68342. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  68343. }
  68344. }
  68345. // Skeletons
  68346. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68347. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  68348. var parsedSkeleton = parsedData.skeletons[index];
  68349. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68350. container.skeletons.push(skeleton);
  68351. log += (index === 0 ? "\n\tSkeletons:" : "");
  68352. log += "\n\t\t" + skeleton.toString(fullDetails);
  68353. }
  68354. }
  68355. // Geometries
  68356. var geometries = parsedData.geometries;
  68357. if (geometries !== undefined && geometries !== null) {
  68358. var addedGeometry = new Array();
  68359. // Boxes
  68360. var boxes = geometries.boxes;
  68361. if (boxes !== undefined && boxes !== null) {
  68362. for (index = 0, cache = boxes.length; index < cache; index++) {
  68363. var parsedBox = boxes[index];
  68364. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  68365. }
  68366. }
  68367. // Spheres
  68368. var spheres = geometries.spheres;
  68369. if (spheres !== undefined && spheres !== null) {
  68370. for (index = 0, cache = spheres.length; index < cache; index++) {
  68371. var parsedSphere = spheres[index];
  68372. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  68373. }
  68374. }
  68375. // Cylinders
  68376. var cylinders = geometries.cylinders;
  68377. if (cylinders !== undefined && cylinders !== null) {
  68378. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68379. var parsedCylinder = cylinders[index];
  68380. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68381. }
  68382. }
  68383. // Toruses
  68384. var toruses = geometries.toruses;
  68385. if (toruses !== undefined && toruses !== null) {
  68386. for (index = 0, cache = toruses.length; index < cache; index++) {
  68387. var parsedTorus = toruses[index];
  68388. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68389. }
  68390. }
  68391. // Grounds
  68392. var grounds = geometries.grounds;
  68393. if (grounds !== undefined && grounds !== null) {
  68394. for (index = 0, cache = grounds.length; index < cache; index++) {
  68395. var parsedGround = grounds[index];
  68396. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68397. }
  68398. }
  68399. // Planes
  68400. var planes = geometries.planes;
  68401. if (planes !== undefined && planes !== null) {
  68402. for (index = 0, cache = planes.length; index < cache; index++) {
  68403. var parsedPlane = planes[index];
  68404. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68405. }
  68406. }
  68407. // TorusKnots
  68408. var torusKnots = geometries.torusKnots;
  68409. if (torusKnots !== undefined && torusKnots !== null) {
  68410. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68411. var parsedTorusKnot = torusKnots[index];
  68412. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68413. }
  68414. }
  68415. // VertexData
  68416. var vertexData = geometries.vertexData;
  68417. if (vertexData !== undefined && vertexData !== null) {
  68418. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68419. var parsedVertexData = vertexData[index];
  68420. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68421. }
  68422. }
  68423. addedGeometry.forEach(function (g) {
  68424. if (g) {
  68425. container.geometries.push(g);
  68426. }
  68427. });
  68428. }
  68429. // Transform nodes
  68430. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68431. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68432. var parsedTransformNode = parsedData.transformNodes[index];
  68433. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68434. container.transformNodes.push(node);
  68435. }
  68436. }
  68437. // Meshes
  68438. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68439. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68440. var parsedMesh = parsedData.meshes[index];
  68441. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68442. container.meshes.push(mesh);
  68443. log += (index === 0 ? "\n\tMeshes:" : "");
  68444. log += "\n\t\t" + mesh.toString(fullDetails);
  68445. }
  68446. }
  68447. // Cameras
  68448. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68449. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68450. var parsedCamera = parsedData.cameras[index];
  68451. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68452. container.cameras.push(camera);
  68453. log += (index === 0 ? "\n\tCameras:" : "");
  68454. log += "\n\t\t" + camera.toString(fullDetails);
  68455. }
  68456. }
  68457. // Browsing all the graph to connect the dots
  68458. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68459. var camera = scene.cameras[index];
  68460. if (camera._waitingParentId) {
  68461. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68462. camera._waitingParentId = null;
  68463. }
  68464. }
  68465. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68466. var light_1 = scene.lights[index];
  68467. if (light_1 && light_1._waitingParentId) {
  68468. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68469. light_1._waitingParentId = null;
  68470. }
  68471. }
  68472. // Sounds
  68473. // TODO: add sound
  68474. var loadedSounds = [];
  68475. var loadedSound;
  68476. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68477. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68478. var parsedSound = parsedData.sounds[index];
  68479. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68480. if (!parsedSound.url)
  68481. parsedSound.url = parsedSound.name;
  68482. if (!loadedSounds[parsedSound.url]) {
  68483. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68484. loadedSounds[parsedSound.url] = loadedSound;
  68485. container.sounds.push(loadedSound);
  68486. }
  68487. else {
  68488. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68489. }
  68490. }
  68491. else {
  68492. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68493. }
  68494. }
  68495. }
  68496. loadedSounds = [];
  68497. // Connect parents & children and parse actions
  68498. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68499. var transformNode = scene.transformNodes[index];
  68500. if (transformNode._waitingParentId) {
  68501. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68502. transformNode._waitingParentId = null;
  68503. }
  68504. }
  68505. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68506. var mesh = scene.meshes[index];
  68507. if (mesh._waitingParentId) {
  68508. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68509. mesh._waitingParentId = null;
  68510. }
  68511. if (mesh._waitingActions) {
  68512. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68513. mesh._waitingActions = null;
  68514. }
  68515. }
  68516. // freeze world matrix application
  68517. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68518. var currentMesh = scene.meshes[index];
  68519. if (currentMesh._waitingFreezeWorldMatrix) {
  68520. currentMesh.freezeWorldMatrix();
  68521. currentMesh._waitingFreezeWorldMatrix = null;
  68522. }
  68523. else {
  68524. currentMesh.computeWorldMatrix(true);
  68525. }
  68526. }
  68527. // Particles Systems
  68528. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68529. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68530. var parsedParticleSystem = parsedData.particleSystems[index];
  68531. if (parsedParticleSystem.activeParticleCount) {
  68532. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68533. container.particleSystems.push(ps);
  68534. }
  68535. else {
  68536. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68537. container.particleSystems.push(ps);
  68538. }
  68539. }
  68540. }
  68541. // Lens flares
  68542. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  68543. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  68544. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  68545. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  68546. container.lensFlareSystems.push(lf);
  68547. }
  68548. }
  68549. // Shadows
  68550. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68551. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68552. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68553. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68554. container.shadowGenerators.push(sg);
  68555. }
  68556. }
  68557. // Lights exclusions / inclusions
  68558. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68559. var light_2 = scene.lights[index];
  68560. // Excluded check
  68561. if (light_2._excludedMeshesIds.length > 0) {
  68562. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68563. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68564. if (excludedMesh) {
  68565. light_2.excludedMeshes.push(excludedMesh);
  68566. }
  68567. }
  68568. light_2._excludedMeshesIds = [];
  68569. }
  68570. // Included check
  68571. if (light_2._includedOnlyMeshesIds.length > 0) {
  68572. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68573. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68574. if (includedOnlyMesh) {
  68575. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68576. }
  68577. }
  68578. light_2._includedOnlyMeshesIds = [];
  68579. }
  68580. }
  68581. // Effect layers
  68582. if (parsedData.effectLayers) {
  68583. for (index = 0; index < parsedData.effectLayers.length; index++) {
  68584. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  68585. container.effectLayers.push(effectLayer);
  68586. }
  68587. }
  68588. // Actions (scene)
  68589. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68590. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68591. }
  68592. if (!addToScene) {
  68593. container.removeAllFromScene();
  68594. }
  68595. }
  68596. catch (err) {
  68597. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68598. if (onError) {
  68599. onError(msg, err);
  68600. }
  68601. else {
  68602. BABYLON.Tools.Log(msg);
  68603. throw err;
  68604. }
  68605. }
  68606. finally {
  68607. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68608. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68609. }
  68610. }
  68611. return container;
  68612. };
  68613. BABYLON.SceneLoader.RegisterPlugin({
  68614. name: "babylon.js",
  68615. extensions: ".babylon",
  68616. canDirectLoad: function (data) {
  68617. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68618. return true;
  68619. }
  68620. return false;
  68621. },
  68622. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68623. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68624. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68625. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68626. // and avoid problems with multiple concurrent .babylon loads.
  68627. var log = "importMesh has failed JSON parse";
  68628. try {
  68629. var parsedData = JSON.parse(data);
  68630. log = "";
  68631. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68632. if (!meshesNames) {
  68633. meshesNames = null;
  68634. }
  68635. else if (!Array.isArray(meshesNames)) {
  68636. meshesNames = [meshesNames];
  68637. }
  68638. var hierarchyIds = new Array();
  68639. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68640. var loadedSkeletonsIds = [];
  68641. var loadedMaterialsIds = [];
  68642. var index;
  68643. var cache;
  68644. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68645. var parsedMesh = parsedData.meshes[index];
  68646. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68647. if (meshesNames !== null) {
  68648. // Remove found mesh name from list.
  68649. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68650. }
  68651. //Geometry?
  68652. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68653. //does the file contain geometries?
  68654. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68655. //find the correct geometry and add it to the scene
  68656. var found = false;
  68657. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68658. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68659. return;
  68660. }
  68661. else {
  68662. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68663. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68664. switch (geometryType) {
  68665. case "boxes":
  68666. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68667. break;
  68668. case "spheres":
  68669. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68670. break;
  68671. case "cylinders":
  68672. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68673. break;
  68674. case "toruses":
  68675. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68676. break;
  68677. case "grounds":
  68678. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68679. break;
  68680. case "planes":
  68681. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68682. break;
  68683. case "torusKnots":
  68684. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68685. break;
  68686. case "vertexData":
  68687. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68688. break;
  68689. }
  68690. found = true;
  68691. }
  68692. });
  68693. }
  68694. });
  68695. if (found === false) {
  68696. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68697. }
  68698. }
  68699. }
  68700. // Material ?
  68701. if (parsedMesh.materialId) {
  68702. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68703. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68704. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68705. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68706. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68707. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68708. var subMatId = parsedMultiMaterial.materials[matIndex];
  68709. loadedMaterialsIds.push(subMatId);
  68710. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68711. if (mat) {
  68712. log += "\n\tMaterial " + mat.toString(fullDetails);
  68713. }
  68714. }
  68715. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68716. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68717. if (mmat) {
  68718. materialFound = true;
  68719. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68720. }
  68721. break;
  68722. }
  68723. }
  68724. }
  68725. if (materialFound === false) {
  68726. loadedMaterialsIds.push(parsedMesh.materialId);
  68727. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68728. if (!mat) {
  68729. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68730. }
  68731. else {
  68732. log += "\n\tMaterial " + mat.toString(fullDetails);
  68733. }
  68734. }
  68735. }
  68736. // Skeleton ?
  68737. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68738. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68739. if (skeletonAlreadyLoaded === false) {
  68740. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68741. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68742. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68743. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68744. skeletons.push(skeleton);
  68745. loadedSkeletonsIds.push(parsedSkeleton.id);
  68746. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68747. }
  68748. }
  68749. }
  68750. }
  68751. // Morph targets ?
  68752. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68753. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68754. var managerData = _a[_i];
  68755. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68756. }
  68757. }
  68758. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68759. meshes.push(mesh);
  68760. log += "\n\tMesh " + mesh.toString(fullDetails);
  68761. }
  68762. }
  68763. // Connecting parents
  68764. var currentMesh;
  68765. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68766. currentMesh = scene.meshes[index];
  68767. if (currentMesh._waitingParentId) {
  68768. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68769. currentMesh._waitingParentId = null;
  68770. }
  68771. }
  68772. // freeze and compute world matrix application
  68773. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68774. currentMesh = scene.meshes[index];
  68775. if (currentMesh._waitingFreezeWorldMatrix) {
  68776. currentMesh.freezeWorldMatrix();
  68777. currentMesh._waitingFreezeWorldMatrix = null;
  68778. }
  68779. else {
  68780. currentMesh.computeWorldMatrix(true);
  68781. }
  68782. }
  68783. }
  68784. // Particles
  68785. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68786. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68787. var parsedParticleSystem = parsedData.particleSystems[index];
  68788. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68789. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68790. }
  68791. }
  68792. }
  68793. return true;
  68794. }
  68795. catch (err) {
  68796. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68797. if (onError) {
  68798. onError(msg, err);
  68799. }
  68800. else {
  68801. BABYLON.Tools.Log(msg);
  68802. throw err;
  68803. }
  68804. }
  68805. finally {
  68806. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68807. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68808. }
  68809. }
  68810. return false;
  68811. },
  68812. load: function (scene, data, rootUrl, onError) {
  68813. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68814. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68815. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68816. // and avoid problems with multiple concurrent .babylon loads.
  68817. var log = "importScene has failed JSON parse";
  68818. try {
  68819. var parsedData = JSON.parse(data);
  68820. log = "";
  68821. // Scene
  68822. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68823. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68824. }
  68825. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68826. scene.autoClear = parsedData.autoClear;
  68827. }
  68828. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68829. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68830. }
  68831. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68832. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68833. }
  68834. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68835. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68836. }
  68837. // Fog
  68838. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68839. scene.fogMode = parsedData.fogMode;
  68840. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68841. scene.fogStart = parsedData.fogStart;
  68842. scene.fogEnd = parsedData.fogEnd;
  68843. scene.fogDensity = parsedData.fogDensity;
  68844. log += "\tFog mode for scene: ";
  68845. switch (scene.fogMode) {
  68846. // getters not compiling, so using hardcoded
  68847. case 1:
  68848. log += "exp\n";
  68849. break;
  68850. case 2:
  68851. log += "exp2\n";
  68852. break;
  68853. case 3:
  68854. log += "linear\n";
  68855. break;
  68856. }
  68857. }
  68858. //Physics
  68859. if (parsedData.physicsEnabled) {
  68860. var physicsPlugin;
  68861. if (parsedData.physicsEngine === "cannon") {
  68862. physicsPlugin = new BABYLON.CannonJSPlugin();
  68863. }
  68864. else if (parsedData.physicsEngine === "oimo") {
  68865. physicsPlugin = new BABYLON.OimoJSPlugin();
  68866. }
  68867. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68868. //else - default engine, which is currently oimo
  68869. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68870. scene.enablePhysics(physicsGravity, physicsPlugin);
  68871. }
  68872. // Metadata
  68873. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68874. scene.metadata = parsedData.metadata;
  68875. }
  68876. //collisions, if defined. otherwise, default is true
  68877. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68878. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68879. }
  68880. scene.workerCollisions = !!parsedData.workerCollisions;
  68881. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68882. if (!container) {
  68883. return false;
  68884. }
  68885. if (parsedData.autoAnimate) {
  68886. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68887. }
  68888. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68889. scene.setActiveCameraByID(parsedData.activeCameraID);
  68890. }
  68891. // Environment texture
  68892. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68893. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68894. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68895. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68896. if (parsedData.environmentTextureRotationY) {
  68897. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68898. }
  68899. scene.environmentTexture = hdrTexture;
  68900. }
  68901. else {
  68902. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68903. if (parsedData.environmentTextureRotationY) {
  68904. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68905. }
  68906. scene.environmentTexture = cubeTexture;
  68907. }
  68908. if (parsedData.createDefaultSkybox === true) {
  68909. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68910. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68911. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68912. }
  68913. }
  68914. // Finish
  68915. return true;
  68916. }
  68917. catch (err) {
  68918. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68919. if (onError) {
  68920. onError(msg, err);
  68921. }
  68922. else {
  68923. BABYLON.Tools.Log(msg);
  68924. throw err;
  68925. }
  68926. }
  68927. finally {
  68928. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68929. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68930. }
  68931. }
  68932. return false;
  68933. },
  68934. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68935. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68936. return container;
  68937. }
  68938. });
  68939. })(BABYLON || (BABYLON = {}));
  68940. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68941. var BABYLON;
  68942. (function (BABYLON) {
  68943. var FilesInput = /** @class */ (function () {
  68944. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68945. this.onProcessFileCallback = function () { return true; };
  68946. this._engine = engine;
  68947. this._currentScene = scene;
  68948. this._sceneLoadedCallback = sceneLoadedCallback;
  68949. this._progressCallback = progressCallback;
  68950. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68951. this._textureLoadingCallback = textureLoadingCallback;
  68952. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68953. this._onReloadCallback = onReloadCallback;
  68954. this._errorCallback = errorCallback;
  68955. }
  68956. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68957. var _this = this;
  68958. if (elementToMonitor) {
  68959. this._elementToMonitor = elementToMonitor;
  68960. this._dragEnterHandler = function (e) { _this.drag(e); };
  68961. this._dragOverHandler = function (e) { _this.drag(e); };
  68962. this._dropHandler = function (e) { _this.drop(e); };
  68963. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68964. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68965. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68966. }
  68967. };
  68968. FilesInput.prototype.dispose = function () {
  68969. if (!this._elementToMonitor) {
  68970. return;
  68971. }
  68972. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68973. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68974. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68975. };
  68976. FilesInput.prototype.renderFunction = function () {
  68977. if (this._additionalRenderLoopLogicCallback) {
  68978. this._additionalRenderLoopLogicCallback();
  68979. }
  68980. if (this._currentScene) {
  68981. if (this._textureLoadingCallback) {
  68982. var remaining = this._currentScene.getWaitingItemsCount();
  68983. if (remaining > 0) {
  68984. this._textureLoadingCallback(remaining);
  68985. }
  68986. }
  68987. this._currentScene.render();
  68988. }
  68989. };
  68990. FilesInput.prototype.drag = function (e) {
  68991. e.stopPropagation();
  68992. e.preventDefault();
  68993. };
  68994. FilesInput.prototype.drop = function (eventDrop) {
  68995. eventDrop.stopPropagation();
  68996. eventDrop.preventDefault();
  68997. this.loadFiles(eventDrop);
  68998. };
  68999. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  69000. var _this = this;
  69001. var reader = folder.createReader();
  69002. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  69003. reader.readEntries(function (entries) {
  69004. remaining.count += entries.length;
  69005. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  69006. var entry = entries_1[_i];
  69007. if (entry.isFile) {
  69008. entry.file(function (file) {
  69009. file.correctName = relativePath + file.name;
  69010. files.push(file);
  69011. if (--remaining.count === 0) {
  69012. callback();
  69013. }
  69014. });
  69015. }
  69016. else if (entry.isDirectory) {
  69017. _this._traverseFolder(entry, files, remaining, callback);
  69018. }
  69019. }
  69020. if (--remaining.count) {
  69021. callback();
  69022. }
  69023. });
  69024. };
  69025. FilesInput.prototype._processFiles = function (files) {
  69026. for (var i = 0; i < files.length; i++) {
  69027. var name = files[i].correctName.toLowerCase();
  69028. var extension = name.split('.').pop();
  69029. if (!this.onProcessFileCallback(files[i], name, extension)) {
  69030. continue;
  69031. }
  69032. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  69033. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  69034. this._sceneFileToLoad = files[i];
  69035. }
  69036. else {
  69037. FilesInput.FilesToLoad[name] = files[i];
  69038. }
  69039. }
  69040. };
  69041. FilesInput.prototype.loadFiles = function (event) {
  69042. var _this = this;
  69043. if (this._startingProcessingFilesCallback)
  69044. this._startingProcessingFilesCallback();
  69045. // Handling data transfer via drag'n'drop
  69046. if (event && event.dataTransfer && event.dataTransfer.files) {
  69047. this._filesToLoad = event.dataTransfer.files;
  69048. }
  69049. // Handling files from input files
  69050. if (event && event.target && event.target.files) {
  69051. this._filesToLoad = event.target.files;
  69052. }
  69053. if (this._filesToLoad && this._filesToLoad.length > 0) {
  69054. var files_1 = new Array();
  69055. var folders = [];
  69056. var items = event.dataTransfer ? event.dataTransfer.items : null;
  69057. for (var i = 0; i < this._filesToLoad.length; i++) {
  69058. var fileToLoad = this._filesToLoad[i];
  69059. var name_1 = fileToLoad.name.toLowerCase();
  69060. var entry = void 0;
  69061. fileToLoad.correctName = name_1;
  69062. if (items) {
  69063. var item = items[i];
  69064. if (item.getAsEntry) {
  69065. entry = item.getAsEntry();
  69066. }
  69067. else if (item.webkitGetAsEntry) {
  69068. entry = item.webkitGetAsEntry();
  69069. }
  69070. }
  69071. if (!entry) {
  69072. files_1.push(fileToLoad);
  69073. }
  69074. else {
  69075. if (entry.isDirectory) {
  69076. folders.push(entry);
  69077. }
  69078. else {
  69079. files_1.push(fileToLoad);
  69080. }
  69081. }
  69082. }
  69083. if (folders.length === 0) {
  69084. this._processFiles(files_1);
  69085. this._processReload();
  69086. }
  69087. else {
  69088. var remaining = { count: folders.length };
  69089. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  69090. var folder = folders_1[_i];
  69091. this._traverseFolder(folder, files_1, remaining, function () {
  69092. _this._processFiles(files_1);
  69093. if (remaining.count === 0) {
  69094. _this._processReload();
  69095. }
  69096. });
  69097. }
  69098. }
  69099. }
  69100. };
  69101. FilesInput.prototype._processReload = function () {
  69102. if (this._onReloadCallback) {
  69103. this._onReloadCallback(this._sceneFileToLoad);
  69104. }
  69105. else {
  69106. this.reload();
  69107. }
  69108. };
  69109. FilesInput.prototype.reload = function () {
  69110. var _this = this;
  69111. // If a scene file has been provided
  69112. if (this._sceneFileToLoad) {
  69113. if (this._currentScene) {
  69114. if (BABYLON.Tools.errorsCount > 0) {
  69115. BABYLON.Tools.ClearLogCache();
  69116. }
  69117. this._engine.stopRenderLoop();
  69118. }
  69119. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  69120. if (_this._progressCallback) {
  69121. _this._progressCallback(progress);
  69122. }
  69123. }).then(function (scene) {
  69124. if (_this._currentScene) {
  69125. _this._currentScene.dispose();
  69126. }
  69127. _this._currentScene = scene;
  69128. if (_this._sceneLoadedCallback) {
  69129. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  69130. }
  69131. // Wait for textures and shaders to be ready
  69132. _this._currentScene.executeWhenReady(function () {
  69133. _this._engine.runRenderLoop(function () {
  69134. _this.renderFunction();
  69135. });
  69136. });
  69137. }).catch(function (error) {
  69138. if (_this._errorCallback) {
  69139. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  69140. }
  69141. });
  69142. }
  69143. else {
  69144. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  69145. }
  69146. };
  69147. FilesInput.FilesToLoad = {};
  69148. return FilesInput;
  69149. }());
  69150. BABYLON.FilesInput = FilesInput;
  69151. })(BABYLON || (BABYLON = {}));
  69152. //# sourceMappingURL=babylon.filesInput.js.map
  69153. var BABYLON;
  69154. (function (BABYLON) {
  69155. /**
  69156. * This class implement a typical dictionary using a string as key and the generic type T as value.
  69157. * The underlying implementation relies on an associative array to ensure the best performances.
  69158. * The value can be anything including 'null' but except 'undefined'
  69159. */
  69160. var StringDictionary = /** @class */ (function () {
  69161. function StringDictionary() {
  69162. this._count = 0;
  69163. this._data = {};
  69164. }
  69165. /**
  69166. * This will clear this dictionary and copy the content from the 'source' one.
  69167. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  69168. * @param source the dictionary to take the content from and copy to this dictionary
  69169. */
  69170. StringDictionary.prototype.copyFrom = function (source) {
  69171. var _this = this;
  69172. this.clear();
  69173. source.forEach(function (t, v) { return _this.add(t, v); });
  69174. };
  69175. /**
  69176. * Get a value based from its key
  69177. * @param key the given key to get the matching value from
  69178. * @return the value if found, otherwise undefined is returned
  69179. */
  69180. StringDictionary.prototype.get = function (key) {
  69181. var val = this._data[key];
  69182. if (val !== undefined) {
  69183. return val;
  69184. }
  69185. return undefined;
  69186. };
  69187. /**
  69188. * Get a value from its key or add it if it doesn't exist.
  69189. * This method will ensure you that a given key/data will be present in the dictionary.
  69190. * @param key the given key to get the matching value from
  69191. * @param factory the factory that will create the value if the key is not present in the dictionary.
  69192. * The factory will only be invoked if there's no data for the given key.
  69193. * @return the value corresponding to the key.
  69194. */
  69195. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  69196. var val = this.get(key);
  69197. if (val !== undefined) {
  69198. return val;
  69199. }
  69200. val = factory(key);
  69201. if (val) {
  69202. this.add(key, val);
  69203. }
  69204. return val;
  69205. };
  69206. /**
  69207. * Get a value from its key if present in the dictionary otherwise add it
  69208. * @param key the key to get the value from
  69209. * @param val if there's no such key/value pair in the dictionary add it with this value
  69210. * @return the value corresponding to the key
  69211. */
  69212. StringDictionary.prototype.getOrAdd = function (key, val) {
  69213. var curVal = this.get(key);
  69214. if (curVal !== undefined) {
  69215. return curVal;
  69216. }
  69217. this.add(key, val);
  69218. return val;
  69219. };
  69220. /**
  69221. * Check if there's a given key in the dictionary
  69222. * @param key the key to check for
  69223. * @return true if the key is present, false otherwise
  69224. */
  69225. StringDictionary.prototype.contains = function (key) {
  69226. return this._data[key] !== undefined;
  69227. };
  69228. /**
  69229. * Add a new key and its corresponding value
  69230. * @param key the key to add
  69231. * @param value the value corresponding to the key
  69232. * @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
  69233. */
  69234. StringDictionary.prototype.add = function (key, value) {
  69235. if (this._data[key] !== undefined) {
  69236. return false;
  69237. }
  69238. this._data[key] = value;
  69239. ++this._count;
  69240. return true;
  69241. };
  69242. StringDictionary.prototype.set = function (key, value) {
  69243. if (this._data[key] === undefined) {
  69244. return false;
  69245. }
  69246. this._data[key] = value;
  69247. return true;
  69248. };
  69249. /**
  69250. * Get the element of the given key and remove it from the dictionary
  69251. * @param key
  69252. */
  69253. StringDictionary.prototype.getAndRemove = function (key) {
  69254. var val = this.get(key);
  69255. if (val !== undefined) {
  69256. delete this._data[key];
  69257. --this._count;
  69258. return val;
  69259. }
  69260. return null;
  69261. };
  69262. /**
  69263. * Remove a key/value from the dictionary.
  69264. * @param key the key to remove
  69265. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  69266. */
  69267. StringDictionary.prototype.remove = function (key) {
  69268. if (this.contains(key)) {
  69269. delete this._data[key];
  69270. --this._count;
  69271. return true;
  69272. }
  69273. return false;
  69274. };
  69275. /**
  69276. * Clear the whole content of the dictionary
  69277. */
  69278. StringDictionary.prototype.clear = function () {
  69279. this._data = {};
  69280. this._count = 0;
  69281. };
  69282. Object.defineProperty(StringDictionary.prototype, "count", {
  69283. get: function () {
  69284. return this._count;
  69285. },
  69286. enumerable: true,
  69287. configurable: true
  69288. });
  69289. /**
  69290. * Execute a callback on each key/val of the dictionary.
  69291. * Note that you can remove any element in this dictionary in the callback implementation
  69292. * @param callback the callback to execute on a given key/value pair
  69293. */
  69294. StringDictionary.prototype.forEach = function (callback) {
  69295. for (var cur in this._data) {
  69296. var val = this._data[cur];
  69297. callback(cur, val);
  69298. }
  69299. };
  69300. /**
  69301. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  69302. * If the callback returns null or undefined the method will iterate to the next key/value pair
  69303. * Note that you can remove any element in this dictionary in the callback implementation
  69304. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  69305. */
  69306. StringDictionary.prototype.first = function (callback) {
  69307. for (var cur in this._data) {
  69308. var val = this._data[cur];
  69309. var res = callback(cur, val);
  69310. if (res) {
  69311. return res;
  69312. }
  69313. }
  69314. return null;
  69315. };
  69316. return StringDictionary;
  69317. }());
  69318. BABYLON.StringDictionary = StringDictionary;
  69319. })(BABYLON || (BABYLON = {}));
  69320. //# sourceMappingURL=babylon.stringDictionary.js.map
  69321. var BABYLON;
  69322. (function (BABYLON) {
  69323. var Tags = /** @class */ (function () {
  69324. function Tags() {
  69325. }
  69326. Tags.EnableFor = function (obj) {
  69327. obj._tags = obj._tags || {};
  69328. obj.hasTags = function () {
  69329. return Tags.HasTags(obj);
  69330. };
  69331. obj.addTags = function (tagsString) {
  69332. return Tags.AddTagsTo(obj, tagsString);
  69333. };
  69334. obj.removeTags = function (tagsString) {
  69335. return Tags.RemoveTagsFrom(obj, tagsString);
  69336. };
  69337. obj.matchesTagsQuery = function (tagsQuery) {
  69338. return Tags.MatchesQuery(obj, tagsQuery);
  69339. };
  69340. };
  69341. Tags.DisableFor = function (obj) {
  69342. delete obj._tags;
  69343. delete obj.hasTags;
  69344. delete obj.addTags;
  69345. delete obj.removeTags;
  69346. delete obj.matchesTagsQuery;
  69347. };
  69348. Tags.HasTags = function (obj) {
  69349. if (!obj._tags) {
  69350. return false;
  69351. }
  69352. return !BABYLON.Tools.IsEmpty(obj._tags);
  69353. };
  69354. Tags.GetTags = function (obj, asString) {
  69355. if (asString === void 0) { asString = true; }
  69356. if (!obj._tags) {
  69357. return null;
  69358. }
  69359. if (asString) {
  69360. var tagsArray = [];
  69361. for (var tag in obj._tags) {
  69362. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  69363. tagsArray.push(tag);
  69364. }
  69365. }
  69366. return tagsArray.join(" ");
  69367. }
  69368. else {
  69369. return obj._tags;
  69370. }
  69371. };
  69372. // the tags 'true' and 'false' are reserved and cannot be used as tags
  69373. // a tag cannot start with '||', '&&', and '!'
  69374. // it cannot contain whitespaces
  69375. Tags.AddTagsTo = function (obj, tagsString) {
  69376. if (!tagsString) {
  69377. return;
  69378. }
  69379. if (typeof tagsString !== "string") {
  69380. return;
  69381. }
  69382. var tags = tagsString.split(" ");
  69383. tags.forEach(function (tag, index, array) {
  69384. Tags._AddTagTo(obj, tag);
  69385. });
  69386. };
  69387. Tags._AddTagTo = function (obj, tag) {
  69388. tag = tag.trim();
  69389. if (tag === "" || tag === "true" || tag === "false") {
  69390. return;
  69391. }
  69392. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69393. return;
  69394. }
  69395. Tags.EnableFor(obj);
  69396. obj._tags[tag] = true;
  69397. };
  69398. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69399. if (!Tags.HasTags(obj)) {
  69400. return;
  69401. }
  69402. var tags = tagsString.split(" ");
  69403. for (var t in tags) {
  69404. Tags._RemoveTagFrom(obj, tags[t]);
  69405. }
  69406. };
  69407. Tags._RemoveTagFrom = function (obj, tag) {
  69408. delete obj._tags[tag];
  69409. };
  69410. Tags.MatchesQuery = function (obj, tagsQuery) {
  69411. if (tagsQuery === undefined) {
  69412. return true;
  69413. }
  69414. if (tagsQuery === "") {
  69415. return Tags.HasTags(obj);
  69416. }
  69417. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69418. };
  69419. return Tags;
  69420. }());
  69421. BABYLON.Tags = Tags;
  69422. })(BABYLON || (BABYLON = {}));
  69423. //# sourceMappingURL=babylon.tags.js.map
  69424. var BABYLON;
  69425. (function (BABYLON) {
  69426. /**
  69427. * Class used to evalaute queries containing `and` and `or` operators
  69428. */
  69429. var AndOrNotEvaluator = /** @class */ (function () {
  69430. function AndOrNotEvaluator() {
  69431. }
  69432. /**
  69433. * Evaluate a query
  69434. * @param query defines the query to evaluate
  69435. * @param evaluateCallback defines the callback used to filter result
  69436. * @returns true if the query matches
  69437. */
  69438. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69439. if (!query.match(/\([^\(\)]*\)/g)) {
  69440. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69441. }
  69442. else {
  69443. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69444. // remove parenthesis
  69445. r = r.slice(1, r.length - 1);
  69446. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69447. });
  69448. }
  69449. if (query === "true") {
  69450. return true;
  69451. }
  69452. if (query === "false") {
  69453. return false;
  69454. }
  69455. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69456. };
  69457. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69458. evaluateCallback = evaluateCallback || (function (r) {
  69459. return r === "true" ? true : false;
  69460. });
  69461. var result;
  69462. var or = parenthesisContent.split("||");
  69463. for (var i in or) {
  69464. if (or.hasOwnProperty(i)) {
  69465. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69466. var and = ori.split("&&");
  69467. if (and.length > 1) {
  69468. for (var j = 0; j < and.length; ++j) {
  69469. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69470. if (andj !== "true" && andj !== "false") {
  69471. if (andj[0] === "!") {
  69472. result = !evaluateCallback(andj.substring(1));
  69473. }
  69474. else {
  69475. result = evaluateCallback(andj);
  69476. }
  69477. }
  69478. else {
  69479. result = andj === "true" ? true : false;
  69480. }
  69481. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69482. ori = "false";
  69483. break;
  69484. }
  69485. }
  69486. }
  69487. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69488. result = true;
  69489. break;
  69490. }
  69491. // result equals false (or undefined)
  69492. if (ori !== "true" && ori !== "false") {
  69493. if (ori[0] === "!") {
  69494. result = !evaluateCallback(ori.substring(1));
  69495. }
  69496. else {
  69497. result = evaluateCallback(ori);
  69498. }
  69499. }
  69500. else {
  69501. result = ori === "true" ? true : false;
  69502. }
  69503. }
  69504. }
  69505. // the whole parenthesis scope is replaced by 'true' or 'false'
  69506. return result ? "true" : "false";
  69507. };
  69508. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69509. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69510. // remove whitespaces
  69511. r = r.replace(/[\s]/g, function () { return ""; });
  69512. return r.length % 2 ? "!" : "";
  69513. });
  69514. booleanString = booleanString.trim();
  69515. if (booleanString === "!true") {
  69516. booleanString = "false";
  69517. }
  69518. else if (booleanString === "!false") {
  69519. booleanString = "true";
  69520. }
  69521. return booleanString;
  69522. };
  69523. return AndOrNotEvaluator;
  69524. }());
  69525. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69526. })(BABYLON || (BABYLON = {}));
  69527. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69528. var BABYLON;
  69529. (function (BABYLON) {
  69530. /**
  69531. * Class used to enable access to IndexedDB
  69532. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69533. */
  69534. var Database = /** @class */ (function () {
  69535. /**
  69536. * Creates a new Database
  69537. * @param urlToScene defines the url to load the scene
  69538. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69539. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69540. */
  69541. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69542. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69543. var _this = this;
  69544. // Handling various flavors of prefixed version of IndexedDB
  69545. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69546. this.callbackManifestChecked = callbackManifestChecked;
  69547. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69548. this.db = null;
  69549. this._enableSceneOffline = false;
  69550. this._enableTexturesOffline = false;
  69551. this.manifestVersionFound = 0;
  69552. this.mustUpdateRessources = false;
  69553. this.hasReachedQuota = false;
  69554. if (!Database.IDBStorageEnabled) {
  69555. this.callbackManifestChecked(true);
  69556. }
  69557. else {
  69558. if (disableManifestCheck) {
  69559. this._enableSceneOffline = true;
  69560. this._enableTexturesOffline = true;
  69561. this.manifestVersionFound = 1;
  69562. BABYLON.Tools.SetImmediate(function () {
  69563. _this.callbackManifestChecked(true);
  69564. });
  69565. }
  69566. else {
  69567. this._checkManifestFile();
  69568. }
  69569. }
  69570. }
  69571. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69572. /**
  69573. * Gets a boolean indicating if scene must be saved in the database
  69574. */
  69575. get: function () {
  69576. return this._enableSceneOffline;
  69577. },
  69578. enumerable: true,
  69579. configurable: true
  69580. });
  69581. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69582. /**
  69583. * Gets a boolean indicating if textures must be saved in the database
  69584. */
  69585. get: function () {
  69586. return this._enableTexturesOffline;
  69587. },
  69588. enumerable: true,
  69589. configurable: true
  69590. });
  69591. Database.prototype._checkManifestFile = function () {
  69592. var _this = this;
  69593. var noManifestFile = function () {
  69594. _this._enableSceneOffline = false;
  69595. _this._enableTexturesOffline = false;
  69596. _this.callbackManifestChecked(false);
  69597. };
  69598. var timeStampUsed = false;
  69599. var manifestURL = this.currentSceneUrl + ".manifest";
  69600. var xhr = new XMLHttpRequest();
  69601. if (navigator.onLine) {
  69602. // Adding a timestamp to by-pass browsers' cache
  69603. timeStampUsed = true;
  69604. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69605. }
  69606. xhr.open("GET", manifestURL, true);
  69607. xhr.addEventListener("load", function () {
  69608. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69609. try {
  69610. var manifestFile = JSON.parse(xhr.response);
  69611. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69612. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69613. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69614. _this.manifestVersionFound = manifestFile.version;
  69615. }
  69616. if (_this.callbackManifestChecked) {
  69617. _this.callbackManifestChecked(true);
  69618. }
  69619. }
  69620. catch (ex) {
  69621. noManifestFile();
  69622. }
  69623. }
  69624. else {
  69625. noManifestFile();
  69626. }
  69627. }, false);
  69628. xhr.addEventListener("error", function (event) {
  69629. if (timeStampUsed) {
  69630. timeStampUsed = false;
  69631. // Let's retry without the timeStamp
  69632. // It could fail when coupled with HTML5 Offline API
  69633. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69634. xhr.open("GET", retryManifestURL, true);
  69635. xhr.send();
  69636. }
  69637. else {
  69638. noManifestFile();
  69639. }
  69640. }, false);
  69641. try {
  69642. xhr.send();
  69643. }
  69644. catch (ex) {
  69645. BABYLON.Tools.Error("Error on XHR send request.");
  69646. this.callbackManifestChecked(false);
  69647. }
  69648. };
  69649. /**
  69650. * Open the database and make it available
  69651. * @param successCallback defines the callback to call on success
  69652. * @param errorCallback defines the callback to call on error
  69653. */
  69654. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69655. var _this = this;
  69656. var handleError = function () {
  69657. _this.isSupported = false;
  69658. if (errorCallback)
  69659. errorCallback();
  69660. };
  69661. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69662. // Your browser doesn't support IndexedDB
  69663. this.isSupported = false;
  69664. if (errorCallback)
  69665. errorCallback();
  69666. }
  69667. else {
  69668. // If the DB hasn't been opened or created yet
  69669. if (!this.db) {
  69670. this.hasReachedQuota = false;
  69671. this.isSupported = true;
  69672. var request = this.idbFactory.open("babylonjs", 1);
  69673. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69674. request.onerror = function (event) {
  69675. handleError();
  69676. };
  69677. // executes when a version change transaction cannot complete due to other active transactions
  69678. request.onblocked = function (event) {
  69679. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69680. handleError();
  69681. };
  69682. // DB has been opened successfully
  69683. request.onsuccess = function (event) {
  69684. _this.db = request.result;
  69685. successCallback();
  69686. };
  69687. // Initialization of the DB. Creating Scenes & Textures stores
  69688. request.onupgradeneeded = function (event) {
  69689. _this.db = (event.target).result;
  69690. if (_this.db) {
  69691. try {
  69692. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69693. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69694. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69695. }
  69696. catch (ex) {
  69697. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69698. handleError();
  69699. }
  69700. }
  69701. };
  69702. }
  69703. // DB has already been created and opened
  69704. else {
  69705. if (successCallback)
  69706. successCallback();
  69707. }
  69708. }
  69709. };
  69710. /**
  69711. * Loads an image from the database
  69712. * @param url defines the url to load from
  69713. * @param image defines the target DOM image
  69714. */
  69715. Database.prototype.loadImageFromDB = function (url, image) {
  69716. var _this = this;
  69717. var completeURL = Database._ReturnFullUrlLocation(url);
  69718. var saveAndLoadImage = function () {
  69719. if (!_this.hasReachedQuota && _this.db !== null) {
  69720. // the texture is not yet in the DB, let's try to save it
  69721. _this._saveImageIntoDBAsync(completeURL, image);
  69722. }
  69723. // If the texture is not in the DB and we've reached the DB quota limit
  69724. // let's load it directly from the web
  69725. else {
  69726. image.src = url;
  69727. }
  69728. };
  69729. if (!this.mustUpdateRessources) {
  69730. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69731. }
  69732. // First time we're download the images or update requested in the manifest file by a version change
  69733. else {
  69734. saveAndLoadImage();
  69735. }
  69736. };
  69737. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69738. if (this.isSupported && this.db !== null) {
  69739. var texture;
  69740. var transaction = this.db.transaction(["textures"]);
  69741. transaction.onabort = function (event) {
  69742. image.src = url;
  69743. };
  69744. transaction.oncomplete = function (event) {
  69745. var blobTextureURL;
  69746. if (texture) {
  69747. var URL = window.URL || window.webkitURL;
  69748. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69749. image.onerror = function () {
  69750. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69751. image.src = url;
  69752. };
  69753. image.src = blobTextureURL;
  69754. }
  69755. else {
  69756. notInDBCallback();
  69757. }
  69758. };
  69759. var getRequest = transaction.objectStore("textures").get(url);
  69760. getRequest.onsuccess = function (event) {
  69761. texture = (event.target).result;
  69762. };
  69763. getRequest.onerror = function (event) {
  69764. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69765. image.src = url;
  69766. };
  69767. }
  69768. else {
  69769. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69770. image.src = url;
  69771. }
  69772. };
  69773. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69774. var _this = this;
  69775. if (this.isSupported) {
  69776. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69777. var generateBlobUrl = function () {
  69778. var blobTextureURL;
  69779. if (blob) {
  69780. var URL = window.URL || window.webkitURL;
  69781. try {
  69782. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69783. }
  69784. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69785. catch (ex) {
  69786. blobTextureURL = URL.createObjectURL(blob);
  69787. }
  69788. }
  69789. if (blobTextureURL) {
  69790. image.src = blobTextureURL;
  69791. }
  69792. };
  69793. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69794. var xhr = new XMLHttpRequest(), blob;
  69795. xhr.open("GET", url, true);
  69796. xhr.responseType = "blob";
  69797. xhr.addEventListener("load", function () {
  69798. if (xhr.status === 200 && _this.db) {
  69799. // Blob as response (XHR2)
  69800. blob = xhr.response;
  69801. var transaction = _this.db.transaction(["textures"], "readwrite");
  69802. // the transaction could abort because of a QuotaExceededError error
  69803. transaction.onabort = function (event) {
  69804. try {
  69805. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69806. var srcElement = (event.srcElement || event.target);
  69807. var error = srcElement.error;
  69808. if (error && error.name === "QuotaExceededError") {
  69809. _this.hasReachedQuota = true;
  69810. }
  69811. }
  69812. catch (ex) { }
  69813. generateBlobUrl();
  69814. };
  69815. transaction.oncomplete = function (event) {
  69816. generateBlobUrl();
  69817. };
  69818. var newTexture = { textureUrl: url, data: blob };
  69819. try {
  69820. // Put the blob into the dabase
  69821. var addRequest = transaction.objectStore("textures").put(newTexture);
  69822. addRequest.onsuccess = function (event) {
  69823. };
  69824. addRequest.onerror = function (event) {
  69825. generateBlobUrl();
  69826. };
  69827. }
  69828. catch (ex) {
  69829. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69830. if (ex.code === 25) {
  69831. Database.IsUASupportingBlobStorage = false;
  69832. }
  69833. image.src = url;
  69834. }
  69835. }
  69836. else {
  69837. image.src = url;
  69838. }
  69839. }, false);
  69840. xhr.addEventListener("error", function (event) {
  69841. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69842. image.src = url;
  69843. }, false);
  69844. xhr.send();
  69845. }
  69846. else {
  69847. image.src = url;
  69848. }
  69849. }
  69850. else {
  69851. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69852. image.src = url;
  69853. }
  69854. };
  69855. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69856. var _this = this;
  69857. var updateVersion = function () {
  69858. // the version is not yet in the DB or we need to update it
  69859. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69860. };
  69861. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69862. };
  69863. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69864. var _this = this;
  69865. if (this.isSupported && this.db) {
  69866. var version;
  69867. try {
  69868. var transaction = this.db.transaction(["versions"]);
  69869. transaction.oncomplete = function (event) {
  69870. if (version) {
  69871. // If the version in the JSON file is different from the version in DB
  69872. if (_this.manifestVersionFound !== version.data) {
  69873. _this.mustUpdateRessources = true;
  69874. updateInDBCallback();
  69875. }
  69876. else {
  69877. callback(version.data);
  69878. }
  69879. }
  69880. // version was not found in DB
  69881. else {
  69882. _this.mustUpdateRessources = true;
  69883. updateInDBCallback();
  69884. }
  69885. };
  69886. transaction.onabort = function (event) {
  69887. callback(-1);
  69888. };
  69889. var getRequest = transaction.objectStore("versions").get(url);
  69890. getRequest.onsuccess = function (event) {
  69891. version = (event.target).result;
  69892. };
  69893. getRequest.onerror = function (event) {
  69894. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69895. callback(-1);
  69896. };
  69897. }
  69898. catch (ex) {
  69899. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69900. callback(-1);
  69901. }
  69902. }
  69903. else {
  69904. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69905. callback(-1);
  69906. }
  69907. };
  69908. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69909. var _this = this;
  69910. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69911. try {
  69912. // Open a transaction to the database
  69913. var transaction = this.db.transaction(["versions"], "readwrite");
  69914. // the transaction could abort because of a QuotaExceededError error
  69915. transaction.onabort = function (event) {
  69916. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69917. var error = event.srcElement['error'];
  69918. if (error && error.name === "QuotaExceededError") {
  69919. _this.hasReachedQuota = true;
  69920. }
  69921. }
  69922. catch (ex) { }
  69923. callback(-1);
  69924. };
  69925. transaction.oncomplete = function (event) {
  69926. callback(_this.manifestVersionFound);
  69927. };
  69928. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69929. // Put the scene into the database
  69930. var addRequest = transaction.objectStore("versions").put(newVersion);
  69931. addRequest.onsuccess = function (event) {
  69932. };
  69933. addRequest.onerror = function (event) {
  69934. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69935. };
  69936. }
  69937. catch (ex) {
  69938. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69939. callback(-1);
  69940. }
  69941. }
  69942. else {
  69943. callback(-1);
  69944. }
  69945. };
  69946. /**
  69947. * Loads a file from database
  69948. * @param url defines the URL to load from
  69949. * @param sceneLoaded defines a callback to call on success
  69950. * @param progressCallBack defines a callback to call when progress changed
  69951. * @param errorCallback defines a callback to call on error
  69952. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69953. */
  69954. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69955. var _this = this;
  69956. var completeUrl = Database._ReturnFullUrlLocation(url);
  69957. var saveAndLoadFile = function () {
  69958. // the scene is not yet in the DB, let's try to save it
  69959. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69960. };
  69961. this._checkVersionFromDB(completeUrl, function (version) {
  69962. if (version !== -1) {
  69963. if (!_this.mustUpdateRessources) {
  69964. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69965. }
  69966. else {
  69967. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69968. }
  69969. }
  69970. else {
  69971. if (errorCallback) {
  69972. errorCallback();
  69973. }
  69974. }
  69975. });
  69976. };
  69977. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69978. if (this.isSupported && this.db) {
  69979. var targetStore;
  69980. if (url.indexOf(".babylon") !== -1) {
  69981. targetStore = "scenes";
  69982. }
  69983. else {
  69984. targetStore = "textures";
  69985. }
  69986. var file;
  69987. var transaction = this.db.transaction([targetStore]);
  69988. transaction.oncomplete = function (event) {
  69989. if (file) {
  69990. callback(file.data);
  69991. }
  69992. // file was not found in DB
  69993. else {
  69994. notInDBCallback();
  69995. }
  69996. };
  69997. transaction.onabort = function (event) {
  69998. notInDBCallback();
  69999. };
  70000. var getRequest = transaction.objectStore(targetStore).get(url);
  70001. getRequest.onsuccess = function (event) {
  70002. file = (event.target).result;
  70003. };
  70004. getRequest.onerror = function (event) {
  70005. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  70006. notInDBCallback();
  70007. };
  70008. }
  70009. else {
  70010. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70011. callback();
  70012. }
  70013. };
  70014. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  70015. var _this = this;
  70016. if (this.isSupported) {
  70017. var targetStore;
  70018. if (url.indexOf(".babylon") !== -1) {
  70019. targetStore = "scenes";
  70020. }
  70021. else {
  70022. targetStore = "textures";
  70023. }
  70024. // Create XHR
  70025. var xhr = new XMLHttpRequest();
  70026. var fileData;
  70027. xhr.open("GET", url, true);
  70028. if (useArrayBuffer) {
  70029. xhr.responseType = "arraybuffer";
  70030. }
  70031. if (progressCallback) {
  70032. xhr.onprogress = progressCallback;
  70033. }
  70034. xhr.addEventListener("load", function () {
  70035. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  70036. // Blob as response (XHR2)
  70037. //fileData = xhr.responseText;
  70038. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  70039. if (!_this.hasReachedQuota && _this.db) {
  70040. // Open a transaction to the database
  70041. var transaction = _this.db.transaction([targetStore], "readwrite");
  70042. // the transaction could abort because of a QuotaExceededError error
  70043. transaction.onabort = function (event) {
  70044. try {
  70045. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  70046. var error = event.srcElement['error'];
  70047. if (error && error.name === "QuotaExceededError") {
  70048. _this.hasReachedQuota = true;
  70049. }
  70050. }
  70051. catch (ex) { }
  70052. callback(fileData);
  70053. };
  70054. transaction.oncomplete = function (event) {
  70055. callback(fileData);
  70056. };
  70057. var newFile;
  70058. if (targetStore === "scenes") {
  70059. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  70060. }
  70061. else {
  70062. newFile = { textureUrl: url, data: fileData };
  70063. }
  70064. try {
  70065. // Put the scene into the database
  70066. var addRequest = transaction.objectStore(targetStore).put(newFile);
  70067. addRequest.onsuccess = function (event) {
  70068. };
  70069. addRequest.onerror = function (event) {
  70070. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  70071. };
  70072. }
  70073. catch (ex) {
  70074. callback(fileData);
  70075. }
  70076. }
  70077. else {
  70078. callback(fileData);
  70079. }
  70080. }
  70081. else {
  70082. callback();
  70083. }
  70084. }, false);
  70085. xhr.addEventListener("error", function (event) {
  70086. BABYLON.Tools.Error("error on XHR request.");
  70087. callback();
  70088. }, false);
  70089. xhr.send();
  70090. }
  70091. else {
  70092. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70093. callback();
  70094. }
  70095. };
  70096. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  70097. Database.IsUASupportingBlobStorage = true;
  70098. /** Gets a boolean indicating if Database storate is enabled */
  70099. Database.IDBStorageEnabled = true;
  70100. Database._ParseURL = function (url) {
  70101. var a = document.createElement('a');
  70102. a.href = url;
  70103. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  70104. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  70105. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  70106. return absLocation;
  70107. };
  70108. Database._ReturnFullUrlLocation = function (url) {
  70109. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  70110. return (Database._ParseURL(window.location.href) + url);
  70111. }
  70112. else {
  70113. return url;
  70114. }
  70115. };
  70116. return Database;
  70117. }());
  70118. BABYLON.Database = Database;
  70119. })(BABYLON || (BABYLON = {}));
  70120. //# sourceMappingURL=babylon.database.js.map
  70121. var BABYLON;
  70122. (function (BABYLON) {
  70123. var FresnelParameters = /** @class */ (function () {
  70124. function FresnelParameters() {
  70125. this._isEnabled = true;
  70126. this.leftColor = BABYLON.Color3.White();
  70127. this.rightColor = BABYLON.Color3.Black();
  70128. this.bias = 0;
  70129. this.power = 1;
  70130. }
  70131. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  70132. get: function () {
  70133. return this._isEnabled;
  70134. },
  70135. set: function (value) {
  70136. if (this._isEnabled === value) {
  70137. return;
  70138. }
  70139. this._isEnabled = value;
  70140. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  70141. },
  70142. enumerable: true,
  70143. configurable: true
  70144. });
  70145. FresnelParameters.prototype.clone = function () {
  70146. var newFresnelParameters = new FresnelParameters();
  70147. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  70148. return newFresnelParameters;
  70149. };
  70150. FresnelParameters.prototype.serialize = function () {
  70151. var serializationObject = {};
  70152. serializationObject.isEnabled = this.isEnabled;
  70153. serializationObject.leftColor = this.leftColor.asArray();
  70154. serializationObject.rightColor = this.rightColor.asArray();
  70155. serializationObject.bias = this.bias;
  70156. serializationObject.power = this.power;
  70157. return serializationObject;
  70158. };
  70159. FresnelParameters.Parse = function (parsedFresnelParameters) {
  70160. var fresnelParameters = new FresnelParameters();
  70161. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  70162. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  70163. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  70164. fresnelParameters.bias = parsedFresnelParameters.bias;
  70165. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  70166. return fresnelParameters;
  70167. };
  70168. return FresnelParameters;
  70169. }());
  70170. BABYLON.FresnelParameters = FresnelParameters;
  70171. })(BABYLON || (BABYLON = {}));
  70172. //# sourceMappingURL=babylon.fresnelParameters.js.map
  70173. var BABYLON;
  70174. (function (BABYLON) {
  70175. var MultiMaterial = /** @class */ (function (_super) {
  70176. __extends(MultiMaterial, _super);
  70177. function MultiMaterial(name, scene) {
  70178. var _this = _super.call(this, name, scene, true) || this;
  70179. scene.multiMaterials.push(_this);
  70180. _this.subMaterials = new Array();
  70181. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  70182. return _this;
  70183. }
  70184. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  70185. get: function () {
  70186. return this._subMaterials;
  70187. },
  70188. set: function (value) {
  70189. this._subMaterials = value;
  70190. this._hookArray(value);
  70191. },
  70192. enumerable: true,
  70193. configurable: true
  70194. });
  70195. MultiMaterial.prototype._hookArray = function (array) {
  70196. var _this = this;
  70197. var oldPush = array.push;
  70198. array.push = function () {
  70199. var items = [];
  70200. for (var _i = 0; _i < arguments.length; _i++) {
  70201. items[_i] = arguments[_i];
  70202. }
  70203. var result = oldPush.apply(array, items);
  70204. _this._markAllSubMeshesAsTexturesDirty();
  70205. return result;
  70206. };
  70207. var oldSplice = array.splice;
  70208. array.splice = function (index, deleteCount) {
  70209. var deleted = oldSplice.apply(array, [index, deleteCount]);
  70210. _this._markAllSubMeshesAsTexturesDirty();
  70211. return deleted;
  70212. };
  70213. };
  70214. // Properties
  70215. MultiMaterial.prototype.getSubMaterial = function (index) {
  70216. if (index < 0 || index >= this.subMaterials.length) {
  70217. return this.getScene().defaultMaterial;
  70218. }
  70219. return this.subMaterials[index];
  70220. };
  70221. MultiMaterial.prototype.getActiveTextures = function () {
  70222. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  70223. if (subMaterial) {
  70224. return subMaterial.getActiveTextures();
  70225. }
  70226. else {
  70227. return [];
  70228. }
  70229. }));
  70230. var _a;
  70231. };
  70232. // Methods
  70233. MultiMaterial.prototype.getClassName = function () {
  70234. return "MultiMaterial";
  70235. };
  70236. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  70237. for (var index = 0; index < this.subMaterials.length; index++) {
  70238. var subMaterial = this.subMaterials[index];
  70239. if (subMaterial) {
  70240. if (subMaterial.storeEffectOnSubMeshes) {
  70241. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  70242. return false;
  70243. }
  70244. continue;
  70245. }
  70246. if (!subMaterial.isReady(mesh)) {
  70247. return false;
  70248. }
  70249. }
  70250. }
  70251. return true;
  70252. };
  70253. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  70254. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  70255. for (var index = 0; index < this.subMaterials.length; index++) {
  70256. var subMaterial = null;
  70257. var current = this.subMaterials[index];
  70258. if (cloneChildren && current) {
  70259. subMaterial = current.clone(name + "-" + current.name);
  70260. }
  70261. else {
  70262. subMaterial = this.subMaterials[index];
  70263. }
  70264. newMultiMaterial.subMaterials.push(subMaterial);
  70265. }
  70266. return newMultiMaterial;
  70267. };
  70268. MultiMaterial.prototype.serialize = function () {
  70269. var serializationObject = {};
  70270. serializationObject.name = this.name;
  70271. serializationObject.id = this.id;
  70272. if (BABYLON.Tags) {
  70273. serializationObject.tags = BABYLON.Tags.GetTags(this);
  70274. }
  70275. serializationObject.materials = [];
  70276. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  70277. var subMat = this.subMaterials[matIndex];
  70278. if (subMat) {
  70279. serializationObject.materials.push(subMat.id);
  70280. }
  70281. else {
  70282. serializationObject.materials.push(null);
  70283. }
  70284. }
  70285. return serializationObject;
  70286. };
  70287. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  70288. var scene = this.getScene();
  70289. if (!scene) {
  70290. return;
  70291. }
  70292. var index = scene.multiMaterials.indexOf(this);
  70293. if (index >= 0) {
  70294. scene.multiMaterials.splice(index, 1);
  70295. }
  70296. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  70297. };
  70298. return MultiMaterial;
  70299. }(BABYLON.Material));
  70300. BABYLON.MultiMaterial = MultiMaterial;
  70301. })(BABYLON || (BABYLON = {}));
  70302. //# sourceMappingURL=babylon.multiMaterial.js.map
  70303. var BABYLON;
  70304. (function (BABYLON) {
  70305. var FreeCameraTouchInput = /** @class */ (function () {
  70306. function FreeCameraTouchInput() {
  70307. this._offsetX = null;
  70308. this._offsetY = null;
  70309. this._pointerPressed = new Array();
  70310. this.touchAngularSensibility = 200000.0;
  70311. this.touchMoveSensibility = 250.0;
  70312. }
  70313. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  70314. var _this = this;
  70315. var previousPosition = null;
  70316. if (this._pointerInput === undefined) {
  70317. this._onLostFocus = function (evt) {
  70318. _this._offsetX = null;
  70319. _this._offsetY = null;
  70320. };
  70321. this._pointerInput = function (p, s) {
  70322. var evt = p.event;
  70323. if (evt.pointerType === "mouse") {
  70324. return;
  70325. }
  70326. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70327. if (!noPreventDefault) {
  70328. evt.preventDefault();
  70329. }
  70330. _this._pointerPressed.push(evt.pointerId);
  70331. if (_this._pointerPressed.length !== 1) {
  70332. return;
  70333. }
  70334. previousPosition = {
  70335. x: evt.clientX,
  70336. y: evt.clientY
  70337. };
  70338. }
  70339. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  70340. if (!noPreventDefault) {
  70341. evt.preventDefault();
  70342. }
  70343. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70344. if (index === -1) {
  70345. return;
  70346. }
  70347. _this._pointerPressed.splice(index, 1);
  70348. if (index != 0) {
  70349. return;
  70350. }
  70351. previousPosition = null;
  70352. _this._offsetX = null;
  70353. _this._offsetY = null;
  70354. }
  70355. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  70356. if (!noPreventDefault) {
  70357. evt.preventDefault();
  70358. }
  70359. if (!previousPosition) {
  70360. return;
  70361. }
  70362. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70363. if (index != 0) {
  70364. return;
  70365. }
  70366. _this._offsetX = evt.clientX - previousPosition.x;
  70367. _this._offsetY = -(evt.clientY - previousPosition.y);
  70368. }
  70369. };
  70370. }
  70371. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  70372. if (this._onLostFocus) {
  70373. element.addEventListener("blur", this._onLostFocus);
  70374. }
  70375. };
  70376. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70377. if (this._pointerInput && element) {
  70378. if (this._observer) {
  70379. this.camera.getScene().onPointerObservable.remove(this._observer);
  70380. this._observer = null;
  70381. }
  70382. if (this._onLostFocus) {
  70383. element.removeEventListener("blur", this._onLostFocus);
  70384. this._onLostFocus = null;
  70385. }
  70386. this._pointerPressed = [];
  70387. this._offsetX = null;
  70388. this._offsetY = null;
  70389. }
  70390. };
  70391. FreeCameraTouchInput.prototype.checkInputs = function () {
  70392. if (this._offsetX && this._offsetY) {
  70393. var camera = this.camera;
  70394. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70395. if (this._pointerPressed.length > 1) {
  70396. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70397. }
  70398. else {
  70399. var speed = camera._computeLocalCameraSpeed();
  70400. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70401. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70402. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70403. }
  70404. }
  70405. };
  70406. FreeCameraTouchInput.prototype.getClassName = function () {
  70407. return "FreeCameraTouchInput";
  70408. };
  70409. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70410. return "touch";
  70411. };
  70412. __decorate([
  70413. BABYLON.serialize()
  70414. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70415. __decorate([
  70416. BABYLON.serialize()
  70417. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70418. return FreeCameraTouchInput;
  70419. }());
  70420. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70421. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70422. })(BABYLON || (BABYLON = {}));
  70423. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70424. var BABYLON;
  70425. (function (BABYLON) {
  70426. // We're mainly based on the logic defined into the FreeCamera code
  70427. var TouchCamera = /** @class */ (function (_super) {
  70428. __extends(TouchCamera, _super);
  70429. //-- end properties for backward compatibility for inputs
  70430. function TouchCamera(name, position, scene) {
  70431. var _this = _super.call(this, name, position, scene) || this;
  70432. _this.inputs.addTouch();
  70433. _this._setupInputs();
  70434. return _this;
  70435. }
  70436. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70437. //-- Begin properties for backward compatibility for inputs
  70438. get: function () {
  70439. var touch = this.inputs.attached["touch"];
  70440. if (touch)
  70441. return touch.touchAngularSensibility;
  70442. return 0;
  70443. },
  70444. set: function (value) {
  70445. var touch = this.inputs.attached["touch"];
  70446. if (touch)
  70447. touch.touchAngularSensibility = value;
  70448. },
  70449. enumerable: true,
  70450. configurable: true
  70451. });
  70452. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70453. get: function () {
  70454. var touch = this.inputs.attached["touch"];
  70455. if (touch)
  70456. return touch.touchMoveSensibility;
  70457. return 0;
  70458. },
  70459. set: function (value) {
  70460. var touch = this.inputs.attached["touch"];
  70461. if (touch)
  70462. touch.touchMoveSensibility = value;
  70463. },
  70464. enumerable: true,
  70465. configurable: true
  70466. });
  70467. TouchCamera.prototype.getClassName = function () {
  70468. return "TouchCamera";
  70469. };
  70470. TouchCamera.prototype._setupInputs = function () {
  70471. var mouse = this.inputs.attached["mouse"];
  70472. if (mouse) {
  70473. mouse.touchEnabled = false;
  70474. }
  70475. };
  70476. return TouchCamera;
  70477. }(BABYLON.FreeCamera));
  70478. BABYLON.TouchCamera = TouchCamera;
  70479. })(BABYLON || (BABYLON = {}));
  70480. //# sourceMappingURL=babylon.touchCamera.js.map
  70481. var BABYLON;
  70482. (function (BABYLON) {
  70483. var ProceduralTexture = /** @class */ (function (_super) {
  70484. __extends(ProceduralTexture, _super);
  70485. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70486. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70487. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70488. if (isCube === void 0) { isCube = false; }
  70489. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70490. _this.isCube = isCube;
  70491. _this.isEnabled = true;
  70492. _this._currentRefreshId = -1;
  70493. _this._refreshRate = 1;
  70494. _this._vertexBuffers = {};
  70495. _this._uniforms = new Array();
  70496. _this._samplers = new Array();
  70497. _this._textures = {};
  70498. _this._floats = {};
  70499. _this._floatsArrays = {};
  70500. _this._colors3 = {};
  70501. _this._colors4 = {};
  70502. _this._vectors2 = {};
  70503. _this._vectors3 = {};
  70504. _this._matrices = {};
  70505. _this._fallbackTextureUsed = false;
  70506. scene.proceduralTextures.push(_this);
  70507. _this._engine = scene.getEngine();
  70508. _this.name = name;
  70509. _this.isRenderTarget = true;
  70510. _this._size = size;
  70511. _this._generateMipMaps = generateMipMaps;
  70512. _this.setFragment(fragment);
  70513. _this._fallbackTexture = fallbackTexture;
  70514. if (isCube) {
  70515. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70516. _this.setFloat("face", 0);
  70517. }
  70518. else {
  70519. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70520. }
  70521. // VBO
  70522. var vertices = [];
  70523. vertices.push(1, 1);
  70524. vertices.push(-1, 1);
  70525. vertices.push(-1, -1);
  70526. vertices.push(1, -1);
  70527. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70528. _this._createIndexBuffer();
  70529. return _this;
  70530. }
  70531. ProceduralTexture.prototype._createIndexBuffer = function () {
  70532. var engine = this._engine;
  70533. // Indices
  70534. var indices = [];
  70535. indices.push(0);
  70536. indices.push(1);
  70537. indices.push(2);
  70538. indices.push(0);
  70539. indices.push(2);
  70540. indices.push(3);
  70541. this._indexBuffer = engine.createIndexBuffer(indices);
  70542. };
  70543. ProceduralTexture.prototype._rebuild = function () {
  70544. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70545. if (vb) {
  70546. vb._rebuild();
  70547. }
  70548. this._createIndexBuffer();
  70549. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70550. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70551. }
  70552. };
  70553. ProceduralTexture.prototype.reset = function () {
  70554. if (this._effect === undefined) {
  70555. return;
  70556. }
  70557. var engine = this._engine;
  70558. engine._releaseEffect(this._effect);
  70559. };
  70560. ProceduralTexture.prototype.isReady = function () {
  70561. var _this = this;
  70562. var engine = this._engine;
  70563. var shaders;
  70564. if (!this._fragment) {
  70565. return false;
  70566. }
  70567. if (this._fallbackTextureUsed) {
  70568. return true;
  70569. }
  70570. if (this._fragment.fragmentElement !== undefined) {
  70571. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70572. }
  70573. else {
  70574. shaders = { vertex: "procedural", fragment: this._fragment };
  70575. }
  70576. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70577. _this.releaseInternalTexture();
  70578. if (_this._fallbackTexture) {
  70579. _this._texture = _this._fallbackTexture._texture;
  70580. if (_this._texture) {
  70581. _this._texture.incrementReferences();
  70582. }
  70583. }
  70584. _this._fallbackTextureUsed = true;
  70585. });
  70586. return this._effect.isReady();
  70587. };
  70588. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70589. this._currentRefreshId = -1;
  70590. };
  70591. ProceduralTexture.prototype.setFragment = function (fragment) {
  70592. this._fragment = fragment;
  70593. };
  70594. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70595. get: function () {
  70596. return this._refreshRate;
  70597. },
  70598. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70599. set: function (value) {
  70600. this._refreshRate = value;
  70601. this.resetRefreshCounter();
  70602. },
  70603. enumerable: true,
  70604. configurable: true
  70605. });
  70606. ProceduralTexture.prototype._shouldRender = function () {
  70607. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70608. return false;
  70609. }
  70610. if (this._fallbackTextureUsed) {
  70611. return false;
  70612. }
  70613. if (this._currentRefreshId === -1) { // At least render once
  70614. this._currentRefreshId = 1;
  70615. return true;
  70616. }
  70617. if (this.refreshRate === this._currentRefreshId) {
  70618. this._currentRefreshId = 1;
  70619. return true;
  70620. }
  70621. this._currentRefreshId++;
  70622. return false;
  70623. };
  70624. ProceduralTexture.prototype.getRenderSize = function () {
  70625. return this._size;
  70626. };
  70627. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70628. if (this._fallbackTextureUsed) {
  70629. return;
  70630. }
  70631. this.releaseInternalTexture();
  70632. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70633. };
  70634. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70635. if (this._uniforms.indexOf(uniformName) === -1) {
  70636. this._uniforms.push(uniformName);
  70637. }
  70638. };
  70639. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70640. if (this._samplers.indexOf(name) === -1) {
  70641. this._samplers.push(name);
  70642. }
  70643. this._textures[name] = texture;
  70644. return this;
  70645. };
  70646. ProceduralTexture.prototype.setFloat = function (name, value) {
  70647. this._checkUniform(name);
  70648. this._floats[name] = value;
  70649. return this;
  70650. };
  70651. ProceduralTexture.prototype.setFloats = function (name, value) {
  70652. this._checkUniform(name);
  70653. this._floatsArrays[name] = value;
  70654. return this;
  70655. };
  70656. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70657. this._checkUniform(name);
  70658. this._colors3[name] = value;
  70659. return this;
  70660. };
  70661. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70662. this._checkUniform(name);
  70663. this._colors4[name] = value;
  70664. return this;
  70665. };
  70666. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70667. this._checkUniform(name);
  70668. this._vectors2[name] = value;
  70669. return this;
  70670. };
  70671. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70672. this._checkUniform(name);
  70673. this._vectors3[name] = value;
  70674. return this;
  70675. };
  70676. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70677. this._checkUniform(name);
  70678. this._matrices[name] = value;
  70679. return this;
  70680. };
  70681. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70682. var scene = this.getScene();
  70683. if (!scene) {
  70684. return;
  70685. }
  70686. var engine = this._engine;
  70687. // Render
  70688. engine.enableEffect(this._effect);
  70689. engine.setState(false);
  70690. // Texture
  70691. for (var name in this._textures) {
  70692. this._effect.setTexture(name, this._textures[name]);
  70693. }
  70694. // Float
  70695. for (name in this._floats) {
  70696. this._effect.setFloat(name, this._floats[name]);
  70697. }
  70698. // Floats
  70699. for (name in this._floatsArrays) {
  70700. this._effect.setArray(name, this._floatsArrays[name]);
  70701. }
  70702. // Color3
  70703. for (name in this._colors3) {
  70704. this._effect.setColor3(name, this._colors3[name]);
  70705. }
  70706. // Color4
  70707. for (name in this._colors4) {
  70708. var color = this._colors4[name];
  70709. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70710. }
  70711. // Vector2
  70712. for (name in this._vectors2) {
  70713. this._effect.setVector2(name, this._vectors2[name]);
  70714. }
  70715. // Vector3
  70716. for (name in this._vectors3) {
  70717. this._effect.setVector3(name, this._vectors3[name]);
  70718. }
  70719. // Matrix
  70720. for (name in this._matrices) {
  70721. this._effect.setMatrix(name, this._matrices[name]);
  70722. }
  70723. if (!this._texture) {
  70724. return;
  70725. }
  70726. if (this.isCube) {
  70727. for (var face = 0; face < 6; face++) {
  70728. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70729. // VBOs
  70730. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70731. this._effect.setFloat("face", face);
  70732. // Clear
  70733. engine.clear(scene.clearColor, true, true, true);
  70734. // Draw order
  70735. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70736. // Mipmaps
  70737. if (face === 5) {
  70738. engine.generateMipMapsForCubemap(this._texture);
  70739. }
  70740. }
  70741. }
  70742. else {
  70743. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70744. // VBOs
  70745. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70746. // Clear
  70747. engine.clear(scene.clearColor, true, true, true);
  70748. // Draw order
  70749. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70750. }
  70751. // Unbind
  70752. engine.unBindFramebuffer(this._texture, this.isCube);
  70753. if (this.onGenerated) {
  70754. this.onGenerated();
  70755. }
  70756. };
  70757. ProceduralTexture.prototype.clone = function () {
  70758. var textureSize = this.getSize();
  70759. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70760. // Base texture
  70761. newTexture.hasAlpha = this.hasAlpha;
  70762. newTexture.level = this.level;
  70763. // RenderTarget Texture
  70764. newTexture.coordinatesMode = this.coordinatesMode;
  70765. return newTexture;
  70766. };
  70767. ProceduralTexture.prototype.dispose = function () {
  70768. var scene = this.getScene();
  70769. if (!scene) {
  70770. return;
  70771. }
  70772. var index = scene.proceduralTextures.indexOf(this);
  70773. if (index >= 0) {
  70774. scene.proceduralTextures.splice(index, 1);
  70775. }
  70776. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70777. if (vertexBuffer) {
  70778. vertexBuffer.dispose();
  70779. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70780. }
  70781. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70782. this._indexBuffer = null;
  70783. }
  70784. _super.prototype.dispose.call(this);
  70785. };
  70786. return ProceduralTexture;
  70787. }(BABYLON.Texture));
  70788. BABYLON.ProceduralTexture = ProceduralTexture;
  70789. })(BABYLON || (BABYLON = {}));
  70790. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70791. var BABYLON;
  70792. (function (BABYLON) {
  70793. var CustomProceduralTexture = /** @class */ (function (_super) {
  70794. __extends(CustomProceduralTexture, _super);
  70795. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70796. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70797. _this._animate = true;
  70798. _this._time = 0;
  70799. _this._texturePath = texturePath;
  70800. //Try to load json
  70801. _this.loadJson(texturePath);
  70802. _this.refreshRate = 1;
  70803. return _this;
  70804. }
  70805. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70806. var _this = this;
  70807. var noConfigFile = function () {
  70808. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70809. try {
  70810. _this.setFragment(_this._texturePath);
  70811. }
  70812. catch (ex) {
  70813. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70814. }
  70815. };
  70816. var configFileUrl = jsonUrl + "/config.json";
  70817. var xhr = new XMLHttpRequest();
  70818. xhr.open("GET", configFileUrl, true);
  70819. xhr.addEventListener("load", function () {
  70820. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70821. try {
  70822. _this._config = JSON.parse(xhr.response);
  70823. _this.updateShaderUniforms();
  70824. _this.updateTextures();
  70825. _this.setFragment(_this._texturePath + "/custom");
  70826. _this._animate = _this._config.animate;
  70827. _this.refreshRate = _this._config.refreshrate;
  70828. }
  70829. catch (ex) {
  70830. noConfigFile();
  70831. }
  70832. }
  70833. else {
  70834. noConfigFile();
  70835. }
  70836. }, false);
  70837. xhr.addEventListener("error", function () {
  70838. noConfigFile();
  70839. }, false);
  70840. try {
  70841. xhr.send();
  70842. }
  70843. catch (ex) {
  70844. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70845. }
  70846. };
  70847. CustomProceduralTexture.prototype.isReady = function () {
  70848. if (!_super.prototype.isReady.call(this)) {
  70849. return false;
  70850. }
  70851. for (var name in this._textures) {
  70852. var texture = this._textures[name];
  70853. if (!texture.isReady()) {
  70854. return false;
  70855. }
  70856. }
  70857. return true;
  70858. };
  70859. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70860. var scene = this.getScene();
  70861. if (this._animate && scene) {
  70862. this._time += scene.getAnimationRatio() * 0.03;
  70863. this.updateShaderUniforms();
  70864. }
  70865. _super.prototype.render.call(this, useCameraPostProcess);
  70866. };
  70867. CustomProceduralTexture.prototype.updateTextures = function () {
  70868. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70869. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70870. }
  70871. };
  70872. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70873. if (this._config) {
  70874. for (var j = 0; j < this._config.uniforms.length; j++) {
  70875. var uniform = this._config.uniforms[j];
  70876. switch (uniform.type) {
  70877. case "float":
  70878. this.setFloat(uniform.name, uniform.value);
  70879. break;
  70880. case "color3":
  70881. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70882. break;
  70883. case "color4":
  70884. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70885. break;
  70886. case "vector2":
  70887. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70888. break;
  70889. case "vector3":
  70890. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70891. break;
  70892. }
  70893. }
  70894. }
  70895. this.setFloat("time", this._time);
  70896. };
  70897. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70898. get: function () {
  70899. return this._animate;
  70900. },
  70901. set: function (value) {
  70902. this._animate = value;
  70903. },
  70904. enumerable: true,
  70905. configurable: true
  70906. });
  70907. return CustomProceduralTexture;
  70908. }(BABYLON.ProceduralTexture));
  70909. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70910. })(BABYLON || (BABYLON = {}));
  70911. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70912. var BABYLON;
  70913. (function (BABYLON) {
  70914. var FreeCameraGamepadInput = /** @class */ (function () {
  70915. function FreeCameraGamepadInput() {
  70916. this.gamepadAngularSensibility = 200;
  70917. this.gamepadMoveSensibility = 40;
  70918. // private members
  70919. this._cameraTransform = BABYLON.Matrix.Identity();
  70920. this._deltaTransform = BABYLON.Vector3.Zero();
  70921. this._vector3 = BABYLON.Vector3.Zero();
  70922. this._vector2 = BABYLON.Vector2.Zero();
  70923. }
  70924. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70925. var _this = this;
  70926. var manager = this.camera.getScene().gamepadManager;
  70927. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70928. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70929. // prioritize XBOX gamepads.
  70930. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70931. _this.gamepad = gamepad;
  70932. }
  70933. }
  70934. });
  70935. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70936. if (_this.gamepad === gamepad) {
  70937. _this.gamepad = null;
  70938. }
  70939. });
  70940. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70941. };
  70942. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70943. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70944. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70945. this.gamepad = null;
  70946. };
  70947. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70948. if (this.gamepad && this.gamepad.leftStick) {
  70949. var camera = this.camera;
  70950. var LSValues = this.gamepad.leftStick;
  70951. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70952. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70953. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70954. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70955. var RSValues = this.gamepad.rightStick;
  70956. if (RSValues) {
  70957. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70958. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70959. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70960. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70961. }
  70962. else {
  70963. RSValues = { x: 0, y: 0 };
  70964. }
  70965. if (!camera.rotationQuaternion) {
  70966. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70967. }
  70968. else {
  70969. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70970. }
  70971. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70972. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70973. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70974. camera.cameraDirection.addInPlace(this._deltaTransform);
  70975. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70976. camera.cameraRotation.addInPlace(this._vector2);
  70977. }
  70978. };
  70979. FreeCameraGamepadInput.prototype.getClassName = function () {
  70980. return "FreeCameraGamepadInput";
  70981. };
  70982. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70983. return "gamepad";
  70984. };
  70985. __decorate([
  70986. BABYLON.serialize()
  70987. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70988. __decorate([
  70989. BABYLON.serialize()
  70990. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70991. return FreeCameraGamepadInput;
  70992. }());
  70993. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70994. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70995. })(BABYLON || (BABYLON = {}));
  70996. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70997. var BABYLON;
  70998. (function (BABYLON) {
  70999. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  71000. function ArcRotateCameraGamepadInput() {
  71001. this.gamepadRotationSensibility = 80;
  71002. this.gamepadMoveSensibility = 40;
  71003. }
  71004. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  71005. var _this = this;
  71006. var manager = this.camera.getScene().gamepadManager;
  71007. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  71008. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  71009. // prioritize XBOX gamepads.
  71010. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  71011. _this.gamepad = gamepad;
  71012. }
  71013. }
  71014. });
  71015. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  71016. if (_this.gamepad === gamepad) {
  71017. _this.gamepad = null;
  71018. }
  71019. });
  71020. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  71021. };
  71022. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  71023. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  71024. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  71025. this.gamepad = null;
  71026. };
  71027. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  71028. if (this.gamepad) {
  71029. var camera = this.camera;
  71030. var RSValues = this.gamepad.rightStick;
  71031. if (RSValues) {
  71032. if (RSValues.x != 0) {
  71033. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  71034. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  71035. camera.inertialAlphaOffset += normalizedRX;
  71036. }
  71037. }
  71038. if (RSValues.y != 0) {
  71039. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  71040. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  71041. camera.inertialBetaOffset += normalizedRY;
  71042. }
  71043. }
  71044. }
  71045. var LSValues = this.gamepad.leftStick;
  71046. if (LSValues && LSValues.y != 0) {
  71047. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  71048. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  71049. this.camera.inertialRadiusOffset -= normalizedLY;
  71050. }
  71051. }
  71052. }
  71053. };
  71054. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  71055. return "ArcRotateCameraGamepadInput";
  71056. };
  71057. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  71058. return "gamepad";
  71059. };
  71060. __decorate([
  71061. BABYLON.serialize()
  71062. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  71063. __decorate([
  71064. BABYLON.serialize()
  71065. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  71066. return ArcRotateCameraGamepadInput;
  71067. }());
  71068. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  71069. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  71070. })(BABYLON || (BABYLON = {}));
  71071. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  71072. var BABYLON;
  71073. (function (BABYLON) {
  71074. var GamepadManager = /** @class */ (function () {
  71075. function GamepadManager(_scene) {
  71076. var _this = this;
  71077. this._scene = _scene;
  71078. this._babylonGamepads = [];
  71079. this._oneGamepadConnected = false;
  71080. this._isMonitoring = false;
  71081. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  71082. if (!BABYLON.Tools.IsWindowObjectExist()) {
  71083. this._gamepadEventSupported = false;
  71084. }
  71085. else {
  71086. this._gamepadEventSupported = 'GamepadEvent' in window;
  71087. this._gamepadSupport = (navigator.getGamepads ||
  71088. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  71089. }
  71090. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  71091. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  71092. for (var i in _this._babylonGamepads) {
  71093. var gamepad = _this._babylonGamepads[i];
  71094. if (gamepad && gamepad._isConnected) {
  71095. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  71096. }
  71097. }
  71098. });
  71099. this._onGamepadConnectedEvent = function (evt) {
  71100. var gamepad = evt.gamepad;
  71101. if (gamepad.index in _this._babylonGamepads) {
  71102. if (_this._babylonGamepads[gamepad.index].isConnected) {
  71103. return;
  71104. }
  71105. }
  71106. var newGamepad;
  71107. if (_this._babylonGamepads[gamepad.index]) {
  71108. newGamepad = _this._babylonGamepads[gamepad.index];
  71109. newGamepad.browserGamepad = gamepad;
  71110. newGamepad._isConnected = true;
  71111. }
  71112. else {
  71113. newGamepad = _this._addNewGamepad(gamepad);
  71114. }
  71115. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71116. _this._startMonitoringGamepads();
  71117. };
  71118. this._onGamepadDisconnectedEvent = function (evt) {
  71119. var gamepad = evt.gamepad;
  71120. // Remove the gamepad from the list of gamepads to monitor.
  71121. for (var i in _this._babylonGamepads) {
  71122. if (_this._babylonGamepads[i].index === gamepad.index) {
  71123. var disconnectedGamepad = _this._babylonGamepads[i];
  71124. disconnectedGamepad._isConnected = false;
  71125. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  71126. break;
  71127. }
  71128. }
  71129. };
  71130. if (this._gamepadSupport) {
  71131. //first add already-connected gamepads
  71132. this._updateGamepadObjects();
  71133. if (this._babylonGamepads.length) {
  71134. this._startMonitoringGamepads();
  71135. }
  71136. // Checking if the gamepad connected event is supported (like in Firefox)
  71137. if (this._gamepadEventSupported) {
  71138. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  71139. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  71140. }
  71141. else {
  71142. this._startMonitoringGamepads();
  71143. }
  71144. }
  71145. }
  71146. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  71147. get: function () {
  71148. return this._babylonGamepads;
  71149. },
  71150. enumerable: true,
  71151. configurable: true
  71152. });
  71153. GamepadManager.prototype.getGamepadByType = function (type) {
  71154. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  71155. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  71156. var gamepad = _a[_i];
  71157. if (gamepad && gamepad.type === type) {
  71158. return gamepad;
  71159. }
  71160. }
  71161. return null;
  71162. };
  71163. GamepadManager.prototype.dispose = function () {
  71164. if (this._gamepadEventSupported) {
  71165. if (this._onGamepadConnectedEvent) {
  71166. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  71167. }
  71168. if (this._onGamepadDisconnectedEvent) {
  71169. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  71170. }
  71171. this._onGamepadConnectedEvent = null;
  71172. this._onGamepadDisconnectedEvent = null;
  71173. }
  71174. this._babylonGamepads.forEach(function (gamepad) {
  71175. gamepad.dispose();
  71176. });
  71177. this.onGamepadConnectedObservable.clear();
  71178. this.onGamepadDisconnectedObservable.clear();
  71179. this._oneGamepadConnected = false;
  71180. this._stopMonitoringGamepads();
  71181. this._babylonGamepads = [];
  71182. };
  71183. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  71184. if (!this._oneGamepadConnected) {
  71185. this._oneGamepadConnected = true;
  71186. }
  71187. var newGamepad;
  71188. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  71189. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  71190. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  71191. }
  71192. // if pose is supported, use the (WebVR) pose enabled controller
  71193. else if (gamepad.pose) {
  71194. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  71195. }
  71196. else {
  71197. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  71198. }
  71199. this._babylonGamepads[newGamepad.index] = newGamepad;
  71200. return newGamepad;
  71201. };
  71202. GamepadManager.prototype._startMonitoringGamepads = function () {
  71203. if (!this._isMonitoring) {
  71204. this._isMonitoring = true;
  71205. //back-comp
  71206. if (!this._scene) {
  71207. this._checkGamepadsStatus();
  71208. }
  71209. }
  71210. };
  71211. GamepadManager.prototype._stopMonitoringGamepads = function () {
  71212. this._isMonitoring = false;
  71213. };
  71214. GamepadManager.prototype._checkGamepadsStatus = function () {
  71215. var _this = this;
  71216. // Hack to be compatible Chrome
  71217. this._updateGamepadObjects();
  71218. for (var i in this._babylonGamepads) {
  71219. var gamepad = this._babylonGamepads[i];
  71220. if (!gamepad || !gamepad.isConnected) {
  71221. continue;
  71222. }
  71223. gamepad.update();
  71224. }
  71225. if (this._isMonitoring && !this._scene) {
  71226. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  71227. }
  71228. };
  71229. // This function is called only on Chrome, which does not properly support
  71230. // connection/disconnection events and forces you to recopy again the gamepad object
  71231. GamepadManager.prototype._updateGamepadObjects = function () {
  71232. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  71233. for (var i = 0; i < gamepads.length; i++) {
  71234. var gamepad = gamepads[i];
  71235. if (gamepad) {
  71236. if (!this._babylonGamepads[gamepad.index]) {
  71237. var newGamepad = this._addNewGamepad(gamepad);
  71238. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71239. }
  71240. else {
  71241. // Forced to copy again this object for Chrome for unknown reason
  71242. this._babylonGamepads[i].browserGamepad = gamepad;
  71243. if (!this._babylonGamepads[i].isConnected) {
  71244. this._babylonGamepads[i]._isConnected = true;
  71245. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  71246. }
  71247. }
  71248. }
  71249. }
  71250. };
  71251. return GamepadManager;
  71252. }());
  71253. BABYLON.GamepadManager = GamepadManager;
  71254. })(BABYLON || (BABYLON = {}));
  71255. //# sourceMappingURL=babylon.gamepadManager.js.map
  71256. var BABYLON;
  71257. (function (BABYLON) {
  71258. var StickValues = /** @class */ (function () {
  71259. function StickValues(x, y) {
  71260. this.x = x;
  71261. this.y = y;
  71262. }
  71263. return StickValues;
  71264. }());
  71265. BABYLON.StickValues = StickValues;
  71266. var Gamepad = /** @class */ (function () {
  71267. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  71268. if (leftStickX === void 0) { leftStickX = 0; }
  71269. if (leftStickY === void 0) { leftStickY = 1; }
  71270. if (rightStickX === void 0) { rightStickX = 2; }
  71271. if (rightStickY === void 0) { rightStickY = 3; }
  71272. this.id = id;
  71273. this.index = index;
  71274. this.browserGamepad = browserGamepad;
  71275. this._isConnected = true;
  71276. this._invertLeftStickY = false;
  71277. this.type = Gamepad.GAMEPAD;
  71278. this._leftStickAxisX = leftStickX;
  71279. this._leftStickAxisY = leftStickY;
  71280. this._rightStickAxisX = rightStickX;
  71281. this._rightStickAxisY = rightStickY;
  71282. if (this.browserGamepad.axes.length >= 2) {
  71283. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71284. }
  71285. if (this.browserGamepad.axes.length >= 4) {
  71286. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71287. }
  71288. }
  71289. Object.defineProperty(Gamepad.prototype, "isConnected", {
  71290. get: function () {
  71291. return this._isConnected;
  71292. },
  71293. enumerable: true,
  71294. configurable: true
  71295. });
  71296. Gamepad.prototype.onleftstickchanged = function (callback) {
  71297. this._onleftstickchanged = callback;
  71298. };
  71299. Gamepad.prototype.onrightstickchanged = function (callback) {
  71300. this._onrightstickchanged = callback;
  71301. };
  71302. Object.defineProperty(Gamepad.prototype, "leftStick", {
  71303. get: function () {
  71304. return this._leftStick;
  71305. },
  71306. set: function (newValues) {
  71307. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  71308. this._onleftstickchanged(newValues);
  71309. }
  71310. this._leftStick = newValues;
  71311. },
  71312. enumerable: true,
  71313. configurable: true
  71314. });
  71315. Object.defineProperty(Gamepad.prototype, "rightStick", {
  71316. get: function () {
  71317. return this._rightStick;
  71318. },
  71319. set: function (newValues) {
  71320. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  71321. this._onrightstickchanged(newValues);
  71322. }
  71323. this._rightStick = newValues;
  71324. },
  71325. enumerable: true,
  71326. configurable: true
  71327. });
  71328. Gamepad.prototype.update = function () {
  71329. if (this._leftStick) {
  71330. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71331. if (this._invertLeftStickY) {
  71332. this.leftStick.y *= -1;
  71333. }
  71334. }
  71335. if (this._rightStick) {
  71336. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71337. }
  71338. };
  71339. Gamepad.prototype.dispose = function () {
  71340. };
  71341. Gamepad.GAMEPAD = 0;
  71342. Gamepad.GENERIC = 1;
  71343. Gamepad.XBOX = 2;
  71344. Gamepad.POSE_ENABLED = 3;
  71345. return Gamepad;
  71346. }());
  71347. BABYLON.Gamepad = Gamepad;
  71348. var GenericPad = /** @class */ (function (_super) {
  71349. __extends(GenericPad, _super);
  71350. function GenericPad(id, index, browserGamepad) {
  71351. var _this = _super.call(this, id, index, browserGamepad) || this;
  71352. _this.onButtonDownObservable = new BABYLON.Observable();
  71353. _this.onButtonUpObservable = new BABYLON.Observable();
  71354. _this.type = Gamepad.GENERIC;
  71355. _this._buttons = new Array(browserGamepad.buttons.length);
  71356. return _this;
  71357. }
  71358. GenericPad.prototype.onbuttondown = function (callback) {
  71359. this._onbuttondown = callback;
  71360. };
  71361. GenericPad.prototype.onbuttonup = function (callback) {
  71362. this._onbuttonup = callback;
  71363. };
  71364. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  71365. if (newValue !== currentValue) {
  71366. if (newValue === 1) {
  71367. if (this._onbuttondown) {
  71368. this._onbuttondown(buttonIndex);
  71369. }
  71370. this.onButtonDownObservable.notifyObservers(buttonIndex);
  71371. }
  71372. if (newValue === 0) {
  71373. if (this._onbuttonup) {
  71374. this._onbuttonup(buttonIndex);
  71375. }
  71376. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71377. }
  71378. }
  71379. return newValue;
  71380. };
  71381. GenericPad.prototype.update = function () {
  71382. _super.prototype.update.call(this);
  71383. for (var index = 0; index < this._buttons.length; index++) {
  71384. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71385. }
  71386. };
  71387. GenericPad.prototype.dispose = function () {
  71388. _super.prototype.dispose.call(this);
  71389. this.onButtonDownObservable.clear();
  71390. this.onButtonUpObservable.clear();
  71391. };
  71392. return GenericPad;
  71393. }(Gamepad));
  71394. BABYLON.GenericPad = GenericPad;
  71395. })(BABYLON || (BABYLON = {}));
  71396. //# sourceMappingURL=babylon.gamepad.js.map
  71397. var BABYLON;
  71398. (function (BABYLON) {
  71399. /**
  71400. * Defines supported buttons for XBox360 compatible gamepads
  71401. */
  71402. var Xbox360Button;
  71403. (function (Xbox360Button) {
  71404. /** A */
  71405. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71406. /** B */
  71407. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71408. /** X */
  71409. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71410. /** Y */
  71411. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71412. /** Start */
  71413. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71414. /** Back */
  71415. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71416. /** Left button */
  71417. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71418. /** Right button */
  71419. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71420. /** Left stick */
  71421. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71422. /** Right stick */
  71423. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71424. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71425. /** Defines values for XBox360 DPad */
  71426. var Xbox360Dpad;
  71427. (function (Xbox360Dpad) {
  71428. /** Up */
  71429. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71430. /** Down */
  71431. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71432. /** Left */
  71433. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71434. /** Right */
  71435. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71436. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71437. /**
  71438. * Defines a XBox360 gamepad
  71439. */
  71440. var Xbox360Pad = /** @class */ (function (_super) {
  71441. __extends(Xbox360Pad, _super);
  71442. /**
  71443. * Creates a new XBox360 gamepad object
  71444. * @param id defines the id of this gamepad
  71445. * @param index defines its index
  71446. * @param gamepad defines the internal HTML gamepad object
  71447. * @param xboxOne defines if it is a XBox One gamepad
  71448. */
  71449. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71450. if (xboxOne === void 0) { xboxOne = false; }
  71451. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71452. _this._leftTrigger = 0;
  71453. _this._rightTrigger = 0;
  71454. /** Observable raised when a button is pressed */
  71455. _this.onButtonDownObservable = new BABYLON.Observable();
  71456. /** Observable raised when a button is released */
  71457. _this.onButtonUpObservable = new BABYLON.Observable();
  71458. /** Observable raised when a pad is pressed */
  71459. _this.onPadDownObservable = new BABYLON.Observable();
  71460. /** Observable raised when a pad is released */
  71461. _this.onPadUpObservable = new BABYLON.Observable();
  71462. _this._buttonA = 0;
  71463. _this._buttonB = 0;
  71464. _this._buttonX = 0;
  71465. _this._buttonY = 0;
  71466. _this._buttonBack = 0;
  71467. _this._buttonStart = 0;
  71468. _this._buttonLB = 0;
  71469. _this._buttonRB = 0;
  71470. _this._buttonLeftStick = 0;
  71471. _this._buttonRightStick = 0;
  71472. _this._dPadUp = 0;
  71473. _this._dPadDown = 0;
  71474. _this._dPadLeft = 0;
  71475. _this._dPadRight = 0;
  71476. _this._isXboxOnePad = false;
  71477. _this.type = BABYLON.Gamepad.XBOX;
  71478. _this._isXboxOnePad = xboxOne;
  71479. return _this;
  71480. }
  71481. /**
  71482. * Defines the callback to call when left trigger is pressed
  71483. * @param callback defines the callback to use
  71484. */
  71485. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71486. this._onlefttriggerchanged = callback;
  71487. };
  71488. /**
  71489. * Defines the callback to call when right trigger is pressed
  71490. * @param callback defines the callback to use
  71491. */
  71492. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71493. this._onrighttriggerchanged = callback;
  71494. };
  71495. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71496. /**
  71497. * Gets or sets left trigger value
  71498. */
  71499. get: function () {
  71500. return this._leftTrigger;
  71501. },
  71502. set: function (newValue) {
  71503. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71504. this._onlefttriggerchanged(newValue);
  71505. }
  71506. this._leftTrigger = newValue;
  71507. },
  71508. enumerable: true,
  71509. configurable: true
  71510. });
  71511. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71512. /**
  71513. * Gets or sets right trigger value
  71514. */
  71515. get: function () {
  71516. return this._rightTrigger;
  71517. },
  71518. set: function (newValue) {
  71519. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71520. this._onrighttriggerchanged(newValue);
  71521. }
  71522. this._rightTrigger = newValue;
  71523. },
  71524. enumerable: true,
  71525. configurable: true
  71526. });
  71527. /**
  71528. * Defines the callback to call when a button is pressed
  71529. * @param callback defines the callback to use
  71530. */
  71531. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71532. this._onbuttondown = callback;
  71533. };
  71534. /**
  71535. * Defines the callback to call when a button is released
  71536. * @param callback defines the callback to use
  71537. */
  71538. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71539. this._onbuttonup = callback;
  71540. };
  71541. /**
  71542. * Defines the callback to call when a pad is pressed
  71543. * @param callback defines the callback to use
  71544. */
  71545. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71546. this._ondpaddown = callback;
  71547. };
  71548. /**
  71549. * Defines the callback to call when a pad is released
  71550. * @param callback defines the callback to use
  71551. */
  71552. Xbox360Pad.prototype.ondpadup = function (callback) {
  71553. this._ondpadup = callback;
  71554. };
  71555. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71556. if (newValue !== currentValue) {
  71557. if (newValue === 1) {
  71558. if (this._onbuttondown) {
  71559. this._onbuttondown(buttonType);
  71560. }
  71561. this.onButtonDownObservable.notifyObservers(buttonType);
  71562. }
  71563. if (newValue === 0) {
  71564. if (this._onbuttonup) {
  71565. this._onbuttonup(buttonType);
  71566. }
  71567. this.onButtonUpObservable.notifyObservers(buttonType);
  71568. }
  71569. }
  71570. return newValue;
  71571. };
  71572. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71573. if (newValue !== currentValue) {
  71574. if (newValue === 1) {
  71575. if (this._ondpaddown) {
  71576. this._ondpaddown(buttonType);
  71577. }
  71578. this.onPadDownObservable.notifyObservers(buttonType);
  71579. }
  71580. if (newValue === 0) {
  71581. if (this._ondpadup) {
  71582. this._ondpadup(buttonType);
  71583. }
  71584. this.onPadUpObservable.notifyObservers(buttonType);
  71585. }
  71586. }
  71587. return newValue;
  71588. };
  71589. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71590. /** Gets or sets value of A button */
  71591. get: function () {
  71592. return this._buttonA;
  71593. },
  71594. set: function (value) {
  71595. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71596. },
  71597. enumerable: true,
  71598. configurable: true
  71599. });
  71600. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71601. /** Gets or sets value of B button */
  71602. get: function () {
  71603. return this._buttonB;
  71604. },
  71605. set: function (value) {
  71606. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71607. },
  71608. enumerable: true,
  71609. configurable: true
  71610. });
  71611. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71612. /** Gets or sets value of X button */
  71613. get: function () {
  71614. return this._buttonX;
  71615. },
  71616. set: function (value) {
  71617. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71618. },
  71619. enumerable: true,
  71620. configurable: true
  71621. });
  71622. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71623. /** Gets or sets value of Y button */
  71624. get: function () {
  71625. return this._buttonY;
  71626. },
  71627. set: function (value) {
  71628. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71629. },
  71630. enumerable: true,
  71631. configurable: true
  71632. });
  71633. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71634. /** Gets or sets value of Start button */
  71635. get: function () {
  71636. return this._buttonStart;
  71637. },
  71638. set: function (value) {
  71639. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71640. },
  71641. enumerable: true,
  71642. configurable: true
  71643. });
  71644. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71645. /** Gets or sets value of Back button */
  71646. get: function () {
  71647. return this._buttonBack;
  71648. },
  71649. set: function (value) {
  71650. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71651. },
  71652. enumerable: true,
  71653. configurable: true
  71654. });
  71655. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71656. /** Gets or sets value of Left button */
  71657. get: function () {
  71658. return this._buttonLB;
  71659. },
  71660. set: function (value) {
  71661. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71662. },
  71663. enumerable: true,
  71664. configurable: true
  71665. });
  71666. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71667. /** Gets or sets value of Right button */
  71668. get: function () {
  71669. return this._buttonRB;
  71670. },
  71671. set: function (value) {
  71672. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71673. },
  71674. enumerable: true,
  71675. configurable: true
  71676. });
  71677. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71678. /** Gets or sets value of left stick */
  71679. get: function () {
  71680. return this._buttonLeftStick;
  71681. },
  71682. set: function (value) {
  71683. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71684. },
  71685. enumerable: true,
  71686. configurable: true
  71687. });
  71688. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71689. /** Gets or sets value of right stick */
  71690. get: function () {
  71691. return this._buttonRightStick;
  71692. },
  71693. set: function (value) {
  71694. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71695. },
  71696. enumerable: true,
  71697. configurable: true
  71698. });
  71699. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71700. /** Gets or sets value of DPad up */
  71701. get: function () {
  71702. return this._dPadUp;
  71703. },
  71704. set: function (value) {
  71705. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71706. },
  71707. enumerable: true,
  71708. configurable: true
  71709. });
  71710. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71711. /** Gets or sets value of DPad down */
  71712. get: function () {
  71713. return this._dPadDown;
  71714. },
  71715. set: function (value) {
  71716. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71717. },
  71718. enumerable: true,
  71719. configurable: true
  71720. });
  71721. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71722. /** Gets or sets value of DPad left */
  71723. get: function () {
  71724. return this._dPadLeft;
  71725. },
  71726. set: function (value) {
  71727. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71728. },
  71729. enumerable: true,
  71730. configurable: true
  71731. });
  71732. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71733. /** Gets or sets value of DPad right */
  71734. get: function () {
  71735. return this._dPadRight;
  71736. },
  71737. set: function (value) {
  71738. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71739. },
  71740. enumerable: true,
  71741. configurable: true
  71742. });
  71743. /**
  71744. * Force the gamepad to synchronize with device values
  71745. */
  71746. Xbox360Pad.prototype.update = function () {
  71747. _super.prototype.update.call(this);
  71748. if (this._isXboxOnePad) {
  71749. this.buttonA = this.browserGamepad.buttons[0].value;
  71750. this.buttonB = this.browserGamepad.buttons[1].value;
  71751. this.buttonX = this.browserGamepad.buttons[2].value;
  71752. this.buttonY = this.browserGamepad.buttons[3].value;
  71753. this.buttonLB = this.browserGamepad.buttons[4].value;
  71754. this.buttonRB = this.browserGamepad.buttons[5].value;
  71755. this.leftTrigger = this.browserGamepad.axes[2];
  71756. this.rightTrigger = this.browserGamepad.axes[5];
  71757. this.buttonBack = this.browserGamepad.buttons[9].value;
  71758. this.buttonStart = this.browserGamepad.buttons[8].value;
  71759. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71760. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71761. this.dPadUp = this.browserGamepad.buttons[11].value;
  71762. this.dPadDown = this.browserGamepad.buttons[12].value;
  71763. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71764. this.dPadRight = this.browserGamepad.buttons[14].value;
  71765. }
  71766. else {
  71767. this.buttonA = this.browserGamepad.buttons[0].value;
  71768. this.buttonB = this.browserGamepad.buttons[1].value;
  71769. this.buttonX = this.browserGamepad.buttons[2].value;
  71770. this.buttonY = this.browserGamepad.buttons[3].value;
  71771. this.buttonLB = this.browserGamepad.buttons[4].value;
  71772. this.buttonRB = this.browserGamepad.buttons[5].value;
  71773. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71774. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71775. this.buttonBack = this.browserGamepad.buttons[8].value;
  71776. this.buttonStart = this.browserGamepad.buttons[9].value;
  71777. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71778. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71779. this.dPadUp = this.browserGamepad.buttons[12].value;
  71780. this.dPadDown = this.browserGamepad.buttons[13].value;
  71781. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71782. this.dPadRight = this.browserGamepad.buttons[15].value;
  71783. }
  71784. };
  71785. Xbox360Pad.prototype.dispose = function () {
  71786. _super.prototype.dispose.call(this);
  71787. this.onButtonDownObservable.clear();
  71788. this.onButtonUpObservable.clear();
  71789. this.onPadDownObservable.clear();
  71790. this.onPadUpObservable.clear();
  71791. };
  71792. return Xbox360Pad;
  71793. }(BABYLON.Gamepad));
  71794. BABYLON.Xbox360Pad = Xbox360Pad;
  71795. })(BABYLON || (BABYLON = {}));
  71796. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71797. var BABYLON;
  71798. (function (BABYLON) {
  71799. /**
  71800. * Defines the types of pose enabled controllers that are supported
  71801. */
  71802. var PoseEnabledControllerType;
  71803. (function (PoseEnabledControllerType) {
  71804. /**
  71805. * HTC Vive
  71806. */
  71807. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71808. /**
  71809. * Oculus Rift
  71810. */
  71811. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71812. /**
  71813. * Windows mixed reality
  71814. */
  71815. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71816. /**
  71817. * Samsung gear VR
  71818. */
  71819. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71820. /**
  71821. * Google Daydream
  71822. */
  71823. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71824. /**
  71825. * Generic
  71826. */
  71827. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71828. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71829. /**
  71830. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71831. */
  71832. var PoseEnabledControllerHelper = /** @class */ (function () {
  71833. function PoseEnabledControllerHelper() {
  71834. }
  71835. /**
  71836. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71837. * @param vrGamepad the gamepad to initialized
  71838. * @returns a vr controller of the type the gamepad identified as
  71839. */
  71840. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71841. // Oculus Touch
  71842. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71843. return new BABYLON.OculusTouchController(vrGamepad);
  71844. }
  71845. // Windows Mixed Reality controllers
  71846. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71847. return new BABYLON.WindowsMotionController(vrGamepad);
  71848. }
  71849. // HTC Vive
  71850. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71851. return new BABYLON.ViveController(vrGamepad);
  71852. }
  71853. // Samsung/Oculus Gear VR or Oculus Go
  71854. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71855. return new BABYLON.GearVRController(vrGamepad);
  71856. }
  71857. // Google Daydream
  71858. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71859. return new BABYLON.DaydreamController(vrGamepad);
  71860. }
  71861. // Generic
  71862. else {
  71863. return new BABYLON.GenericController(vrGamepad);
  71864. }
  71865. };
  71866. return PoseEnabledControllerHelper;
  71867. }());
  71868. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71869. /**
  71870. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71871. */
  71872. var PoseEnabledController = /** @class */ (function (_super) {
  71873. __extends(PoseEnabledController, _super);
  71874. /**
  71875. * Creates a new PoseEnabledController from a gamepad
  71876. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71877. */
  71878. function PoseEnabledController(browserGamepad) {
  71879. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71880. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71881. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71882. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71883. /**
  71884. * The device position in babylon space
  71885. */
  71886. _this.devicePosition = BABYLON.Vector3.Zero();
  71887. /**
  71888. * The device rotation in babylon space
  71889. */
  71890. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71891. /**
  71892. * The scale factor of the device in babylon space
  71893. */
  71894. _this.deviceScaleFactor = 1;
  71895. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71896. /**
  71897. * Internal, matrix used to convert room space to babylon space
  71898. */
  71899. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71900. /**
  71901. * Node to be used when casting a ray from the controller
  71902. */
  71903. _this._pointingPoseNode = null;
  71904. _this._workingMatrix = BABYLON.Matrix.Identity();
  71905. /**
  71906. * @hidden
  71907. */
  71908. _this._meshAttachedObservable = new BABYLON.Observable();
  71909. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71910. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71911. _this.position = BABYLON.Vector3.Zero();
  71912. _this.rotationQuaternion = new BABYLON.Quaternion();
  71913. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71914. _this._calculatedRotation = new BABYLON.Quaternion();
  71915. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71916. return _this;
  71917. }
  71918. /**
  71919. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71920. */
  71921. PoseEnabledController.prototype.update = function () {
  71922. _super.prototype.update.call(this);
  71923. var pose = this.browserGamepad.pose;
  71924. this.updateFromDevice(pose);
  71925. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71926. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71927. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71928. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71929. if (this._mesh) {
  71930. this._mesh.position.copyFrom(this.devicePosition);
  71931. if (this._mesh.rotationQuaternion) {
  71932. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71933. }
  71934. }
  71935. };
  71936. /**
  71937. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71938. * @param poseData raw pose fromthe device
  71939. */
  71940. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71941. if (poseData) {
  71942. this.rawPose = poseData;
  71943. if (poseData.position) {
  71944. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71945. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71946. this._deviceRoomPosition.z *= -1;
  71947. }
  71948. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71949. this._calculatedPosition.addInPlace(this.position);
  71950. }
  71951. var pose = this.rawPose;
  71952. if (poseData.orientation && pose.orientation) {
  71953. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71954. if (this._mesh) {
  71955. if (this._mesh.getScene().useRightHandedSystem) {
  71956. this._deviceRoomRotationQuaternion.z *= -1;
  71957. this._deviceRoomRotationQuaternion.w *= -1;
  71958. }
  71959. else {
  71960. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71961. }
  71962. }
  71963. // if the camera is set, rotate to the camera's rotation
  71964. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71965. }
  71966. }
  71967. };
  71968. /**
  71969. * Attaches a mesh to the controller
  71970. * @param mesh the mesh to be attached
  71971. */
  71972. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71973. if (this._mesh) {
  71974. this._mesh.parent = null;
  71975. }
  71976. this._mesh = mesh;
  71977. if (this._poseControlledCamera) {
  71978. this._mesh.parent = this._poseControlledCamera;
  71979. }
  71980. if (!this._mesh.rotationQuaternion) {
  71981. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71982. }
  71983. this._meshAttachedObservable.notifyObservers(mesh);
  71984. };
  71985. /**
  71986. * Attaches the controllers mesh to a camera
  71987. * @param camera the camera the mesh should be attached to
  71988. */
  71989. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71990. this._poseControlledCamera = camera;
  71991. if (this._mesh) {
  71992. this._mesh.parent = this._poseControlledCamera;
  71993. }
  71994. };
  71995. /**
  71996. * Disposes of the controller
  71997. */
  71998. PoseEnabledController.prototype.dispose = function () {
  71999. if (this._mesh) {
  72000. this._mesh.dispose();
  72001. }
  72002. this._mesh = null;
  72003. _super.prototype.dispose.call(this);
  72004. };
  72005. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  72006. /**
  72007. * The mesh that is attached to the controller
  72008. */
  72009. get: function () {
  72010. return this._mesh;
  72011. },
  72012. enumerable: true,
  72013. configurable: true
  72014. });
  72015. /**
  72016. * Gets the ray of the controller in the direction the controller is pointing
  72017. * @param length the length the resulting ray should be
  72018. * @returns a ray in the direction the controller is pointing
  72019. */
  72020. PoseEnabledController.prototype.getForwardRay = function (length) {
  72021. if (length === void 0) { length = 100; }
  72022. if (!this.mesh) {
  72023. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  72024. }
  72025. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  72026. var origin = m.getTranslation();
  72027. var forward = new BABYLON.Vector3(0, 0, -1);
  72028. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72029. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72030. return new BABYLON.Ray(origin, direction, length);
  72031. };
  72032. /**
  72033. * Name of the child mesh that can be used to cast a ray from the controller
  72034. */
  72035. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  72036. return PoseEnabledController;
  72037. }(BABYLON.Gamepad));
  72038. BABYLON.PoseEnabledController = PoseEnabledController;
  72039. })(BABYLON || (BABYLON = {}));
  72040. //# sourceMappingURL=babylon.poseEnabledController.js.map
  72041. var BABYLON;
  72042. (function (BABYLON) {
  72043. /**
  72044. * Defines the WebVRController object that represents controllers tracked in 3D space
  72045. */
  72046. var WebVRController = /** @class */ (function (_super) {
  72047. __extends(WebVRController, _super);
  72048. /**
  72049. * Creates a new WebVRController from a gamepad
  72050. * @param vrGamepad the gamepad that the WebVRController should be created from
  72051. */
  72052. function WebVRController(vrGamepad) {
  72053. var _this = _super.call(this, vrGamepad) || this;
  72054. // Observables
  72055. /**
  72056. * Fired when the trigger state has changed
  72057. */
  72058. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  72059. /**
  72060. * Fired when the main button state has changed
  72061. */
  72062. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  72063. /**
  72064. * Fired when the secondary button state has changed
  72065. */
  72066. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  72067. /**
  72068. * Fired when the pad state has changed
  72069. */
  72070. _this.onPadStateChangedObservable = new BABYLON.Observable();
  72071. /**
  72072. * Fired when controllers stick values have changed
  72073. */
  72074. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  72075. /**
  72076. * X and Y axis corrisponding to the controllers joystick
  72077. */
  72078. _this.pad = { x: 0, y: 0 };
  72079. // avoid GC, store state in a tmp object
  72080. _this._changes = {
  72081. pressChanged: false,
  72082. touchChanged: false,
  72083. valueChanged: false,
  72084. changed: false
  72085. };
  72086. _this._buttons = new Array(vrGamepad.buttons.length);
  72087. _this.hand = vrGamepad.hand;
  72088. return _this;
  72089. }
  72090. /**
  72091. * Fired when a controller button's state has changed
  72092. * @param callback the callback containing the button that was modified
  72093. */
  72094. WebVRController.prototype.onButtonStateChange = function (callback) {
  72095. this._onButtonStateChange = callback;
  72096. };
  72097. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  72098. /**
  72099. * The default controller model for the controller
  72100. */
  72101. get: function () {
  72102. return this._defaultModel;
  72103. },
  72104. enumerable: true,
  72105. configurable: true
  72106. });
  72107. /**
  72108. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  72109. */
  72110. WebVRController.prototype.update = function () {
  72111. _super.prototype.update.call(this);
  72112. for (var index = 0; index < this._buttons.length; index++) {
  72113. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  72114. }
  72115. ;
  72116. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  72117. this.pad.x = this.leftStick.x;
  72118. this.pad.y = this.leftStick.y;
  72119. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  72120. }
  72121. };
  72122. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  72123. if (!newState) {
  72124. newState = {
  72125. pressed: false,
  72126. touched: false,
  72127. value: 0
  72128. };
  72129. }
  72130. if (!currentState) {
  72131. this._buttons[buttonIndex] = {
  72132. pressed: newState.pressed,
  72133. touched: newState.touched,
  72134. value: newState.value
  72135. };
  72136. return;
  72137. }
  72138. this._checkChanges(newState, currentState);
  72139. if (this._changes.changed) {
  72140. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  72141. this._handleButtonChange(buttonIndex, newState, this._changes);
  72142. }
  72143. this._buttons[buttonIndex].pressed = newState.pressed;
  72144. this._buttons[buttonIndex].touched = newState.touched;
  72145. // oculus triggers are never 0, thou not touched.
  72146. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  72147. };
  72148. WebVRController.prototype._checkChanges = function (newState, currentState) {
  72149. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  72150. this._changes.touchChanged = newState.touched !== currentState.touched;
  72151. this._changes.valueChanged = newState.value !== currentState.value;
  72152. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  72153. return this._changes;
  72154. };
  72155. /**
  72156. * Disposes of th webVRCOntroller
  72157. */
  72158. WebVRController.prototype.dispose = function () {
  72159. _super.prototype.dispose.call(this);
  72160. this.onTriggerStateChangedObservable.clear();
  72161. this.onMainButtonStateChangedObservable.clear();
  72162. this.onSecondaryButtonStateChangedObservable.clear();
  72163. this.onPadStateChangedObservable.clear();
  72164. this.onPadValuesChangedObservable.clear();
  72165. };
  72166. return WebVRController;
  72167. }(BABYLON.PoseEnabledController));
  72168. BABYLON.WebVRController = WebVRController;
  72169. })(BABYLON || (BABYLON = {}));
  72170. //# sourceMappingURL=babylon.webVRController.js.map
  72171. var BABYLON;
  72172. (function (BABYLON) {
  72173. /**
  72174. * Oculus Touch Controller
  72175. */
  72176. var OculusTouchController = /** @class */ (function (_super) {
  72177. __extends(OculusTouchController, _super);
  72178. /**
  72179. * Creates a new OculusTouchController from a gamepad
  72180. * @param vrGamepad the gamepad that the controller should be created from
  72181. */
  72182. function OculusTouchController(vrGamepad) {
  72183. var _this = _super.call(this, vrGamepad) || this;
  72184. /**
  72185. * Fired when the secondary trigger on this controller is modified
  72186. */
  72187. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  72188. /**
  72189. * Fired when the thumb rest on this controller is modified
  72190. */
  72191. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  72192. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  72193. return _this;
  72194. }
  72195. /**
  72196. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72197. * @param scene scene in which to add meshes
  72198. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72199. */
  72200. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72201. var _this = this;
  72202. var meshName;
  72203. // Hand
  72204. if (this.hand === 'left') {
  72205. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  72206. }
  72207. else { // Right is the default if no hand is specified
  72208. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  72209. }
  72210. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  72211. /*
  72212. Parent Mesh name: oculus_touch_left
  72213. - body
  72214. - trigger
  72215. - thumbstick
  72216. - grip
  72217. - button_y
  72218. - button_x
  72219. - button_enter
  72220. */
  72221. _this._defaultModel = newMeshes[1];
  72222. _this.attachToMesh(_this._defaultModel);
  72223. if (meshLoaded) {
  72224. meshLoaded(_this._defaultModel);
  72225. }
  72226. });
  72227. };
  72228. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  72229. /**
  72230. * Fired when the A button on this controller is modified
  72231. */
  72232. get: function () {
  72233. if (this.hand === 'right') {
  72234. return this.onMainButtonStateChangedObservable;
  72235. }
  72236. else {
  72237. throw new Error('No A button on left hand');
  72238. }
  72239. },
  72240. enumerable: true,
  72241. configurable: true
  72242. });
  72243. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  72244. /**
  72245. * Fired when the B button on this controller is modified
  72246. */
  72247. get: function () {
  72248. if (this.hand === 'right') {
  72249. return this.onSecondaryButtonStateChangedObservable;
  72250. }
  72251. else {
  72252. throw new Error('No B button on left hand');
  72253. }
  72254. },
  72255. enumerable: true,
  72256. configurable: true
  72257. });
  72258. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  72259. /**
  72260. * Fired when the X button on this controller is modified
  72261. */
  72262. get: function () {
  72263. if (this.hand === 'left') {
  72264. return this.onMainButtonStateChangedObservable;
  72265. }
  72266. else {
  72267. throw new Error('No X button on right hand');
  72268. }
  72269. },
  72270. enumerable: true,
  72271. configurable: true
  72272. });
  72273. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  72274. /**
  72275. * Fired when the Y button on this controller is modified
  72276. */
  72277. get: function () {
  72278. if (this.hand === 'left') {
  72279. return this.onSecondaryButtonStateChangedObservable;
  72280. }
  72281. else {
  72282. throw new Error('No Y button on right hand');
  72283. }
  72284. },
  72285. enumerable: true,
  72286. configurable: true
  72287. });
  72288. /**
  72289. * Called once for each button that changed state since the last frame
  72290. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  72291. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  72292. * 2) secondary trigger (same)
  72293. * 3) A (right) X (left), touch, pressed = value
  72294. * 4) B / Y
  72295. * 5) thumb rest
  72296. * @param buttonIdx Which button index changed
  72297. * @param state New state of the button
  72298. * @param changes Which properties on the state changed since last frame
  72299. */
  72300. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72301. var notifyObject = state; //{ state: state, changes: changes };
  72302. var triggerDirection = this.hand === 'right' ? -1 : 1;
  72303. switch (buttonIdx) {
  72304. case 0:
  72305. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72306. return;
  72307. case 1: // index trigger
  72308. if (this._defaultModel) {
  72309. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  72310. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  72311. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  72312. }
  72313. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72314. return;
  72315. case 2: // secondary trigger
  72316. if (this._defaultModel) {
  72317. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  72318. }
  72319. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  72320. return;
  72321. case 3:
  72322. if (this._defaultModel) {
  72323. if (notifyObject.pressed) {
  72324. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  72325. }
  72326. else {
  72327. (this._defaultModel.getChildren()[1]).position.y = 0;
  72328. }
  72329. }
  72330. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72331. return;
  72332. case 4:
  72333. if (this._defaultModel) {
  72334. if (notifyObject.pressed) {
  72335. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72336. }
  72337. else {
  72338. (this._defaultModel.getChildren()[2]).position.y = 0;
  72339. }
  72340. }
  72341. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72342. return;
  72343. case 5:
  72344. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  72345. return;
  72346. }
  72347. };
  72348. /**
  72349. * Base Url for the controller model.
  72350. */
  72351. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  72352. /**
  72353. * File name for the left controller model.
  72354. */
  72355. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  72356. /**
  72357. * File name for the right controller model.
  72358. */
  72359. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  72360. return OculusTouchController;
  72361. }(BABYLON.WebVRController));
  72362. BABYLON.OculusTouchController = OculusTouchController;
  72363. })(BABYLON || (BABYLON = {}));
  72364. //# sourceMappingURL=babylon.oculusTouchController.js.map
  72365. var BABYLON;
  72366. (function (BABYLON) {
  72367. /**
  72368. * Vive Controller
  72369. */
  72370. var ViveController = /** @class */ (function (_super) {
  72371. __extends(ViveController, _super);
  72372. /**
  72373. * Creates a new ViveController from a gamepad
  72374. * @param vrGamepad the gamepad that the controller should be created from
  72375. */
  72376. function ViveController(vrGamepad) {
  72377. var _this = _super.call(this, vrGamepad) || this;
  72378. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72379. _this._invertLeftStickY = true;
  72380. return _this;
  72381. }
  72382. /**
  72383. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72384. * @param scene scene in which to add meshes
  72385. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72386. */
  72387. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72388. var _this = this;
  72389. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72390. /*
  72391. Parent Mesh name: ViveWand
  72392. - body
  72393. - r_gripper
  72394. - l_gripper
  72395. - menu_button
  72396. - system_button
  72397. - trackpad
  72398. - trigger
  72399. - LED
  72400. */
  72401. _this._defaultModel = newMeshes[1];
  72402. _this.attachToMesh(_this._defaultModel);
  72403. if (meshLoaded) {
  72404. meshLoaded(_this._defaultModel);
  72405. }
  72406. });
  72407. };
  72408. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72409. /**
  72410. * Fired when the left button on this controller is modified
  72411. */
  72412. get: function () {
  72413. return this.onMainButtonStateChangedObservable;
  72414. },
  72415. enumerable: true,
  72416. configurable: true
  72417. });
  72418. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72419. /**
  72420. * Fired when the right button on this controller is modified
  72421. */
  72422. get: function () {
  72423. return this.onMainButtonStateChangedObservable;
  72424. },
  72425. enumerable: true,
  72426. configurable: true
  72427. });
  72428. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72429. /**
  72430. * Fired when the menu button on this controller is modified
  72431. */
  72432. get: function () {
  72433. return this.onSecondaryButtonStateChangedObservable;
  72434. },
  72435. enumerable: true,
  72436. configurable: true
  72437. });
  72438. /**
  72439. * Called once for each button that changed state since the last frame
  72440. * Vive mapping:
  72441. * 0: touchpad
  72442. * 1: trigger
  72443. * 2: left AND right buttons
  72444. * 3: menu button
  72445. * @param buttonIdx Which button index changed
  72446. * @param state New state of the button
  72447. * @param changes Which properties on the state changed since last frame
  72448. */
  72449. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72450. var notifyObject = state; //{ state: state, changes: changes };
  72451. switch (buttonIdx) {
  72452. case 0:
  72453. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72454. return;
  72455. case 1: // index trigger
  72456. if (this._defaultModel) {
  72457. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72458. }
  72459. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72460. return;
  72461. case 2: // left AND right button
  72462. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72463. return;
  72464. case 3:
  72465. if (this._defaultModel) {
  72466. if (notifyObject.pressed) {
  72467. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72468. }
  72469. else {
  72470. (this._defaultModel.getChildren()[2]).position.y = 0;
  72471. }
  72472. }
  72473. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72474. return;
  72475. }
  72476. };
  72477. /**
  72478. * Base Url for the controller model.
  72479. */
  72480. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72481. /**
  72482. * File name for the controller model.
  72483. */
  72484. ViveController.MODEL_FILENAME = 'wand.babylon';
  72485. return ViveController;
  72486. }(BABYLON.WebVRController));
  72487. BABYLON.ViveController = ViveController;
  72488. })(BABYLON || (BABYLON = {}));
  72489. //# sourceMappingURL=babylon.viveController.js.map
  72490. var BABYLON;
  72491. (function (BABYLON) {
  72492. /**
  72493. * Generic Controller
  72494. */
  72495. var GenericController = /** @class */ (function (_super) {
  72496. __extends(GenericController, _super);
  72497. /**
  72498. * Creates a new GenericController from a gamepad
  72499. * @param vrGamepad the gamepad that the controller should be created from
  72500. */
  72501. function GenericController(vrGamepad) {
  72502. return _super.call(this, vrGamepad) || this;
  72503. }
  72504. /**
  72505. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72506. * @param scene scene in which to add meshes
  72507. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72508. */
  72509. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72510. var _this = this;
  72511. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72512. _this._defaultModel = newMeshes[1];
  72513. _this.attachToMesh(_this._defaultModel);
  72514. if (meshLoaded) {
  72515. meshLoaded(_this._defaultModel);
  72516. }
  72517. });
  72518. };
  72519. /**
  72520. * Called once for each button that changed state since the last frame
  72521. * @param buttonIdx Which button index changed
  72522. * @param state New state of the button
  72523. * @param changes Which properties on the state changed since last frame
  72524. */
  72525. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72526. console.log("Button id: " + buttonIdx + "state: ");
  72527. console.dir(state);
  72528. };
  72529. /**
  72530. * Base Url for the controller model.
  72531. */
  72532. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72533. /**
  72534. * File name for the controller model.
  72535. */
  72536. GenericController.MODEL_FILENAME = 'generic.babylon';
  72537. return GenericController;
  72538. }(BABYLON.WebVRController));
  72539. BABYLON.GenericController = GenericController;
  72540. })(BABYLON || (BABYLON = {}));
  72541. //# sourceMappingURL=babylon.genericController.js.map
  72542. var BABYLON;
  72543. (function (BABYLON) {
  72544. /**
  72545. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72546. */
  72547. var LoadedMeshInfo = /** @class */ (function () {
  72548. function LoadedMeshInfo() {
  72549. /**
  72550. * Map of the button meshes contained in the controller
  72551. */
  72552. this.buttonMeshes = {};
  72553. /**
  72554. * Map of the axis meshes contained in the controller
  72555. */
  72556. this.axisMeshes = {};
  72557. }
  72558. return LoadedMeshInfo;
  72559. }());
  72560. /**
  72561. * Defines the WindowsMotionController object that the state of the windows motion controller
  72562. */
  72563. var WindowsMotionController = /** @class */ (function (_super) {
  72564. __extends(WindowsMotionController, _super);
  72565. /**
  72566. * Creates a new WindowsMotionController from a gamepad
  72567. * @param vrGamepad the gamepad that the controller should be created from
  72568. */
  72569. function WindowsMotionController(vrGamepad) {
  72570. var _this = _super.call(this, vrGamepad) || this;
  72571. _this._mapping = {
  72572. // Semantic button names
  72573. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72574. // A mapping of the button name to glTF model node name
  72575. // that should be transformed by button value.
  72576. buttonMeshNames: {
  72577. 'trigger': 'SELECT',
  72578. 'menu': 'MENU',
  72579. 'grip': 'GRASP',
  72580. 'thumbstick': 'THUMBSTICK_PRESS',
  72581. 'trackpad': 'TOUCHPAD_PRESS'
  72582. },
  72583. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72584. buttonObservableNames: {
  72585. 'trigger': 'onTriggerStateChangedObservable',
  72586. 'menu': 'onSecondaryButtonStateChangedObservable',
  72587. 'grip': 'onMainButtonStateChangedObservable',
  72588. 'thumbstick': 'onPadStateChangedObservable',
  72589. 'trackpad': 'onTrackpadChangedObservable'
  72590. },
  72591. // A mapping of the axis name to glTF model node name
  72592. // that should be transformed by axis value.
  72593. // This array mirrors the browserGamepad.axes array, such that
  72594. // the mesh corresponding to axis 0 is in this array index 0.
  72595. axisMeshNames: [
  72596. 'THUMBSTICK_X',
  72597. 'THUMBSTICK_Y',
  72598. 'TOUCHPAD_TOUCH_X',
  72599. 'TOUCHPAD_TOUCH_Y'
  72600. ],
  72601. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72602. };
  72603. /**
  72604. * Fired when the trackpad on this controller is clicked
  72605. */
  72606. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72607. /**
  72608. * Fired when the trackpad on this controller is modified
  72609. */
  72610. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72611. /**
  72612. * The current x and y values of this controller's trackpad
  72613. */
  72614. _this.trackpad = { x: 0, y: 0 };
  72615. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72616. _this._loadedMeshInfo = null;
  72617. return _this;
  72618. }
  72619. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72620. /**
  72621. * Fired when the trigger on this controller is modified
  72622. */
  72623. get: function () {
  72624. return this.onTriggerStateChangedObservable;
  72625. },
  72626. enumerable: true,
  72627. configurable: true
  72628. });
  72629. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72630. /**
  72631. * Fired when the menu button on this controller is modified
  72632. */
  72633. get: function () {
  72634. return this.onSecondaryButtonStateChangedObservable;
  72635. },
  72636. enumerable: true,
  72637. configurable: true
  72638. });
  72639. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72640. /**
  72641. * Fired when the grip button on this controller is modified
  72642. */
  72643. get: function () {
  72644. return this.onMainButtonStateChangedObservable;
  72645. },
  72646. enumerable: true,
  72647. configurable: true
  72648. });
  72649. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72650. /**
  72651. * Fired when the thumbstick button on this controller is modified
  72652. */
  72653. get: function () {
  72654. return this.onPadStateChangedObservable;
  72655. },
  72656. enumerable: true,
  72657. configurable: true
  72658. });
  72659. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72660. /**
  72661. * Fired when the touchpad button on this controller is modified
  72662. */
  72663. get: function () {
  72664. return this.onTrackpadChangedObservable;
  72665. },
  72666. enumerable: true,
  72667. configurable: true
  72668. });
  72669. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72670. /**
  72671. * Fired when the touchpad values on this controller are modified
  72672. */
  72673. get: function () {
  72674. return this.onTrackpadValuesChangedObservable;
  72675. },
  72676. enumerable: true,
  72677. configurable: true
  72678. });
  72679. WindowsMotionController.prototype._updateTrackpad = function () {
  72680. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  72681. this.trackpad.x = this.browserGamepad["axes"][2];
  72682. this.trackpad.y = this.browserGamepad["axes"][3];
  72683. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72684. }
  72685. };
  72686. /**
  72687. * Called once per frame by the engine.
  72688. */
  72689. WindowsMotionController.prototype.update = function () {
  72690. _super.prototype.update.call(this);
  72691. if (this.browserGamepad.axes) {
  72692. this._updateTrackpad();
  72693. // Only need to animate axes if there is a loaded mesh
  72694. if (this._loadedMeshInfo) {
  72695. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72696. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72697. }
  72698. }
  72699. }
  72700. };
  72701. /**
  72702. * Called once for each button that changed state since the last frame
  72703. * @param buttonIdx Which button index changed
  72704. * @param state New state of the button
  72705. * @param changes Which properties on the state changed since last frame
  72706. */
  72707. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72708. var buttonName = this._mapping.buttons[buttonIdx];
  72709. if (!buttonName) {
  72710. return;
  72711. }
  72712. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  72713. this._updateTrackpad();
  72714. // Only emit events for buttons that we know how to map from index to name
  72715. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72716. if (observable) {
  72717. observable.notifyObservers(state);
  72718. }
  72719. this._lerpButtonTransform(buttonName, state.value);
  72720. };
  72721. /**
  72722. * Moves the buttons on the controller mesh based on their current state
  72723. * @param buttonName the name of the button to move
  72724. * @param buttonValue the value of the button which determines the buttons new position
  72725. */
  72726. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72727. // If there is no loaded mesh, there is nothing to transform.
  72728. if (!this._loadedMeshInfo) {
  72729. return;
  72730. }
  72731. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72732. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72733. return;
  72734. }
  72735. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72736. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72737. };
  72738. /**
  72739. * Moves the axis on the controller mesh based on its current state
  72740. * @param axis the index of the axis
  72741. * @param axisValue the value of the axis which determines the meshes new position
  72742. * @hidden
  72743. */
  72744. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72745. if (!this._loadedMeshInfo) {
  72746. return;
  72747. }
  72748. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72749. if (!meshInfo) {
  72750. return;
  72751. }
  72752. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72753. return;
  72754. }
  72755. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72756. var lerpValue = axisValue * 0.5 + 0.5;
  72757. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72758. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72759. };
  72760. /**
  72761. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72762. * @param scene scene in which to add meshes
  72763. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72764. */
  72765. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72766. var _this = this;
  72767. if (forceDefault === void 0) { forceDefault = false; }
  72768. var path;
  72769. var filename;
  72770. // Checking if GLB loader is present
  72771. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72772. // Determine the device specific folder based on the ID suffix
  72773. var device = 'default';
  72774. if (this.id && !forceDefault) {
  72775. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72776. device = ((match && match[0]) || device);
  72777. }
  72778. // Hand
  72779. if (this.hand === 'left') {
  72780. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72781. }
  72782. else { // Right is the default if no hand is specified
  72783. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72784. }
  72785. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72786. }
  72787. else {
  72788. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72789. path = BABYLON.GenericController.MODEL_BASE_URL;
  72790. filename = BABYLON.GenericController.MODEL_FILENAME;
  72791. }
  72792. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72793. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72794. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72795. if (!_this._loadedMeshInfo) {
  72796. return;
  72797. }
  72798. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72799. _this.attachToMesh(_this._defaultModel);
  72800. if (meshLoaded) {
  72801. meshLoaded(_this._defaultModel);
  72802. }
  72803. }, null, function (scene, message) {
  72804. BABYLON.Tools.Log(message);
  72805. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72806. if (!forceDefault) {
  72807. _this.initControllerMesh(scene, meshLoaded, true);
  72808. }
  72809. });
  72810. };
  72811. /**
  72812. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72813. * can be transformed by button presses and axes values, based on this._mapping.
  72814. *
  72815. * @param scene scene in which the meshes exist
  72816. * @param meshes list of meshes that make up the controller model to process
  72817. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72818. */
  72819. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72820. var loadedMeshInfo = null;
  72821. // Create a new mesh to contain the glTF hierarchy
  72822. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72823. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72824. var childMesh = null;
  72825. for (var i = 0; i < meshes.length; i++) {
  72826. var mesh = meshes[i];
  72827. if (!mesh.parent) {
  72828. // Exclude controller meshes from picking results
  72829. mesh.isPickable = false;
  72830. // Handle root node, attach to the new parentMesh
  72831. childMesh = mesh;
  72832. break;
  72833. }
  72834. }
  72835. if (childMesh) {
  72836. childMesh.setParent(parentMesh);
  72837. // Create our mesh info. Note that this method will always return non-null.
  72838. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72839. }
  72840. else {
  72841. BABYLON.Tools.Warn('Could not find root node in model file.');
  72842. }
  72843. return loadedMeshInfo;
  72844. };
  72845. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72846. var loadedMeshInfo = new LoadedMeshInfo();
  72847. var i;
  72848. loadedMeshInfo.rootNode = rootNode;
  72849. // Reset the caches
  72850. loadedMeshInfo.buttonMeshes = {};
  72851. loadedMeshInfo.axisMeshes = {};
  72852. // Button Meshes
  72853. for (i = 0; i < this._mapping.buttons.length; i++) {
  72854. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72855. if (!buttonMeshName) {
  72856. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72857. continue;
  72858. }
  72859. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72860. if (!buttonMesh) {
  72861. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72862. continue;
  72863. }
  72864. var buttonMeshInfo = {
  72865. index: i,
  72866. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72867. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72868. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72869. };
  72870. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72871. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72872. }
  72873. else {
  72874. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72875. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72876. '(VALUE: ' + !!buttonMeshInfo.value +
  72877. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72878. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72879. ')');
  72880. }
  72881. }
  72882. // Axis Meshes
  72883. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72884. var axisMeshName = this._mapping.axisMeshNames[i];
  72885. if (!axisMeshName) {
  72886. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72887. continue;
  72888. }
  72889. var axisMesh = getChildByName(rootNode, axisMeshName);
  72890. if (!axisMesh) {
  72891. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72892. continue;
  72893. }
  72894. var axisMeshInfo = {
  72895. index: i,
  72896. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72897. min: getImmediateChildByName(axisMesh, 'MIN'),
  72898. max: getImmediateChildByName(axisMesh, 'MAX')
  72899. };
  72900. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72901. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72902. }
  72903. else {
  72904. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72905. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72906. '(VALUE: ' + !!axisMeshInfo.value +
  72907. ', MIN: ' + !!axisMeshInfo.min +
  72908. ', MAX:' + !!axisMeshInfo.max +
  72909. ')');
  72910. }
  72911. }
  72912. // Pointing Ray
  72913. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72914. if (!loadedMeshInfo.pointingPoseNode) {
  72915. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72916. }
  72917. return loadedMeshInfo;
  72918. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72919. function getChildByName(node, name) {
  72920. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72921. }
  72922. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72923. function getImmediateChildByName(node, name) {
  72924. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72925. }
  72926. };
  72927. /**
  72928. * Gets the ray of the controller in the direction the controller is pointing
  72929. * @param length the length the resulting ray should be
  72930. * @returns a ray in the direction the controller is pointing
  72931. */
  72932. WindowsMotionController.prototype.getForwardRay = function (length) {
  72933. if (length === void 0) { length = 100; }
  72934. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72935. return _super.prototype.getForwardRay.call(this, length);
  72936. }
  72937. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72938. var origin = m.getTranslation();
  72939. var forward = new BABYLON.Vector3(0, 0, -1);
  72940. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72941. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72942. return new BABYLON.Ray(origin, direction, length);
  72943. };
  72944. /**
  72945. * Disposes of the controller
  72946. */
  72947. WindowsMotionController.prototype.dispose = function () {
  72948. _super.prototype.dispose.call(this);
  72949. this.onTrackpadChangedObservable.clear();
  72950. };
  72951. /**
  72952. * The base url used to load the left and right controller models
  72953. */
  72954. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72955. /**
  72956. * The name of the left controller model file
  72957. */
  72958. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72959. /**
  72960. * The name of the right controller model file
  72961. */
  72962. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72963. /**
  72964. * The controller name prefix for this controller type
  72965. */
  72966. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72967. /**
  72968. * The controller id pattern for this controller type
  72969. */
  72970. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72971. return WindowsMotionController;
  72972. }(BABYLON.WebVRController));
  72973. BABYLON.WindowsMotionController = WindowsMotionController;
  72974. })(BABYLON || (BABYLON = {}));
  72975. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72976. var BABYLON;
  72977. (function (BABYLON) {
  72978. /**
  72979. * Gear VR Controller
  72980. */
  72981. var GearVRController = /** @class */ (function (_super) {
  72982. __extends(GearVRController, _super);
  72983. /**
  72984. * Creates a new GearVRController from a gamepad
  72985. * @param vrGamepad the gamepad that the controller should be created from
  72986. */
  72987. function GearVRController(vrGamepad) {
  72988. var _this = _super.call(this, vrGamepad) || this;
  72989. _this._buttonIndexToObservableNameMap = [
  72990. 'onTrackpadChangedObservable',
  72991. 'onTriggerStateChangedObservable' // Trigger
  72992. ];
  72993. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72994. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72995. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72996. return _this;
  72997. }
  72998. /**
  72999. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73000. * @param scene scene in which to add meshes
  73001. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73002. */
  73003. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73004. var _this = this;
  73005. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  73006. _this._defaultModel = newMeshes[1];
  73007. _this.attachToMesh(_this._defaultModel);
  73008. if (meshLoaded) {
  73009. meshLoaded(_this._defaultModel);
  73010. }
  73011. });
  73012. };
  73013. /**
  73014. * Called once for each button that changed state since the last frame
  73015. * @param buttonIdx Which button index changed
  73016. * @param state New state of the button
  73017. * @param changes Which properties on the state changed since last frame
  73018. */
  73019. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73020. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  73021. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  73022. // Only emit events for buttons that we know how to map from index to observable
  73023. var observable = this[observableName];
  73024. if (observable) {
  73025. observable.notifyObservers(state);
  73026. }
  73027. }
  73028. };
  73029. /**
  73030. * Base Url for the controller model.
  73031. */
  73032. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  73033. /**
  73034. * File name for the controller model.
  73035. */
  73036. GearVRController.MODEL_FILENAME = 'generic.babylon';
  73037. /**
  73038. * Gamepad Id prefix used to identify this controller.
  73039. */
  73040. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  73041. return GearVRController;
  73042. }(BABYLON.WebVRController));
  73043. BABYLON.GearVRController = GearVRController;
  73044. })(BABYLON || (BABYLON = {}));
  73045. //# sourceMappingURL=babylon.gearVRController.js.map
  73046. var BABYLON;
  73047. (function (BABYLON) {
  73048. /**
  73049. * Google Daydream controller
  73050. */
  73051. var DaydreamController = /** @class */ (function (_super) {
  73052. __extends(DaydreamController, _super);
  73053. /**
  73054. * Creates a new DaydreamController from a gamepad
  73055. * @param vrGamepad the gamepad that the controller should be created from
  73056. */
  73057. function DaydreamController(vrGamepad) {
  73058. var _this = _super.call(this, vrGamepad) || this;
  73059. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  73060. return _this;
  73061. }
  73062. /**
  73063. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73064. * @param scene scene in which to add meshes
  73065. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73066. */
  73067. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73068. var _this = this;
  73069. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  73070. _this._defaultModel = newMeshes[1];
  73071. _this.attachToMesh(_this._defaultModel);
  73072. if (meshLoaded) {
  73073. meshLoaded(_this._defaultModel);
  73074. }
  73075. });
  73076. };
  73077. /**
  73078. * Called once for each button that changed state since the last frame
  73079. * @param buttonIdx Which button index changed
  73080. * @param state New state of the button
  73081. * @param changes Which properties on the state changed since last frame
  73082. */
  73083. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73084. // Daydream controller only has 1 GamepadButton (on the trackpad).
  73085. if (buttonIdx === 0) {
  73086. var observable = this.onTriggerStateChangedObservable;
  73087. if (observable) {
  73088. observable.notifyObservers(state);
  73089. }
  73090. }
  73091. else {
  73092. // If the app or home buttons are ever made available
  73093. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  73094. }
  73095. };
  73096. /**
  73097. * Base Url for the controller model.
  73098. */
  73099. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  73100. /**
  73101. * File name for the controller model.
  73102. */
  73103. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  73104. /**
  73105. * Gamepad Id prefix used to identify Daydream Controller.
  73106. */
  73107. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  73108. return DaydreamController;
  73109. }(BABYLON.WebVRController));
  73110. BABYLON.DaydreamController = DaydreamController;
  73111. })(BABYLON || (BABYLON = {}));
  73112. //# sourceMappingURL=babylon.daydreamController.js.map
  73113. var BABYLON;
  73114. (function (BABYLON) {
  73115. var FollowCamera = /** @class */ (function (_super) {
  73116. __extends(FollowCamera, _super);
  73117. function FollowCamera(name, position, scene, lockedTarget) {
  73118. if (lockedTarget === void 0) { lockedTarget = null; }
  73119. var _this = _super.call(this, name, position, scene) || this;
  73120. _this.radius = 12;
  73121. _this.rotationOffset = 0;
  73122. _this.heightOffset = 4;
  73123. _this.cameraAcceleration = 0.05;
  73124. _this.maxCameraSpeed = 20;
  73125. _this.lockedTarget = lockedTarget;
  73126. return _this;
  73127. }
  73128. FollowCamera.prototype.getRadians = function (degrees) {
  73129. return degrees * Math.PI / 180;
  73130. };
  73131. FollowCamera.prototype.follow = function (cameraTarget) {
  73132. if (!cameraTarget)
  73133. return;
  73134. var yRotation;
  73135. if (cameraTarget.rotationQuaternion) {
  73136. var rotMatrix = new BABYLON.Matrix();
  73137. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  73138. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  73139. }
  73140. else {
  73141. yRotation = cameraTarget.rotation.y;
  73142. }
  73143. var radians = this.getRadians(this.rotationOffset) + yRotation;
  73144. var targetPosition = cameraTarget.getAbsolutePosition();
  73145. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  73146. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  73147. var dx = targetX - this.position.x;
  73148. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  73149. var dz = (targetZ) - this.position.z;
  73150. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  73151. var vy = dy * this.cameraAcceleration;
  73152. var vz = dz * this.cameraAcceleration * 2;
  73153. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  73154. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73155. }
  73156. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  73157. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73158. }
  73159. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  73160. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73161. }
  73162. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  73163. this.setTarget(targetPosition);
  73164. };
  73165. FollowCamera.prototype._checkInputs = function () {
  73166. _super.prototype._checkInputs.call(this);
  73167. if (this.lockedTarget) {
  73168. this.follow(this.lockedTarget);
  73169. }
  73170. };
  73171. FollowCamera.prototype.getClassName = function () {
  73172. return "FollowCamera";
  73173. };
  73174. __decorate([
  73175. BABYLON.serialize()
  73176. ], FollowCamera.prototype, "radius", void 0);
  73177. __decorate([
  73178. BABYLON.serialize()
  73179. ], FollowCamera.prototype, "rotationOffset", void 0);
  73180. __decorate([
  73181. BABYLON.serialize()
  73182. ], FollowCamera.prototype, "heightOffset", void 0);
  73183. __decorate([
  73184. BABYLON.serialize()
  73185. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  73186. __decorate([
  73187. BABYLON.serialize()
  73188. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  73189. __decorate([
  73190. BABYLON.serializeAsMeshReference("lockedTargetId")
  73191. ], FollowCamera.prototype, "lockedTarget", void 0);
  73192. return FollowCamera;
  73193. }(BABYLON.TargetCamera));
  73194. BABYLON.FollowCamera = FollowCamera;
  73195. var ArcFollowCamera = /** @class */ (function (_super) {
  73196. __extends(ArcFollowCamera, _super);
  73197. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  73198. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  73199. _this.alpha = alpha;
  73200. _this.beta = beta;
  73201. _this.radius = radius;
  73202. _this.target = target;
  73203. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  73204. _this.follow();
  73205. return _this;
  73206. }
  73207. ArcFollowCamera.prototype.follow = function () {
  73208. if (!this.target) {
  73209. return;
  73210. }
  73211. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  73212. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  73213. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  73214. var targetPosition = this.target.getAbsolutePosition();
  73215. this.position = targetPosition.add(this._cartesianCoordinates);
  73216. this.setTarget(targetPosition);
  73217. };
  73218. ArcFollowCamera.prototype._checkInputs = function () {
  73219. _super.prototype._checkInputs.call(this);
  73220. this.follow();
  73221. };
  73222. ArcFollowCamera.prototype.getClassName = function () {
  73223. return "ArcFollowCamera";
  73224. };
  73225. return ArcFollowCamera;
  73226. }(BABYLON.TargetCamera));
  73227. BABYLON.ArcFollowCamera = ArcFollowCamera;
  73228. })(BABYLON || (BABYLON = {}));
  73229. //# sourceMappingURL=babylon.followCamera.js.map
  73230. var BABYLON;
  73231. (function (BABYLON) {
  73232. // We're mainly based on the logic defined into the FreeCamera code
  73233. var UniversalCamera = /** @class */ (function (_super) {
  73234. __extends(UniversalCamera, _super);
  73235. //-- end properties for backward compatibility for inputs
  73236. function UniversalCamera(name, position, scene) {
  73237. var _this = _super.call(this, name, position, scene) || this;
  73238. _this.inputs.addGamepad();
  73239. return _this;
  73240. }
  73241. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  73242. //-- Begin properties for backward compatibility for inputs
  73243. get: function () {
  73244. var gamepad = this.inputs.attached["gamepad"];
  73245. if (gamepad)
  73246. return gamepad.gamepadAngularSensibility;
  73247. return 0;
  73248. },
  73249. set: function (value) {
  73250. var gamepad = this.inputs.attached["gamepad"];
  73251. if (gamepad)
  73252. gamepad.gamepadAngularSensibility = value;
  73253. },
  73254. enumerable: true,
  73255. configurable: true
  73256. });
  73257. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  73258. get: function () {
  73259. var gamepad = this.inputs.attached["gamepad"];
  73260. if (gamepad)
  73261. return gamepad.gamepadMoveSensibility;
  73262. return 0;
  73263. },
  73264. set: function (value) {
  73265. var gamepad = this.inputs.attached["gamepad"];
  73266. if (gamepad)
  73267. gamepad.gamepadMoveSensibility = value;
  73268. },
  73269. enumerable: true,
  73270. configurable: true
  73271. });
  73272. UniversalCamera.prototype.getClassName = function () {
  73273. return "UniversalCamera";
  73274. };
  73275. return UniversalCamera;
  73276. }(BABYLON.TouchCamera));
  73277. BABYLON.UniversalCamera = UniversalCamera;
  73278. })(BABYLON || (BABYLON = {}));
  73279. //# sourceMappingURL=babylon.universalCamera.js.map
  73280. var BABYLON;
  73281. (function (BABYLON) {
  73282. // We're mainly based on the logic defined into the FreeCamera code
  73283. var GamepadCamera = /** @class */ (function (_super) {
  73284. __extends(GamepadCamera, _super);
  73285. //-- end properties for backward compatibility for inputs
  73286. function GamepadCamera(name, position, scene) {
  73287. return _super.call(this, name, position, scene) || this;
  73288. }
  73289. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  73290. //-- Begin properties for backward compatibility for inputs
  73291. get: function () {
  73292. var gamepad = this.inputs.attached["gamepad"];
  73293. if (gamepad)
  73294. return gamepad.gamepadAngularSensibility;
  73295. return 0;
  73296. },
  73297. set: function (value) {
  73298. var gamepad = this.inputs.attached["gamepad"];
  73299. if (gamepad)
  73300. gamepad.gamepadAngularSensibility = value;
  73301. },
  73302. enumerable: true,
  73303. configurable: true
  73304. });
  73305. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  73306. get: function () {
  73307. var gamepad = this.inputs.attached["gamepad"];
  73308. if (gamepad)
  73309. return gamepad.gamepadMoveSensibility;
  73310. return 0;
  73311. },
  73312. set: function (value) {
  73313. var gamepad = this.inputs.attached["gamepad"];
  73314. if (gamepad)
  73315. gamepad.gamepadMoveSensibility = value;
  73316. },
  73317. enumerable: true,
  73318. configurable: true
  73319. });
  73320. GamepadCamera.prototype.getClassName = function () {
  73321. return "GamepadCamera";
  73322. };
  73323. return GamepadCamera;
  73324. }(BABYLON.UniversalCamera));
  73325. BABYLON.GamepadCamera = GamepadCamera;
  73326. })(BABYLON || (BABYLON = {}));
  73327. //# sourceMappingURL=babylon.gamepadCamera.js.map
  73328. var BABYLON;
  73329. (function (BABYLON) {
  73330. var PostProcessRenderPipelineManager = /** @class */ (function () {
  73331. function PostProcessRenderPipelineManager() {
  73332. this._renderPipelines = {};
  73333. }
  73334. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  73335. this._renderPipelines[renderPipeline._name] = renderPipeline;
  73336. };
  73337. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  73338. if (unique === void 0) { unique = false; }
  73339. var renderPipeline = this._renderPipelines[renderPipelineName];
  73340. if (!renderPipeline) {
  73341. return;
  73342. }
  73343. renderPipeline._attachCameras(cameras, unique);
  73344. };
  73345. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  73346. var renderPipeline = this._renderPipelines[renderPipelineName];
  73347. if (!renderPipeline) {
  73348. return;
  73349. }
  73350. renderPipeline._detachCameras(cameras);
  73351. };
  73352. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73353. var renderPipeline = this._renderPipelines[renderPipelineName];
  73354. if (!renderPipeline) {
  73355. return;
  73356. }
  73357. renderPipeline._enableEffect(renderEffectName, cameras);
  73358. };
  73359. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73360. var renderPipeline = this._renderPipelines[renderPipelineName];
  73361. if (!renderPipeline) {
  73362. return;
  73363. }
  73364. renderPipeline._disableEffect(renderEffectName, cameras);
  73365. };
  73366. PostProcessRenderPipelineManager.prototype.update = function () {
  73367. for (var renderPipelineName in this._renderPipelines) {
  73368. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73369. var pipeline = this._renderPipelines[renderPipelineName];
  73370. if (!pipeline.isSupported) {
  73371. pipeline.dispose();
  73372. delete this._renderPipelines[renderPipelineName];
  73373. }
  73374. else {
  73375. pipeline._update();
  73376. }
  73377. }
  73378. }
  73379. };
  73380. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  73381. for (var renderPipelineName in this._renderPipelines) {
  73382. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73383. var pipeline = this._renderPipelines[renderPipelineName];
  73384. pipeline._rebuild();
  73385. }
  73386. }
  73387. };
  73388. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73389. for (var renderPipelineName in this._renderPipelines) {
  73390. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73391. var pipeline = this._renderPipelines[renderPipelineName];
  73392. pipeline.dispose();
  73393. }
  73394. }
  73395. };
  73396. return PostProcessRenderPipelineManager;
  73397. }());
  73398. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73399. })(BABYLON || (BABYLON = {}));
  73400. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73401. var BABYLON;
  73402. (function (BABYLON) {
  73403. /**
  73404. * This represents a set of one or more post processes in Babylon.
  73405. * A post process can be used to apply a shader to a texture after it is rendered.
  73406. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73407. */
  73408. var PostProcessRenderEffect = /** @class */ (function () {
  73409. /**
  73410. * Instantiates a post process render effect.
  73411. * A post process can be used to apply a shader to a texture after it is rendered.
  73412. * @param engine The engine the effect is tied to
  73413. * @param name The name of the effect
  73414. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73415. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73416. */
  73417. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73418. this._name = name;
  73419. this._singleInstance = singleInstance || true;
  73420. this._getPostProcesses = getPostProcesses;
  73421. this._cameras = {};
  73422. this._indicesForCamera = {};
  73423. this._postProcesses = {};
  73424. }
  73425. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73426. /**
  73427. * Checks if all the post processes in the effect are supported.
  73428. */
  73429. get: function () {
  73430. for (var index in this._postProcesses) {
  73431. if (this._postProcesses.hasOwnProperty(index)) {
  73432. var pps = this._postProcesses[index];
  73433. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73434. if (!pps[ppIndex].isSupported) {
  73435. return false;
  73436. }
  73437. }
  73438. }
  73439. }
  73440. return true;
  73441. },
  73442. enumerable: true,
  73443. configurable: true
  73444. });
  73445. /**
  73446. * Updates the current state of the effect
  73447. */
  73448. PostProcessRenderEffect.prototype._update = function () {
  73449. };
  73450. /**
  73451. * Attaches the effect on cameras
  73452. * @param cameras The camera to attach to.
  73453. */
  73454. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73455. var _this = this;
  73456. var cameraKey;
  73457. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73458. if (!cams) {
  73459. return;
  73460. }
  73461. for (var i = 0; i < cams.length; i++) {
  73462. var camera = cams[i];
  73463. var cameraName = camera.name;
  73464. if (this._singleInstance) {
  73465. cameraKey = 0;
  73466. }
  73467. else {
  73468. cameraKey = cameraName;
  73469. }
  73470. if (!this._postProcesses[cameraKey]) {
  73471. var postProcess = this._getPostProcesses();
  73472. if (postProcess) {
  73473. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73474. }
  73475. }
  73476. if (!this._indicesForCamera[cameraName]) {
  73477. this._indicesForCamera[cameraName] = [];
  73478. }
  73479. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73480. var index = camera.attachPostProcess(postProcess);
  73481. _this._indicesForCamera[cameraName].push(index);
  73482. });
  73483. if (!this._cameras[cameraName]) {
  73484. this._cameras[cameraName] = camera;
  73485. }
  73486. }
  73487. };
  73488. /**
  73489. * Detatches the effect on cameras
  73490. * @param cameras The camera to detatch from.
  73491. */
  73492. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73493. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73494. if (!cams) {
  73495. return;
  73496. }
  73497. for (var i = 0; i < cams.length; i++) {
  73498. var camera = cams[i];
  73499. var cameraName = camera.name;
  73500. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73501. camera.detachPostProcess(postProcess);
  73502. });
  73503. if (this._cameras[cameraName]) {
  73504. //this._indicesForCamera.splice(index, 1);
  73505. this._cameras[cameraName] = null;
  73506. }
  73507. }
  73508. };
  73509. /**
  73510. * Enables the effect on given cameras
  73511. * @param cameras The camera to enable.
  73512. */
  73513. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73514. var _this = this;
  73515. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73516. if (!cams) {
  73517. return;
  73518. }
  73519. for (var i = 0; i < cams.length; i++) {
  73520. var camera = cams[i];
  73521. var cameraName = camera.name;
  73522. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73523. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73524. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73525. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73526. });
  73527. }
  73528. }
  73529. }
  73530. };
  73531. /**
  73532. * Disables the effect on the given cameras
  73533. * @param cameras The camera to disable.
  73534. */
  73535. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73536. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73537. if (!cams) {
  73538. return;
  73539. }
  73540. for (var i = 0; i < cams.length; i++) {
  73541. var camera = cams[i];
  73542. var cameraName = camera.name;
  73543. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73544. camera.detachPostProcess(postProcess);
  73545. });
  73546. }
  73547. };
  73548. /**
  73549. * Gets a list of the post processes contained in the effect.
  73550. * @param camera The camera to get the post processes on.
  73551. * @returns The list of the post processes in the effect.
  73552. */
  73553. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73554. if (this._singleInstance) {
  73555. return this._postProcesses[0];
  73556. }
  73557. else {
  73558. if (!camera) {
  73559. return null;
  73560. }
  73561. return this._postProcesses[camera.name];
  73562. }
  73563. };
  73564. return PostProcessRenderEffect;
  73565. }());
  73566. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73567. })(BABYLON || (BABYLON = {}));
  73568. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73569. var BABYLON;
  73570. (function (BABYLON) {
  73571. var PostProcessRenderPipeline = /** @class */ (function () {
  73572. function PostProcessRenderPipeline(engine, name) {
  73573. this.engine = engine;
  73574. this._name = name;
  73575. this._renderEffects = {};
  73576. this._renderEffectsForIsolatedPass = new Array();
  73577. this._cameras = [];
  73578. }
  73579. PostProcessRenderPipeline.prototype.getClassName = function () {
  73580. return "PostProcessRenderPipeline";
  73581. };
  73582. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73583. get: function () {
  73584. for (var renderEffectName in this._renderEffects) {
  73585. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73586. if (!this._renderEffects[renderEffectName].isSupported) {
  73587. return false;
  73588. }
  73589. }
  73590. }
  73591. return true;
  73592. },
  73593. enumerable: true,
  73594. configurable: true
  73595. });
  73596. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73597. this._renderEffects[renderEffect._name] = renderEffect;
  73598. };
  73599. // private
  73600. PostProcessRenderPipeline.prototype._rebuild = function () {
  73601. };
  73602. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73603. var renderEffects = this._renderEffects[renderEffectName];
  73604. if (!renderEffects) {
  73605. return;
  73606. }
  73607. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73608. };
  73609. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73610. var renderEffects = this._renderEffects[renderEffectName];
  73611. if (!renderEffects) {
  73612. return;
  73613. }
  73614. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73615. };
  73616. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73617. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73618. if (!cams) {
  73619. return;
  73620. }
  73621. var indicesToDelete = [];
  73622. var i;
  73623. for (i = 0; i < cams.length; i++) {
  73624. var camera = cams[i];
  73625. var cameraName = camera.name;
  73626. if (this._cameras.indexOf(camera) === -1) {
  73627. this._cameras[cameraName] = camera;
  73628. }
  73629. else if (unique) {
  73630. indicesToDelete.push(i);
  73631. }
  73632. }
  73633. for (i = 0; i < indicesToDelete.length; i++) {
  73634. cameras.splice(indicesToDelete[i], 1);
  73635. }
  73636. for (var renderEffectName in this._renderEffects) {
  73637. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73638. this._renderEffects[renderEffectName]._attachCameras(cams);
  73639. }
  73640. }
  73641. };
  73642. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73643. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73644. if (!cams) {
  73645. return;
  73646. }
  73647. for (var renderEffectName in this._renderEffects) {
  73648. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73649. this._renderEffects[renderEffectName]._detachCameras(cams);
  73650. }
  73651. }
  73652. for (var i = 0; i < cams.length; i++) {
  73653. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73654. }
  73655. };
  73656. PostProcessRenderPipeline.prototype._update = function () {
  73657. for (var renderEffectName in this._renderEffects) {
  73658. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73659. this._renderEffects[renderEffectName]._update();
  73660. }
  73661. }
  73662. for (var i = 0; i < this._cameras.length; i++) {
  73663. var cameraName = this._cameras[i].name;
  73664. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73665. this._renderEffectsForIsolatedPass[cameraName]._update();
  73666. }
  73667. }
  73668. };
  73669. PostProcessRenderPipeline.prototype._reset = function () {
  73670. this._renderEffects = {};
  73671. this._renderEffectsForIsolatedPass = new Array();
  73672. };
  73673. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73674. // 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)
  73675. var effectKeys = Object.keys(this._renderEffects);
  73676. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73677. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73678. if (postProcesses) {
  73679. postProcesses[0].samples = sampleCount;
  73680. return true;
  73681. }
  73682. }
  73683. return false;
  73684. };
  73685. PostProcessRenderPipeline.prototype.dispose = function () {
  73686. // Must be implemented by children
  73687. };
  73688. __decorate([
  73689. BABYLON.serialize()
  73690. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73691. return PostProcessRenderPipeline;
  73692. }());
  73693. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73694. })(BABYLON || (BABYLON = {}));
  73695. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73696. var BABYLON;
  73697. (function (BABYLON) {
  73698. /**
  73699. * This represents a depth renderer in Babylon.
  73700. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73701. */
  73702. var DepthRenderer = /** @class */ (function () {
  73703. /**
  73704. * Instantiates a depth renderer
  73705. * @param scene The scene the renderer belongs to
  73706. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73707. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73708. */
  73709. function DepthRenderer(scene, type, camera) {
  73710. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73711. if (camera === void 0) { camera = null; }
  73712. var _this = this;
  73713. this._scene = scene;
  73714. this._camera = camera;
  73715. var engine = scene.getEngine();
  73716. // Render target
  73717. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73718. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73719. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73720. this._depthMap.refreshRate = 1;
  73721. this._depthMap.renderParticles = false;
  73722. this._depthMap.renderList = null;
  73723. // Camera to get depth map from to support multiple concurrent cameras
  73724. this._depthMap.activeCamera = this._camera;
  73725. this._depthMap.ignoreCameraViewport = true;
  73726. this._depthMap.useCameraPostProcesses = false;
  73727. // set default depth value to 1.0 (far away)
  73728. this._depthMap.onClearObservable.add(function (engine) {
  73729. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73730. });
  73731. // Custom render function
  73732. var renderSubMesh = function (subMesh) {
  73733. var mesh = subMesh.getRenderingMesh();
  73734. var scene = _this._scene;
  73735. var engine = scene.getEngine();
  73736. var material = subMesh.getMaterial();
  73737. if (!material) {
  73738. return;
  73739. }
  73740. // Culling and reverse (right handed system)
  73741. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73742. // Managing instances
  73743. var batch = mesh._getInstancesRenderList(subMesh._id);
  73744. if (batch.mustReturn) {
  73745. return;
  73746. }
  73747. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73748. var camera = _this._camera || scene.activeCamera;
  73749. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73750. engine.enableEffect(_this._effect);
  73751. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73752. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73753. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73754. // Alpha test
  73755. if (material && material.needAlphaTesting()) {
  73756. var alphaTexture = material.getAlphaTestTexture();
  73757. if (alphaTexture) {
  73758. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73759. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73760. }
  73761. }
  73762. // Bones
  73763. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73764. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73765. }
  73766. // Draw
  73767. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73768. }
  73769. };
  73770. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73771. var index;
  73772. if (depthOnlySubMeshes.length) {
  73773. engine.setColorWrite(false);
  73774. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73775. renderSubMesh(depthOnlySubMeshes.data[index]);
  73776. }
  73777. engine.setColorWrite(true);
  73778. }
  73779. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73780. renderSubMesh(opaqueSubMeshes.data[index]);
  73781. }
  73782. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73783. renderSubMesh(alphaTestSubMeshes.data[index]);
  73784. }
  73785. };
  73786. }
  73787. /**
  73788. * Creates the depth rendering effect and checks if the effect is ready.
  73789. * @param subMesh The submesh to be used to render the depth map of
  73790. * @param useInstances If multiple world instances should be used
  73791. * @returns if the depth renderer is ready to render the depth map
  73792. */
  73793. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73794. var material = subMesh.getMaterial();
  73795. if (material.disableDepthWrite) {
  73796. return false;
  73797. }
  73798. var defines = [];
  73799. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73800. var mesh = subMesh.getMesh();
  73801. // Alpha test
  73802. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73803. defines.push("#define ALPHATEST");
  73804. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73805. attribs.push(BABYLON.VertexBuffer.UVKind);
  73806. defines.push("#define UV1");
  73807. }
  73808. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73809. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73810. defines.push("#define UV2");
  73811. }
  73812. }
  73813. // Bones
  73814. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73815. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73816. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73817. if (mesh.numBoneInfluencers > 4) {
  73818. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73819. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73820. }
  73821. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73822. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73823. }
  73824. else {
  73825. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73826. }
  73827. // Instances
  73828. if (useInstances) {
  73829. defines.push("#define INSTANCES");
  73830. attribs.push("world0");
  73831. attribs.push("world1");
  73832. attribs.push("world2");
  73833. attribs.push("world3");
  73834. }
  73835. // Get correct effect
  73836. var join = defines.join("\n");
  73837. if (this._cachedDefines !== join) {
  73838. this._cachedDefines = join;
  73839. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73840. }
  73841. return this._effect.isReady();
  73842. };
  73843. /**
  73844. * Gets the texture which the depth map will be written to.
  73845. * @returns The depth map texture
  73846. */
  73847. DepthRenderer.prototype.getDepthMap = function () {
  73848. return this._depthMap;
  73849. };
  73850. /**
  73851. * Disposes of the depth renderer.
  73852. */
  73853. DepthRenderer.prototype.dispose = function () {
  73854. this._depthMap.dispose();
  73855. };
  73856. return DepthRenderer;
  73857. }());
  73858. BABYLON.DepthRenderer = DepthRenderer;
  73859. })(BABYLON || (BABYLON = {}));
  73860. //# sourceMappingURL=babylon.depthRenderer.js.map
  73861. var BABYLON;
  73862. (function (BABYLON) {
  73863. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73864. __extends(SSAORenderingPipeline, _super);
  73865. /**
  73866. * @constructor
  73867. * @param {string} name - The rendering pipeline name
  73868. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73869. * @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 }
  73870. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73871. */
  73872. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73873. var _this = _super.call(this, scene.getEngine(), name) || this;
  73874. // Members
  73875. /**
  73876. * The PassPostProcess id in the pipeline that contains the original scene color
  73877. */
  73878. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73879. /**
  73880. * The SSAO PostProcess id in the pipeline
  73881. */
  73882. _this.SSAORenderEffect = "SSAORenderEffect";
  73883. /**
  73884. * The horizontal blur PostProcess id in the pipeline
  73885. */
  73886. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73887. /**
  73888. * The vertical blur PostProcess id in the pipeline
  73889. */
  73890. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73891. /**
  73892. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73893. */
  73894. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73895. /**
  73896. * The output strength of the SSAO post-process. Default value is 1.0.
  73897. */
  73898. _this.totalStrength = 1.0;
  73899. /**
  73900. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73901. */
  73902. _this.radius = 0.0001;
  73903. /**
  73904. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73905. * Must not be equal to fallOff and superior to fallOff.
  73906. * Default value is 0.975
  73907. */
  73908. _this.area = 0.0075;
  73909. /**
  73910. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73911. * Must not be equal to area and inferior to area.
  73912. * Default value is 0.0
  73913. */
  73914. _this.fallOff = 0.000001;
  73915. /**
  73916. * The base color of the SSAO post-process
  73917. * The final result is "base + ssao" between [0, 1]
  73918. */
  73919. _this.base = 0.5;
  73920. _this._firstUpdate = true;
  73921. _this._scene = scene;
  73922. // Set up assets
  73923. _this._createRandomTexture();
  73924. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73925. var ssaoRatio = ratio.ssaoRatio || ratio;
  73926. var combineRatio = ratio.combineRatio || ratio;
  73927. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73928. _this._createSSAOPostProcess(ssaoRatio);
  73929. _this._createBlurPostProcess(ssaoRatio);
  73930. _this._createSSAOCombinePostProcess(combineRatio);
  73931. // Set up pipeline
  73932. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73933. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73934. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73935. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73936. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73937. // Finish
  73938. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73939. if (cameras)
  73940. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73941. return _this;
  73942. }
  73943. // Public Methods
  73944. /**
  73945. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73946. */
  73947. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73948. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73949. for (var i = 0; i < this._scene.cameras.length; i++) {
  73950. var camera = this._scene.cameras[i];
  73951. this._originalColorPostProcess.dispose(camera);
  73952. this._ssaoPostProcess.dispose(camera);
  73953. this._blurHPostProcess.dispose(camera);
  73954. this._blurVPostProcess.dispose(camera);
  73955. this._ssaoCombinePostProcess.dispose(camera);
  73956. }
  73957. this._randomTexture.dispose();
  73958. if (disableDepthRender)
  73959. this._scene.disableDepthRenderer();
  73960. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73961. _super.prototype.dispose.call(this);
  73962. };
  73963. // Private Methods
  73964. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73965. var _this = this;
  73966. var size = 16;
  73967. 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);
  73968. 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);
  73969. this._blurHPostProcess.onActivateObservable.add(function () {
  73970. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73971. _this._blurHPostProcess.kernel = size * dw;
  73972. });
  73973. this._blurVPostProcess.onActivateObservable.add(function () {
  73974. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73975. _this._blurVPostProcess.kernel = size * dw;
  73976. });
  73977. };
  73978. SSAORenderingPipeline.prototype._rebuild = function () {
  73979. this._firstUpdate = true;
  73980. _super.prototype._rebuild.call(this);
  73981. };
  73982. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73983. var _this = this;
  73984. var numSamples = 16;
  73985. var sampleSphere = [
  73986. 0.5381, 0.1856, -0.4319,
  73987. 0.1379, 0.2486, 0.4430,
  73988. 0.3371, 0.5679, -0.0057,
  73989. -0.6999, -0.0451, -0.0019,
  73990. 0.0689, -0.1598, -0.8547,
  73991. 0.0560, 0.0069, -0.1843,
  73992. -0.0146, 0.1402, 0.0762,
  73993. 0.0100, -0.1924, -0.0344,
  73994. -0.3577, -0.5301, -0.4358,
  73995. -0.3169, 0.1063, 0.0158,
  73996. 0.0103, -0.5869, 0.0046,
  73997. -0.0897, -0.4940, 0.3287,
  73998. 0.7119, -0.0154, -0.0918,
  73999. -0.0533, 0.0596, -0.5411,
  74000. 0.0352, -0.0631, 0.5460,
  74001. -0.4776, 0.2847, -0.0271
  74002. ];
  74003. var samplesFactor = 1.0 / numSamples;
  74004. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  74005. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74006. "area", "fallOff", "base", "range", "viewport"
  74007. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74008. this._ssaoPostProcess.onApply = function (effect) {
  74009. if (_this._firstUpdate) {
  74010. effect.setArray3("sampleSphere", sampleSphere);
  74011. effect.setFloat("samplesFactor", samplesFactor);
  74012. effect.setFloat("randTextureTiles", 4.0);
  74013. }
  74014. effect.setFloat("totalStrength", _this.totalStrength);
  74015. effect.setFloat("radius", _this.radius);
  74016. effect.setFloat("area", _this.area);
  74017. effect.setFloat("fallOff", _this.fallOff);
  74018. effect.setFloat("base", _this.base);
  74019. effect.setTexture("textureSampler", _this._depthTexture);
  74020. effect.setTexture("randomSampler", _this._randomTexture);
  74021. };
  74022. };
  74023. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74024. var _this = this;
  74025. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74026. this._ssaoCombinePostProcess.onApply = function (effect) {
  74027. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  74028. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74029. };
  74030. };
  74031. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  74032. var size = 512;
  74033. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74034. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74035. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74036. var context = this._randomTexture.getContext();
  74037. var rand = function (min, max) {
  74038. return Math.random() * (max - min) + min;
  74039. };
  74040. var randVector = BABYLON.Vector3.Zero();
  74041. for (var x = 0; x < size; x++) {
  74042. for (var y = 0; y < size; y++) {
  74043. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  74044. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  74045. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  74046. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74047. context.fillRect(x, y, 1, 1);
  74048. }
  74049. }
  74050. this._randomTexture.update(false);
  74051. };
  74052. __decorate([
  74053. BABYLON.serialize()
  74054. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  74055. __decorate([
  74056. BABYLON.serialize()
  74057. ], SSAORenderingPipeline.prototype, "radius", void 0);
  74058. __decorate([
  74059. BABYLON.serialize()
  74060. ], SSAORenderingPipeline.prototype, "area", void 0);
  74061. __decorate([
  74062. BABYLON.serialize()
  74063. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  74064. __decorate([
  74065. BABYLON.serialize()
  74066. ], SSAORenderingPipeline.prototype, "base", void 0);
  74067. return SSAORenderingPipeline;
  74068. }(BABYLON.PostProcessRenderPipeline));
  74069. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  74070. })(BABYLON || (BABYLON = {}));
  74071. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  74072. var BABYLON;
  74073. (function (BABYLON) {
  74074. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  74075. __extends(SSAO2RenderingPipeline, _super);
  74076. /**
  74077. * @constructor
  74078. * @param {string} name - The rendering pipeline name
  74079. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74080. * @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 }
  74081. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74082. */
  74083. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  74084. var _this = _super.call(this, scene.getEngine(), name) || this;
  74085. // Members
  74086. /**
  74087. * The PassPostProcess id in the pipeline that contains the original scene color
  74088. */
  74089. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  74090. /**
  74091. * The SSAO PostProcess id in the pipeline
  74092. */
  74093. _this.SSAORenderEffect = "SSAORenderEffect";
  74094. /**
  74095. * The horizontal blur PostProcess id in the pipeline
  74096. */
  74097. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  74098. /**
  74099. * The vertical blur PostProcess id in the pipeline
  74100. */
  74101. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  74102. /**
  74103. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  74104. */
  74105. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  74106. /**
  74107. * The output strength of the SSAO post-process. Default value is 1.0.
  74108. */
  74109. _this.totalStrength = 1.0;
  74110. /**
  74111. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  74112. */
  74113. _this.maxZ = 100.0;
  74114. /**
  74115. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  74116. */
  74117. _this.minZAspect = 0.2;
  74118. /**
  74119. * Number of samples used for the SSAO calculations. Default value is 8
  74120. */
  74121. _this._samples = 8;
  74122. /**
  74123. * Are we using bilateral blur ?
  74124. */
  74125. _this._expensiveBlur = true;
  74126. /**
  74127. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  74128. */
  74129. _this.radius = 2.0;
  74130. /**
  74131. * The base color of the SSAO post-process
  74132. * The final result is "base + ssao" between [0, 1]
  74133. */
  74134. _this.base = 0.1;
  74135. _this._firstUpdate = true;
  74136. _this._scene = scene;
  74137. _this._ratio = ratio;
  74138. if (!_this.isSupported) {
  74139. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  74140. return _this;
  74141. }
  74142. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  74143. var blurRatio = _this._ratio.blurRatio || ratio;
  74144. // Set up assets
  74145. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  74146. _this._createRandomTexture();
  74147. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  74148. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  74149. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  74150. _this._createSSAOPostProcess(1.0);
  74151. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  74152. _this._createSSAOCombinePostProcess(blurRatio);
  74153. // Set up pipeline
  74154. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  74155. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  74156. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  74157. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  74158. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  74159. // Finish
  74160. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74161. if (cameras)
  74162. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74163. return _this;
  74164. }
  74165. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  74166. get: function () {
  74167. return this._samples;
  74168. },
  74169. set: function (n) {
  74170. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  74171. this._samples = n;
  74172. this._sampleSphere = this._generateHemisphere();
  74173. this._firstUpdate = true;
  74174. },
  74175. enumerable: true,
  74176. configurable: true
  74177. });
  74178. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  74179. get: function () {
  74180. return this._expensiveBlur;
  74181. },
  74182. set: function (b) {
  74183. 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"]);
  74184. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  74185. this._expensiveBlur = b;
  74186. this._firstUpdate = true;
  74187. },
  74188. enumerable: true,
  74189. configurable: true
  74190. });
  74191. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  74192. /**
  74193. * Support test.
  74194. */
  74195. get: function () {
  74196. var engine = BABYLON.Engine.LastCreatedEngine;
  74197. if (!engine) {
  74198. return false;
  74199. }
  74200. return engine.getCaps().drawBuffersExtension;
  74201. },
  74202. enumerable: true,
  74203. configurable: true
  74204. });
  74205. // Public Methods
  74206. /**
  74207. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  74208. */
  74209. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  74210. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  74211. for (var i = 0; i < this._scene.cameras.length; i++) {
  74212. var camera = this._scene.cameras[i];
  74213. this._originalColorPostProcess.dispose(camera);
  74214. this._ssaoPostProcess.dispose(camera);
  74215. this._blurHPostProcess.dispose(camera);
  74216. this._blurVPostProcess.dispose(camera);
  74217. this._ssaoCombinePostProcess.dispose(camera);
  74218. }
  74219. this._randomTexture.dispose();
  74220. if (disableGeometryBufferRenderer)
  74221. this._scene.disableGeometryBufferRenderer();
  74222. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74223. _super.prototype.dispose.call(this);
  74224. };
  74225. // Private Methods
  74226. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  74227. var _this = this;
  74228. this._samplerOffsets = [];
  74229. var expensive = this.expensiveBlur;
  74230. for (var i = -8; i < 8; i++) {
  74231. this._samplerOffsets.push(i * 2 + 0.5);
  74232. }
  74233. 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");
  74234. this._blurHPostProcess.onApply = function (effect) {
  74235. if (!_this._scene.activeCamera) {
  74236. return;
  74237. }
  74238. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  74239. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74240. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74241. effect.setFloat("radius", _this.radius);
  74242. effect.setTexture("depthSampler", _this._depthTexture);
  74243. if (_this._firstUpdate) {
  74244. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74245. }
  74246. };
  74247. 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");
  74248. this._blurVPostProcess.onApply = function (effect) {
  74249. if (!_this._scene.activeCamera) {
  74250. return;
  74251. }
  74252. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  74253. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74254. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74255. effect.setFloat("radius", _this.radius);
  74256. effect.setTexture("depthSampler", _this._depthTexture);
  74257. if (_this._firstUpdate) {
  74258. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74259. _this._firstUpdate = false;
  74260. }
  74261. };
  74262. };
  74263. SSAO2RenderingPipeline.prototype._rebuild = function () {
  74264. this._firstUpdate = true;
  74265. _super.prototype._rebuild.call(this);
  74266. };
  74267. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  74268. var numSamples = this.samples;
  74269. var result = [];
  74270. var vector, scale;
  74271. var rand = function (min, max) {
  74272. return Math.random() * (max - min) + min;
  74273. };
  74274. var i = 0;
  74275. while (i < numSamples) {
  74276. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  74277. vector.normalize();
  74278. scale = i / numSamples;
  74279. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  74280. vector.scaleInPlace(scale);
  74281. result.push(vector.x, vector.y, vector.z);
  74282. i++;
  74283. }
  74284. return result;
  74285. };
  74286. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  74287. var _this = this;
  74288. var numSamples = this.samples;
  74289. this._sampleSphere = this._generateHemisphere();
  74290. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  74291. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74292. "base", "range", "projection", "near", "far", "texelSize",
  74293. "xViewport", "yViewport", "maxZ", "minZAspect"
  74294. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74295. this._ssaoPostProcess.onApply = function (effect) {
  74296. if (_this._firstUpdate) {
  74297. effect.setArray3("sampleSphere", _this._sampleSphere);
  74298. effect.setFloat("randTextureTiles", 4.0);
  74299. }
  74300. if (!_this._scene.activeCamera) {
  74301. return;
  74302. }
  74303. effect.setFloat("samplesFactor", 1 / _this.samples);
  74304. effect.setFloat("totalStrength", _this.totalStrength);
  74305. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  74306. effect.setFloat("radius", _this.radius);
  74307. effect.setFloat("maxZ", _this.maxZ);
  74308. effect.setFloat("minZAspect", _this.minZAspect);
  74309. effect.setFloat("base", _this.base);
  74310. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74311. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74312. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  74313. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  74314. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  74315. effect.setTexture("textureSampler", _this._depthTexture);
  74316. effect.setTexture("normalSampler", _this._normalTexture);
  74317. effect.setTexture("randomSampler", _this._randomTexture);
  74318. };
  74319. };
  74320. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74321. var _this = this;
  74322. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74323. this._ssaoCombinePostProcess.onApply = function (effect) {
  74324. var viewport = _this._scene.activeCamera.viewport;
  74325. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  74326. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74327. };
  74328. };
  74329. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  74330. var size = 512;
  74331. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74332. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74333. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74334. var context = this._randomTexture.getContext();
  74335. var rand = function (min, max) {
  74336. return Math.random() * (max - min) + min;
  74337. };
  74338. var randVector = BABYLON.Vector3.Zero();
  74339. for (var x = 0; x < size; x++) {
  74340. for (var y = 0; y < size; y++) {
  74341. randVector.x = rand(0.0, 1.0);
  74342. randVector.y = rand(0.0, 1.0);
  74343. randVector.z = 0.0;
  74344. randVector.normalize();
  74345. randVector.scaleInPlace(255);
  74346. randVector.x = Math.floor(randVector.x);
  74347. randVector.y = Math.floor(randVector.y);
  74348. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74349. context.fillRect(x, y, 1, 1);
  74350. }
  74351. }
  74352. this._randomTexture.update(false);
  74353. };
  74354. /**
  74355. * Serialize the rendering pipeline (Used when exporting)
  74356. * @returns the serialized object
  74357. */
  74358. SSAO2RenderingPipeline.prototype.serialize = function () {
  74359. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74360. serializationObject.customType = "SSAO2RenderingPipeline";
  74361. return serializationObject;
  74362. };
  74363. /**
  74364. * Parse the serialized pipeline
  74365. * @param source Source pipeline.
  74366. * @param scene The scene to load the pipeline to.
  74367. * @param rootUrl The URL of the serialized pipeline.
  74368. * @returns An instantiated pipeline from the serialized object.
  74369. */
  74370. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  74371. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74372. };
  74373. __decorate([
  74374. BABYLON.serialize()
  74375. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  74376. __decorate([
  74377. BABYLON.serialize()
  74378. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  74379. __decorate([
  74380. BABYLON.serialize()
  74381. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74382. __decorate([
  74383. BABYLON.serialize("samples")
  74384. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74385. __decorate([
  74386. BABYLON.serialize()
  74387. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74388. __decorate([
  74389. BABYLON.serialize("expensiveBlur")
  74390. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74391. __decorate([
  74392. BABYLON.serialize()
  74393. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74394. __decorate([
  74395. BABYLON.serialize()
  74396. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74397. return SSAO2RenderingPipeline;
  74398. }(BABYLON.PostProcessRenderPipeline));
  74399. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74400. })(BABYLON || (BABYLON = {}));
  74401. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74402. // BABYLON.JS Chromatic Aberration GLSL Shader
  74403. // Author: Olivier Guyot
  74404. // Separates very slightly R, G and B colors on the edges of the screen
  74405. // Inspired by Francois Tarlier & Martins Upitis
  74406. var BABYLON;
  74407. (function (BABYLON) {
  74408. var LensRenderingPipeline = /** @class */ (function (_super) {
  74409. __extends(LensRenderingPipeline, _super);
  74410. /**
  74411. * @constructor
  74412. *
  74413. * Effect parameters are as follow:
  74414. * {
  74415. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74416. * edge_blur: number; // from 0 to x (1 for realism)
  74417. * distortion: number; // from 0 to x (1 for realism)
  74418. * grain_amount: number; // from 0 to 1
  74419. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74420. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74421. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74422. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74423. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74424. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74425. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74426. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74427. * }
  74428. * Note: if an effect parameter is unset, effect is disabled
  74429. *
  74430. * @param {string} name - The rendering pipeline name
  74431. * @param {object} parameters - An object containing all parameters (see above)
  74432. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74433. * @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)
  74434. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74435. */
  74436. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74437. if (ratio === void 0) { ratio = 1.0; }
  74438. var _this = _super.call(this, scene.getEngine(), name) || this;
  74439. // Lens effects can be of the following:
  74440. // - chromatic aberration (slight shift of RGB colors)
  74441. // - blur on the edge of the lens
  74442. // - lens distortion
  74443. // - depth-of-field blur & highlights enhancing
  74444. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74445. // - grain effect (noise or custom texture)
  74446. // Two additional texture samplers are needed:
  74447. // - depth map (for depth-of-field)
  74448. // - grain texture
  74449. /**
  74450. * The chromatic aberration PostProcess id in the pipeline
  74451. */
  74452. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74453. /**
  74454. * The highlights enhancing PostProcess id in the pipeline
  74455. */
  74456. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74457. /**
  74458. * The depth-of-field PostProcess id in the pipeline
  74459. */
  74460. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74461. _this._scene = scene;
  74462. // Fetch texture samplers
  74463. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74464. if (parameters.grain_texture) {
  74465. _this._grainTexture = parameters.grain_texture;
  74466. }
  74467. else {
  74468. _this._createGrainTexture();
  74469. }
  74470. // save parameters
  74471. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74472. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74473. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74474. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74475. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74476. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74477. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74478. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74479. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74480. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74481. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74482. // Create effects
  74483. _this._createChromaticAberrationPostProcess(ratio);
  74484. _this._createHighlightsPostProcess(ratio);
  74485. _this._createDepthOfFieldPostProcess(ratio / 4);
  74486. // Set up pipeline
  74487. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74488. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74489. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74490. if (_this._highlightsGain === -1) {
  74491. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74492. }
  74493. // Finish
  74494. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74495. if (cameras) {
  74496. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74497. }
  74498. return _this;
  74499. }
  74500. // public methods (self explanatory)
  74501. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74502. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74503. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74504. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74505. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74506. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74507. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74508. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74509. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74510. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74511. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74512. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74513. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74514. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74515. };
  74516. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74517. this._highlightsPostProcess.updateEffect();
  74518. };
  74519. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74520. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74521. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74522. this._highlightsGain = amount;
  74523. };
  74524. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74525. if (this._highlightsGain === -1) {
  74526. this._highlightsGain = 1.0;
  74527. }
  74528. this._highlightsThreshold = amount;
  74529. };
  74530. LensRenderingPipeline.prototype.disableHighlights = function () {
  74531. this._highlightsGain = -1;
  74532. };
  74533. /**
  74534. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74535. */
  74536. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74537. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74538. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74539. this._chromaticAberrationPostProcess = null;
  74540. this._highlightsPostProcess = null;
  74541. this._depthOfFieldPostProcess = null;
  74542. this._grainTexture.dispose();
  74543. if (disableDepthRender)
  74544. this._scene.disableDepthRenderer();
  74545. };
  74546. // colors shifting and distortion
  74547. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74548. var _this = this;
  74549. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74550. [], // samplers
  74551. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74552. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74553. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74554. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74555. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74556. effect.setFloat('radialIntensity', 1);
  74557. effect.setFloat2('direction', 17, 17);
  74558. effect.setFloat2('centerPosition', 0.5, 0.5);
  74559. };
  74560. };
  74561. // highlights enhancing
  74562. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74563. var _this = this;
  74564. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74565. [], // samplers
  74566. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74567. this._highlightsPostProcess.onApply = function (effect) {
  74568. effect.setFloat('gain', _this._highlightsGain);
  74569. effect.setFloat('threshold', _this._highlightsThreshold);
  74570. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74571. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74572. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74573. };
  74574. };
  74575. // colors shifting and distortion
  74576. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74577. var _this = this;
  74578. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74579. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74580. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74581. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74582. this._depthOfFieldPostProcess.onApply = function (effect) {
  74583. effect.setTexture("depthSampler", _this._depthTexture);
  74584. effect.setTexture("grainSampler", _this._grainTexture);
  74585. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74586. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74587. effect.setFloat('grain_amount', _this._grainAmount);
  74588. effect.setBool('blur_noise', _this._blurNoise);
  74589. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74590. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74591. effect.setFloat('distortion', _this._distortion);
  74592. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74593. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74594. effect.setFloat('aperture', _this._dofAperture);
  74595. effect.setFloat('darken', _this._dofDarken);
  74596. effect.setFloat('edge_blur', _this._edgeBlur);
  74597. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74598. if (_this._scene.activeCamera) {
  74599. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74600. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74601. }
  74602. };
  74603. };
  74604. // creates a black and white random noise texture, 512x512
  74605. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74606. var size = 512;
  74607. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74608. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74609. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74610. var context = this._grainTexture.getContext();
  74611. var rand = function (min, max) {
  74612. return Math.random() * (max - min) + min;
  74613. };
  74614. var value;
  74615. for (var x = 0; x < size; x++) {
  74616. for (var y = 0; y < size; y++) {
  74617. value = Math.floor(rand(0.42, 0.58) * 255);
  74618. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74619. context.fillRect(x, y, 1, 1);
  74620. }
  74621. }
  74622. this._grainTexture.update(false);
  74623. };
  74624. return LensRenderingPipeline;
  74625. }(BABYLON.PostProcessRenderPipeline));
  74626. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74627. })(BABYLON || (BABYLON = {}));
  74628. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74629. var BABYLON;
  74630. (function (BABYLON) {
  74631. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74632. __extends(StandardRenderingPipeline, _super);
  74633. /**
  74634. * @constructor
  74635. * @param {string} name - The rendering pipeline name
  74636. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74637. * @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)
  74638. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74639. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74640. */
  74641. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74642. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74643. var _this = _super.call(this, scene.getEngine(), name) || this;
  74644. _this.downSampleX4PostProcess = null;
  74645. _this.brightPassPostProcess = null;
  74646. _this.blurHPostProcesses = [];
  74647. _this.blurVPostProcesses = [];
  74648. _this.textureAdderPostProcess = null;
  74649. _this.volumetricLightPostProcess = null;
  74650. _this.volumetricLightSmoothXPostProcess = null;
  74651. _this.volumetricLightSmoothYPostProcess = null;
  74652. _this.volumetricLightMergePostProces = null;
  74653. _this.volumetricLightFinalPostProcess = null;
  74654. _this.luminancePostProcess = null;
  74655. _this.luminanceDownSamplePostProcesses = [];
  74656. _this.hdrPostProcess = null;
  74657. _this.textureAdderFinalPostProcess = null;
  74658. _this.lensFlareFinalPostProcess = null;
  74659. _this.hdrFinalPostProcess = null;
  74660. _this.lensFlarePostProcess = null;
  74661. _this.lensFlareComposePostProcess = null;
  74662. _this.motionBlurPostProcess = null;
  74663. _this.depthOfFieldPostProcess = null;
  74664. // Values
  74665. _this.brightThreshold = 1.0;
  74666. _this.blurWidth = 512.0;
  74667. _this.horizontalBlur = false;
  74668. _this.exposure = 1.0;
  74669. _this.lensTexture = null;
  74670. _this.volumetricLightCoefficient = 0.2;
  74671. _this.volumetricLightPower = 4.0;
  74672. _this.volumetricLightBlurScale = 64.0;
  74673. _this.sourceLight = null;
  74674. _this.hdrMinimumLuminance = 1.0;
  74675. _this.hdrDecreaseRate = 0.5;
  74676. _this.hdrIncreaseRate = 0.5;
  74677. _this.lensColorTexture = null;
  74678. _this.lensFlareStrength = 20.0;
  74679. _this.lensFlareGhostDispersal = 1.4;
  74680. _this.lensFlareHaloWidth = 0.7;
  74681. _this.lensFlareDistortionStrength = 16.0;
  74682. _this.lensStarTexture = null;
  74683. _this.lensFlareDirtTexture = null;
  74684. _this.depthOfFieldDistance = 10.0;
  74685. _this.depthOfFieldBlurWidth = 64.0;
  74686. _this.motionStrength = 1.0;
  74687. // IAnimatable
  74688. _this.animations = [];
  74689. _this._currentDepthOfFieldSource = null;
  74690. _this._hdrCurrentLuminance = 1.0;
  74691. // Getters and setters
  74692. _this._bloomEnabled = true;
  74693. _this._depthOfFieldEnabled = false;
  74694. _this._vlsEnabled = false;
  74695. _this._lensFlareEnabled = false;
  74696. _this._hdrEnabled = false;
  74697. _this._motionBlurEnabled = false;
  74698. _this._motionBlurSamples = 64.0;
  74699. _this._volumetricLightStepsCount = 50.0;
  74700. _this._cameras = cameras || [];
  74701. // Initialize
  74702. _this._scene = scene;
  74703. _this._basePostProcess = originalPostProcess;
  74704. _this._ratio = ratio;
  74705. // Misc
  74706. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74707. // Finish
  74708. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74709. _this._buildPipeline();
  74710. return _this;
  74711. }
  74712. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74713. get: function () {
  74714. return this._bloomEnabled;
  74715. },
  74716. set: function (enabled) {
  74717. if (this._bloomEnabled === enabled) {
  74718. return;
  74719. }
  74720. this._bloomEnabled = enabled;
  74721. this._buildPipeline();
  74722. },
  74723. enumerable: true,
  74724. configurable: true
  74725. });
  74726. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74727. get: function () {
  74728. return this._depthOfFieldEnabled;
  74729. },
  74730. set: function (enabled) {
  74731. if (this._depthOfFieldEnabled === enabled) {
  74732. return;
  74733. }
  74734. this._depthOfFieldEnabled = enabled;
  74735. this._buildPipeline();
  74736. },
  74737. enumerable: true,
  74738. configurable: true
  74739. });
  74740. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74741. get: function () {
  74742. return this._lensFlareEnabled;
  74743. },
  74744. set: function (enabled) {
  74745. if (this._lensFlareEnabled === enabled) {
  74746. return;
  74747. }
  74748. this._lensFlareEnabled = enabled;
  74749. this._buildPipeline();
  74750. },
  74751. enumerable: true,
  74752. configurable: true
  74753. });
  74754. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74755. get: function () {
  74756. return this._hdrEnabled;
  74757. },
  74758. set: function (enabled) {
  74759. if (this._hdrEnabled === enabled) {
  74760. return;
  74761. }
  74762. this._hdrEnabled = enabled;
  74763. this._buildPipeline();
  74764. },
  74765. enumerable: true,
  74766. configurable: true
  74767. });
  74768. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74769. get: function () {
  74770. return this._vlsEnabled;
  74771. },
  74772. set: function (enabled) {
  74773. if (this._vlsEnabled === enabled) {
  74774. return;
  74775. }
  74776. if (enabled) {
  74777. var geometry = this._scene.enableGeometryBufferRenderer();
  74778. if (!geometry) {
  74779. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74780. return;
  74781. }
  74782. }
  74783. this._vlsEnabled = enabled;
  74784. this._buildPipeline();
  74785. },
  74786. enumerable: true,
  74787. configurable: true
  74788. });
  74789. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74790. get: function () {
  74791. return this._motionBlurEnabled;
  74792. },
  74793. set: function (enabled) {
  74794. if (this._motionBlurEnabled === enabled) {
  74795. return;
  74796. }
  74797. this._motionBlurEnabled = enabled;
  74798. this._buildPipeline();
  74799. },
  74800. enumerable: true,
  74801. configurable: true
  74802. });
  74803. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74804. get: function () {
  74805. return this._volumetricLightStepsCount;
  74806. },
  74807. set: function (count) {
  74808. if (this.volumetricLightPostProcess) {
  74809. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74810. }
  74811. this._volumetricLightStepsCount = count;
  74812. },
  74813. enumerable: true,
  74814. configurable: true
  74815. });
  74816. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74817. get: function () {
  74818. return this._motionBlurSamples;
  74819. },
  74820. set: function (samples) {
  74821. if (this.motionBlurPostProcess) {
  74822. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74823. }
  74824. this._motionBlurSamples = samples;
  74825. },
  74826. enumerable: true,
  74827. configurable: true
  74828. });
  74829. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74830. var _this = this;
  74831. var ratio = this._ratio;
  74832. var scene = this._scene;
  74833. this._disposePostProcesses();
  74834. this._reset();
  74835. // Create pass post-process
  74836. if (!this._basePostProcess) {
  74837. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74838. this.originalPostProcess.onApply = function (effect) {
  74839. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74840. };
  74841. }
  74842. else {
  74843. this.originalPostProcess = this._basePostProcess;
  74844. }
  74845. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74846. this._currentDepthOfFieldSource = this.originalPostProcess;
  74847. if (this._bloomEnabled) {
  74848. // Create down sample X4 post-process
  74849. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74850. // Create bright pass post-process
  74851. this._createBrightPassPostProcess(scene, ratio / 2);
  74852. // Create gaussian blur post-processes (down sampling blurs)
  74853. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74854. // Create texture adder post-process
  74855. this._createTextureAdderPostProcess(scene, ratio);
  74856. // Create depth-of-field source post-process
  74857. 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);
  74858. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74859. }
  74860. if (this._vlsEnabled) {
  74861. // Create volumetric light
  74862. this._createVolumetricLightPostProcess(scene, ratio);
  74863. // Create volumetric light final post-process
  74864. 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);
  74865. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74866. }
  74867. if (this._lensFlareEnabled) {
  74868. // Create lens flare post-process
  74869. this._createLensFlarePostProcess(scene, ratio);
  74870. // Create depth-of-field source post-process post lens-flare and disable it now
  74871. 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);
  74872. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74873. }
  74874. if (this._hdrEnabled) {
  74875. // Create luminance
  74876. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74877. // Create HDR
  74878. this._createHdrPostProcess(scene, ratio);
  74879. // Create depth-of-field source post-process post hdr and disable it now
  74880. 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);
  74881. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74882. }
  74883. if (this._depthOfFieldEnabled) {
  74884. // Create gaussian blur used by depth-of-field
  74885. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74886. // Create depth-of-field post-process
  74887. this._createDepthOfFieldPostProcess(scene, ratio);
  74888. }
  74889. if (this._motionBlurEnabled) {
  74890. // Create motion blur post-process
  74891. this._createMotionBlurPostProcess(scene, ratio);
  74892. }
  74893. if (this._cameras !== null) {
  74894. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74895. }
  74896. };
  74897. // Down Sample X4 Post-Processs
  74898. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74899. var _this = this;
  74900. var downSampleX4Offsets = new Array(32);
  74901. 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);
  74902. this.downSampleX4PostProcess.onApply = function (effect) {
  74903. var id = 0;
  74904. var width = _this.downSampleX4PostProcess.width;
  74905. var height = _this.downSampleX4PostProcess.height;
  74906. for (var i = -2; i < 2; i++) {
  74907. for (var j = -2; j < 2; j++) {
  74908. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74909. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74910. id += 2;
  74911. }
  74912. }
  74913. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74914. };
  74915. // Add to pipeline
  74916. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74917. };
  74918. // Brightpass Post-Process
  74919. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74920. var _this = this;
  74921. var brightOffsets = new Array(8);
  74922. 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);
  74923. this.brightPassPostProcess.onApply = function (effect) {
  74924. var sU = (1.0 / _this.brightPassPostProcess.width);
  74925. var sV = (1.0 / _this.brightPassPostProcess.height);
  74926. brightOffsets[0] = -0.5 * sU;
  74927. brightOffsets[1] = 0.5 * sV;
  74928. brightOffsets[2] = 0.5 * sU;
  74929. brightOffsets[3] = 0.5 * sV;
  74930. brightOffsets[4] = -0.5 * sU;
  74931. brightOffsets[5] = -0.5 * sV;
  74932. brightOffsets[6] = 0.5 * sU;
  74933. brightOffsets[7] = -0.5 * sV;
  74934. effect.setArray2("dsOffsets", brightOffsets);
  74935. effect.setFloat("brightThreshold", _this.brightThreshold);
  74936. };
  74937. // Add to pipeline
  74938. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74939. };
  74940. // Create blur H&V post-processes
  74941. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74942. var _this = this;
  74943. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74944. var engine = scene.getEngine();
  74945. 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);
  74946. 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);
  74947. blurX.onActivateObservable.add(function () {
  74948. var dw = blurX.width / engine.getRenderWidth();
  74949. blurX.kernel = _this[blurWidthKey] * dw;
  74950. });
  74951. blurY.onActivateObservable.add(function () {
  74952. var dw = blurY.height / engine.getRenderHeight();
  74953. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74954. });
  74955. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74956. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74957. this.blurHPostProcesses.push(blurX);
  74958. this.blurVPostProcesses.push(blurY);
  74959. };
  74960. // Create texture adder post-process
  74961. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74962. var _this = this;
  74963. 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);
  74964. this.textureAdderPostProcess.onApply = function (effect) {
  74965. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74966. effect.setTexture("lensSampler", _this.lensTexture);
  74967. effect.setFloat("exposure", _this.exposure);
  74968. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74969. };
  74970. // Add to pipeline
  74971. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74972. };
  74973. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74974. var _this = this;
  74975. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74976. geometryRenderer.enablePosition = true;
  74977. var geometry = geometryRenderer.getGBuffer();
  74978. // Base post-process
  74979. 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));
  74980. var depthValues = BABYLON.Vector2.Zero();
  74981. this.volumetricLightPostProcess.onApply = function (effect) {
  74982. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74983. var generator = _this.sourceLight.getShadowGenerator();
  74984. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74985. effect.setTexture("positionSampler", geometry.textures[2]);
  74986. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74987. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74988. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74989. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74990. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74991. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74992. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74993. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74994. effect.setVector2("depthValues", depthValues);
  74995. }
  74996. };
  74997. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74998. // Smooth
  74999. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  75000. // Merge
  75001. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  75002. this.volumetricLightMergePostProces.onApply = function (effect) {
  75003. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  75004. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  75005. };
  75006. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  75007. };
  75008. // Create luminance
  75009. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  75010. var _this = this;
  75011. // Create luminance
  75012. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  75013. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  75014. var offsets = [];
  75015. this.luminancePostProcess.onApply = function (effect) {
  75016. var sU = (1.0 / _this.luminancePostProcess.width);
  75017. var sV = (1.0 / _this.luminancePostProcess.height);
  75018. offsets[0] = -0.5 * sU;
  75019. offsets[1] = 0.5 * sV;
  75020. offsets[2] = 0.5 * sU;
  75021. offsets[3] = 0.5 * sV;
  75022. offsets[4] = -0.5 * sU;
  75023. offsets[5] = -0.5 * sV;
  75024. offsets[6] = 0.5 * sU;
  75025. offsets[7] = -0.5 * sV;
  75026. effect.setArray2("lumOffsets", offsets);
  75027. };
  75028. // Add to pipeline
  75029. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  75030. // Create down sample luminance
  75031. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  75032. var size = Math.pow(3, i);
  75033. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  75034. if (i === 0) {
  75035. defines += "#define FINAL_DOWN_SAMPLER";
  75036. }
  75037. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  75038. this.luminanceDownSamplePostProcesses.push(postProcess);
  75039. }
  75040. // Create callbacks and add effects
  75041. var lastLuminance = this.luminancePostProcess;
  75042. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  75043. var downSampleOffsets = new Array(18);
  75044. pp.onApply = function (effect) {
  75045. if (!lastLuminance) {
  75046. return;
  75047. }
  75048. var id = 0;
  75049. for (var x = -1; x < 2; x++) {
  75050. for (var y = -1; y < 2; y++) {
  75051. downSampleOffsets[id] = x / lastLuminance.width;
  75052. downSampleOffsets[id + 1] = y / lastLuminance.height;
  75053. id += 2;
  75054. }
  75055. }
  75056. effect.setArray2("dsOffsets", downSampleOffsets);
  75057. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  75058. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  75059. lastLuminance = _this.luminancePostProcess;
  75060. }
  75061. else {
  75062. lastLuminance = pp;
  75063. }
  75064. };
  75065. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  75066. pp.onAfterRender = function (effect) {
  75067. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  75068. 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);
  75069. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  75070. };
  75071. }
  75072. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  75073. });
  75074. };
  75075. // Create HDR post-process
  75076. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  75077. var _this = this;
  75078. 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);
  75079. var outputLiminance = 1;
  75080. var time = 0;
  75081. var lastTime = 0;
  75082. this.hdrPostProcess.onApply = function (effect) {
  75083. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  75084. time += scene.getEngine().getDeltaTime();
  75085. if (outputLiminance < 0) {
  75086. outputLiminance = _this._hdrCurrentLuminance;
  75087. }
  75088. else {
  75089. var dt = (lastTime - time) / 1000.0;
  75090. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  75091. outputLiminance += _this.hdrDecreaseRate * dt;
  75092. }
  75093. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  75094. outputLiminance -= _this.hdrIncreaseRate * dt;
  75095. }
  75096. else {
  75097. outputLiminance = _this._hdrCurrentLuminance;
  75098. }
  75099. }
  75100. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  75101. effect.setFloat("averageLuminance", outputLiminance);
  75102. lastTime = time;
  75103. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  75104. };
  75105. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  75106. };
  75107. // Create lens flare post-process
  75108. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  75109. var _this = this;
  75110. 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);
  75111. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  75112. this._createBlurPostProcesses(scene, ratio / 4, 2);
  75113. 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);
  75114. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  75115. var resolution = new BABYLON.Vector2(0, 0);
  75116. // Lens flare
  75117. this.lensFlarePostProcess.onApply = function (effect) {
  75118. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  75119. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  75120. effect.setFloat("strength", _this.lensFlareStrength);
  75121. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  75122. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  75123. // Shift
  75124. resolution.x = _this.lensFlarePostProcess.width;
  75125. resolution.y = _this.lensFlarePostProcess.height;
  75126. effect.setVector2("resolution", resolution);
  75127. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  75128. };
  75129. // Compose
  75130. 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);
  75131. 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);
  75132. this.lensFlareComposePostProcess.onApply = function (effect) {
  75133. if (!_this._scene.activeCamera) {
  75134. return;
  75135. }
  75136. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  75137. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  75138. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  75139. // Lens start rotation matrix
  75140. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  75141. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  75142. 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));
  75143. camRot *= 4.0;
  75144. 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);
  75145. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  75146. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  75147. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  75148. };
  75149. };
  75150. // Create depth-of-field post-process
  75151. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  75152. var _this = this;
  75153. 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);
  75154. this.depthOfFieldPostProcess.onApply = function (effect) {
  75155. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  75156. effect.setTexture("depthSampler", _this._getDepthTexture());
  75157. effect.setFloat("distance", _this.depthOfFieldDistance);
  75158. };
  75159. // Add to pipeline
  75160. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  75161. };
  75162. // Create motion blur post-process
  75163. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  75164. var _this = this;
  75165. 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);
  75166. var motionScale = 0;
  75167. var prevViewProjection = BABYLON.Matrix.Identity();
  75168. var invViewProjection = BABYLON.Matrix.Identity();
  75169. var viewProjection = BABYLON.Matrix.Identity();
  75170. var screenSize = BABYLON.Vector2.Zero();
  75171. this.motionBlurPostProcess.onApply = function (effect) {
  75172. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  75173. viewProjection.invertToRef(invViewProjection);
  75174. effect.setMatrix("inverseViewProjection", invViewProjection);
  75175. effect.setMatrix("prevViewProjection", prevViewProjection);
  75176. prevViewProjection = viewProjection;
  75177. screenSize.x = _this.motionBlurPostProcess.width;
  75178. screenSize.y = _this.motionBlurPostProcess.height;
  75179. effect.setVector2("screenSize", screenSize);
  75180. motionScale = scene.getEngine().getFps() / 60.0;
  75181. effect.setFloat("motionScale", motionScale);
  75182. effect.setFloat("motionStrength", _this.motionStrength);
  75183. effect.setTexture("depthSampler", _this._getDepthTexture());
  75184. };
  75185. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  75186. };
  75187. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  75188. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  75189. var renderer = this._scene.enableGeometryBufferRenderer();
  75190. return renderer.getGBuffer().textures[0];
  75191. }
  75192. return this._scene.enableDepthRenderer().getDepthMap();
  75193. };
  75194. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  75195. for (var i = 0; i < this._cameras.length; i++) {
  75196. var camera = this._cameras[i];
  75197. if (this.originalPostProcess) {
  75198. this.originalPostProcess.dispose(camera);
  75199. }
  75200. if (this.downSampleX4PostProcess) {
  75201. this.downSampleX4PostProcess.dispose(camera);
  75202. }
  75203. if (this.brightPassPostProcess) {
  75204. this.brightPassPostProcess.dispose(camera);
  75205. }
  75206. if (this.textureAdderPostProcess) {
  75207. this.textureAdderPostProcess.dispose(camera);
  75208. }
  75209. if (this.textureAdderFinalPostProcess) {
  75210. this.textureAdderFinalPostProcess.dispose(camera);
  75211. }
  75212. if (this.volumetricLightPostProcess) {
  75213. this.volumetricLightPostProcess.dispose(camera);
  75214. }
  75215. if (this.volumetricLightSmoothXPostProcess) {
  75216. this.volumetricLightSmoothXPostProcess.dispose(camera);
  75217. }
  75218. if (this.volumetricLightSmoothYPostProcess) {
  75219. this.volumetricLightSmoothYPostProcess.dispose(camera);
  75220. }
  75221. if (this.volumetricLightMergePostProces) {
  75222. this.volumetricLightMergePostProces.dispose(camera);
  75223. }
  75224. if (this.volumetricLightFinalPostProcess) {
  75225. this.volumetricLightFinalPostProcess.dispose(camera);
  75226. }
  75227. if (this.lensFlarePostProcess) {
  75228. this.lensFlarePostProcess.dispose(camera);
  75229. }
  75230. if (this.lensFlareComposePostProcess) {
  75231. this.lensFlareComposePostProcess.dispose(camera);
  75232. }
  75233. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  75234. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  75235. }
  75236. if (this.luminancePostProcess) {
  75237. this.luminancePostProcess.dispose(camera);
  75238. }
  75239. if (this.hdrPostProcess) {
  75240. this.hdrPostProcess.dispose(camera);
  75241. }
  75242. if (this.hdrFinalPostProcess) {
  75243. this.hdrFinalPostProcess.dispose(camera);
  75244. }
  75245. if (this.depthOfFieldPostProcess) {
  75246. this.depthOfFieldPostProcess.dispose(camera);
  75247. }
  75248. if (this.motionBlurPostProcess) {
  75249. this.motionBlurPostProcess.dispose(camera);
  75250. }
  75251. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  75252. this.blurHPostProcesses[j].dispose(camera);
  75253. }
  75254. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  75255. this.blurVPostProcesses[j].dispose(camera);
  75256. }
  75257. }
  75258. this.originalPostProcess = null;
  75259. this.downSampleX4PostProcess = null;
  75260. this.brightPassPostProcess = null;
  75261. this.textureAdderPostProcess = null;
  75262. this.textureAdderFinalPostProcess = null;
  75263. this.volumetricLightPostProcess = null;
  75264. this.volumetricLightSmoothXPostProcess = null;
  75265. this.volumetricLightSmoothYPostProcess = null;
  75266. this.volumetricLightMergePostProces = null;
  75267. this.volumetricLightFinalPostProcess = null;
  75268. this.lensFlarePostProcess = null;
  75269. this.lensFlareComposePostProcess = null;
  75270. this.luminancePostProcess = null;
  75271. this.hdrPostProcess = null;
  75272. this.hdrFinalPostProcess = null;
  75273. this.depthOfFieldPostProcess = null;
  75274. this.motionBlurPostProcess = null;
  75275. this.luminanceDownSamplePostProcesses = [];
  75276. this.blurHPostProcesses = [];
  75277. this.blurVPostProcesses = [];
  75278. };
  75279. /**
  75280. * Dispose of the pipeline and stop all post processes
  75281. */
  75282. StandardRenderingPipeline.prototype.dispose = function () {
  75283. this._disposePostProcesses();
  75284. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75285. _super.prototype.dispose.call(this);
  75286. };
  75287. /**
  75288. * Serialize the rendering pipeline (Used when exporting)
  75289. * @returns the serialized object
  75290. */
  75291. StandardRenderingPipeline.prototype.serialize = function () {
  75292. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75293. if (this.sourceLight) {
  75294. serializationObject.sourceLightId = this.sourceLight.id;
  75295. }
  75296. serializationObject.customType = "StandardRenderingPipeline";
  75297. return serializationObject;
  75298. };
  75299. /**
  75300. * Parse the serialized pipeline
  75301. * @param source Source pipeline.
  75302. * @param scene The scene to load the pipeline to.
  75303. * @param rootUrl The URL of the serialized pipeline.
  75304. * @returns An instantiated pipeline from the serialized object.
  75305. */
  75306. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75307. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75308. if (source.sourceLightId) {
  75309. p.sourceLight = scene.getLightByID(source.sourceLightId);
  75310. }
  75311. return p;
  75312. };
  75313. // Luminance steps
  75314. StandardRenderingPipeline.LuminanceSteps = 6;
  75315. __decorate([
  75316. BABYLON.serialize()
  75317. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  75318. __decorate([
  75319. BABYLON.serialize()
  75320. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  75321. __decorate([
  75322. BABYLON.serialize()
  75323. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  75324. __decorate([
  75325. BABYLON.serialize()
  75326. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  75327. __decorate([
  75328. BABYLON.serializeAsTexture("lensTexture")
  75329. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  75330. __decorate([
  75331. BABYLON.serialize()
  75332. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  75333. __decorate([
  75334. BABYLON.serialize()
  75335. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  75336. __decorate([
  75337. BABYLON.serialize()
  75338. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  75339. __decorate([
  75340. BABYLON.serialize()
  75341. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  75342. __decorate([
  75343. BABYLON.serialize()
  75344. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  75345. __decorate([
  75346. BABYLON.serialize()
  75347. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  75348. __decorate([
  75349. BABYLON.serializeAsTexture("lensColorTexture")
  75350. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  75351. __decorate([
  75352. BABYLON.serialize()
  75353. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  75354. __decorate([
  75355. BABYLON.serialize()
  75356. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  75357. __decorate([
  75358. BABYLON.serialize()
  75359. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  75360. __decorate([
  75361. BABYLON.serialize()
  75362. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  75363. __decorate([
  75364. BABYLON.serializeAsTexture("lensStarTexture")
  75365. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  75366. __decorate([
  75367. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  75368. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  75369. __decorate([
  75370. BABYLON.serialize()
  75371. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  75372. __decorate([
  75373. BABYLON.serialize()
  75374. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  75375. __decorate([
  75376. BABYLON.serialize()
  75377. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  75378. __decorate([
  75379. BABYLON.serialize()
  75380. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  75381. __decorate([
  75382. BABYLON.serialize()
  75383. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75384. __decorate([
  75385. BABYLON.serialize()
  75386. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75387. __decorate([
  75388. BABYLON.serialize()
  75389. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75390. __decorate([
  75391. BABYLON.serialize()
  75392. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75393. __decorate([
  75394. BABYLON.serialize()
  75395. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75396. __decorate([
  75397. BABYLON.serialize()
  75398. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75399. __decorate([
  75400. BABYLON.serialize()
  75401. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75402. __decorate([
  75403. BABYLON.serialize()
  75404. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75405. return StandardRenderingPipeline;
  75406. }(BABYLON.PostProcessRenderPipeline));
  75407. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75408. })(BABYLON || (BABYLON = {}));
  75409. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75410. var BABYLON;
  75411. (function (BABYLON) {
  75412. var FxaaPostProcess = /** @class */ (function (_super) {
  75413. __extends(FxaaPostProcess, _super);
  75414. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75415. if (camera === void 0) { camera = null; }
  75416. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75417. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75418. var defines = _this._getDefines();
  75419. _this.updateEffect(defines);
  75420. _this.onApplyObservable.add(function (effect) {
  75421. var texelSize = _this.texelSize;
  75422. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75423. });
  75424. return _this;
  75425. }
  75426. FxaaPostProcess.prototype._getDefines = function () {
  75427. var engine = this.getEngine();
  75428. if (!engine) {
  75429. return null;
  75430. }
  75431. var glInfo = engine.getGlInfo();
  75432. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75433. return "#define MALI 1\n";
  75434. }
  75435. return null;
  75436. };
  75437. return FxaaPostProcess;
  75438. }(BABYLON.PostProcess));
  75439. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75440. })(BABYLON || (BABYLON = {}));
  75441. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75442. var BABYLON;
  75443. (function (BABYLON) {
  75444. /**
  75445. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75446. */
  75447. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75448. __extends(ChromaticAberrationPostProcess, _super);
  75449. /**
  75450. * Creates a new instance ChromaticAberrationPostProcess
  75451. * @param name The name of the effect.
  75452. * @param screenWidth The width of the screen to apply the effect on.
  75453. * @param screenHeight The height of the screen to apply the effect on.
  75454. * @param options The required width/height ratio to downsize to before computing the render pass.
  75455. * @param camera The camera to apply the render pass to.
  75456. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75457. * @param engine The engine which the post process will be applied. (default: current engine)
  75458. * @param reusable If the post process can be reused on the same frame. (default: false)
  75459. * @param textureType Type of textures used when performing the post process. (default: 0)
  75460. * @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)
  75461. */
  75462. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75463. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75464. if (blockCompilation === void 0) { blockCompilation = false; }
  75465. 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;
  75466. /**
  75467. * The amount of seperation of rgb channels (default: 30)
  75468. */
  75469. _this.aberrationAmount = 30;
  75470. /**
  75471. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75472. */
  75473. _this.radialIntensity = 0;
  75474. /**
  75475. * 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))
  75476. */
  75477. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75478. /**
  75479. * 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))
  75480. */
  75481. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75482. _this.onApplyObservable.add(function (effect) {
  75483. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75484. effect.setFloat('screen_width', screenWidth);
  75485. effect.setFloat('screen_height', screenHeight);
  75486. effect.setFloat('radialIntensity', _this.radialIntensity);
  75487. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75488. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75489. });
  75490. return _this;
  75491. }
  75492. return ChromaticAberrationPostProcess;
  75493. }(BABYLON.PostProcess));
  75494. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75495. })(BABYLON || (BABYLON = {}));
  75496. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75497. var BABYLON;
  75498. (function (BABYLON) {
  75499. /**
  75500. * The GrainPostProcess adds noise to the image at mid luminance levels
  75501. */
  75502. var GrainPostProcess = /** @class */ (function (_super) {
  75503. __extends(GrainPostProcess, _super);
  75504. /**
  75505. * Creates a new instance of @see GrainPostProcess
  75506. * @param name The name of the effect.
  75507. * @param options The required width/height ratio to downsize to before computing the render pass.
  75508. * @param camera The camera to apply the render pass to.
  75509. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75510. * @param engine The engine which the post process will be applied. (default: current engine)
  75511. * @param reusable If the post process can be reused on the same frame. (default: false)
  75512. * @param textureType Type of textures used when performing the post process. (default: 0)
  75513. * @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)
  75514. */
  75515. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75516. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75517. if (blockCompilation === void 0) { blockCompilation = false; }
  75518. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75519. /**
  75520. * The intensity of the grain added (default: 30)
  75521. */
  75522. _this.intensity = 30;
  75523. /**
  75524. * If the grain should be randomized on every frame
  75525. */
  75526. _this.animated = false;
  75527. _this.onApplyObservable.add(function (effect) {
  75528. effect.setFloat('intensity', _this.intensity);
  75529. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75530. });
  75531. return _this;
  75532. }
  75533. return GrainPostProcess;
  75534. }(BABYLON.PostProcess));
  75535. BABYLON.GrainPostProcess = GrainPostProcess;
  75536. })(BABYLON || (BABYLON = {}));
  75537. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75538. var BABYLON;
  75539. (function (BABYLON) {
  75540. /**
  75541. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75542. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75543. */
  75544. var SharpenPostProcess = /** @class */ (function (_super) {
  75545. __extends(SharpenPostProcess, _super);
  75546. /**
  75547. * Creates a new instance ConvolutionPostProcess
  75548. * @param name The name of the effect.
  75549. * @param options The required width/height ratio to downsize to before computing the render pass.
  75550. * @param camera The camera to apply the render pass to.
  75551. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75552. * @param engine The engine which the post process will be applied. (default: current engine)
  75553. * @param reusable If the post process can be reused on the same frame. (default: false)
  75554. * @param textureType Type of textures used when performing the post process. (default: 0)
  75555. * @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)
  75556. */
  75557. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75558. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75559. if (blockCompilation === void 0) { blockCompilation = false; }
  75560. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75561. /**
  75562. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75563. */
  75564. _this.colorAmount = 1.0;
  75565. /**
  75566. * How much sharpness should be applied (default: 0.3)
  75567. */
  75568. _this.edgeAmount = 0.3;
  75569. _this.onApply = function (effect) {
  75570. effect.setFloat2("screenSize", _this.width, _this.height);
  75571. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75572. };
  75573. return _this;
  75574. }
  75575. return SharpenPostProcess;
  75576. }(BABYLON.PostProcess));
  75577. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75578. })(BABYLON || (BABYLON = {}));
  75579. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75580. var BABYLON;
  75581. (function (BABYLON) {
  75582. /**
  75583. * The Blur Post Process which blurs an image based on a kernel and direction.
  75584. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75585. */
  75586. var BlurPostProcess = /** @class */ (function (_super) {
  75587. __extends(BlurPostProcess, _super);
  75588. /**
  75589. * Creates a new instance BlurPostProcess
  75590. * @param name The name of the effect.
  75591. * @param direction The direction in which to blur the image.
  75592. * @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.
  75593. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75594. * @param camera The camera to apply the render pass to.
  75595. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75596. * @param engine The engine which the post process will be applied. (default: current engine)
  75597. * @param reusable If the post process can be reused on the same frame. (default: false)
  75598. * @param textureType Type of textures used when performing the post process. (default: 0)
  75599. * @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)
  75600. */
  75601. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75602. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75603. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75604. if (defines === void 0) { defines = ""; }
  75605. if (blockCompilation === void 0) { blockCompilation = false; }
  75606. 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;
  75607. _this.direction = direction;
  75608. _this.blockCompilation = blockCompilation;
  75609. _this._packedFloat = false;
  75610. _this._staticDefines = "";
  75611. _this._staticDefines = defines;
  75612. _this.onApplyObservable.add(function (effect) {
  75613. if (_this._outputTexture) {
  75614. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75615. }
  75616. else {
  75617. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75618. }
  75619. });
  75620. _this.kernel = kernel;
  75621. return _this;
  75622. }
  75623. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75624. /**
  75625. * Gets the length in pixels of the blur sample region
  75626. */
  75627. get: function () {
  75628. return this._idealKernel;
  75629. },
  75630. /**
  75631. * Sets the length in pixels of the blur sample region
  75632. */
  75633. set: function (v) {
  75634. if (this._idealKernel === v) {
  75635. return;
  75636. }
  75637. v = Math.max(v, 1);
  75638. this._idealKernel = v;
  75639. this._kernel = this._nearestBestKernel(v);
  75640. if (!this.blockCompilation) {
  75641. this._updateParameters();
  75642. }
  75643. },
  75644. enumerable: true,
  75645. configurable: true
  75646. });
  75647. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75648. /**
  75649. * Gets wether or not the blur is unpacking/repacking floats
  75650. */
  75651. get: function () {
  75652. return this._packedFloat;
  75653. },
  75654. /**
  75655. * Sets wether or not the blur needs to unpack/repack floats
  75656. */
  75657. set: function (v) {
  75658. if (this._packedFloat === v) {
  75659. return;
  75660. }
  75661. this._packedFloat = v;
  75662. if (!this.blockCompilation) {
  75663. this._updateParameters();
  75664. }
  75665. },
  75666. enumerable: true,
  75667. configurable: true
  75668. });
  75669. /**
  75670. * Updates the effect with the current post process compile time values and recompiles the shader.
  75671. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75672. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75673. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75674. * @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
  75675. * @param onCompiled Called when the shader has been compiled.
  75676. * @param onError Called if there is an error when compiling a shader.
  75677. */
  75678. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75679. if (defines === void 0) { defines = null; }
  75680. if (uniforms === void 0) { uniforms = null; }
  75681. if (samplers === void 0) { samplers = null; }
  75682. this._updateParameters(onCompiled, onError);
  75683. };
  75684. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75685. // Generate sampling offsets and weights
  75686. var N = this._kernel;
  75687. var centerIndex = (N - 1) / 2;
  75688. // Generate Gaussian sampling weights over kernel
  75689. var offsets = [];
  75690. var weights = [];
  75691. var totalWeight = 0;
  75692. for (var i = 0; i < N; i++) {
  75693. var u = i / (N - 1);
  75694. var w = this._gaussianWeight(u * 2.0 - 1);
  75695. offsets[i] = (i - centerIndex);
  75696. weights[i] = w;
  75697. totalWeight += w;
  75698. }
  75699. // Normalize weights
  75700. for (var i = 0; i < weights.length; i++) {
  75701. weights[i] /= totalWeight;
  75702. }
  75703. // Optimize: combine samples to take advantage of hardware linear sampling
  75704. // Walk from left to center, combining pairs (symmetrically)
  75705. var linearSamplingWeights = [];
  75706. var linearSamplingOffsets = [];
  75707. var linearSamplingMap = [];
  75708. for (var i = 0; i <= centerIndex; i += 2) {
  75709. var j = Math.min(i + 1, Math.floor(centerIndex));
  75710. var singleCenterSample = i === j;
  75711. if (singleCenterSample) {
  75712. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75713. }
  75714. else {
  75715. var sharedCell = j === centerIndex;
  75716. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75717. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75718. if (offsetLinear === 0) {
  75719. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75720. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75721. }
  75722. else {
  75723. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75724. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75725. }
  75726. }
  75727. }
  75728. for (var i = 0; i < linearSamplingMap.length; i++) {
  75729. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75730. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75731. }
  75732. // Replace with optimized
  75733. offsets = linearSamplingOffsets;
  75734. weights = linearSamplingWeights;
  75735. // Generate shaders
  75736. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75737. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75738. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75739. var defines = "";
  75740. defines += this._staticDefines;
  75741. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75742. if (this._staticDefines.indexOf("DOF") != -1) {
  75743. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75744. varyingCount--;
  75745. }
  75746. for (var i = 0; i < varyingCount; i++) {
  75747. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75748. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75749. }
  75750. var depCount = 0;
  75751. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75752. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75753. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75754. depCount++;
  75755. }
  75756. if (this.packedFloat) {
  75757. defines += "#define PACKEDFLOAT 1";
  75758. }
  75759. this.blockCompilation = false;
  75760. _super.prototype.updateEffect.call(this, defines, null, null, {
  75761. varyingCount: varyingCount,
  75762. depCount: depCount
  75763. }, onCompiled, onError);
  75764. };
  75765. /**
  75766. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75767. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75768. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75769. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75770. * The gaps between physical kernels are compensated for in the weighting of the samples
  75771. * @param idealKernel Ideal blur kernel.
  75772. * @return Nearest best kernel.
  75773. */
  75774. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75775. var v = Math.round(idealKernel);
  75776. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75777. var k = _a[_i];
  75778. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75779. return Math.max(k, 3);
  75780. }
  75781. }
  75782. return Math.max(v, 3);
  75783. };
  75784. /**
  75785. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75786. * @param x The point on the Gaussian distribution to sample.
  75787. * @return the value of the Gaussian function at x.
  75788. */
  75789. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75790. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75791. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75792. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75793. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75794. // truncated at around 1.3% of peak strength.
  75795. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75796. var sigma = (1 / 3);
  75797. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75798. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75799. var weight = (1.0 / denominator) * Math.exp(exponent);
  75800. return weight;
  75801. };
  75802. /**
  75803. * Generates a string that can be used as a floating point number in GLSL.
  75804. * @param x Value to print.
  75805. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75806. * @return GLSL float string.
  75807. */
  75808. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75809. if (decimalFigures === void 0) { decimalFigures = 8; }
  75810. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75811. };
  75812. return BlurPostProcess;
  75813. }(BABYLON.PostProcess));
  75814. BABYLON.BlurPostProcess = BlurPostProcess;
  75815. })(BABYLON || (BABYLON = {}));
  75816. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75817. var BABYLON;
  75818. (function (BABYLON) {
  75819. /**
  75820. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75821. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75822. * based on samples that have a large difference in distance than the center pixel.
  75823. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75824. */
  75825. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75826. __extends(DepthOfFieldBlurPostProcess, _super);
  75827. /**
  75828. * Creates a new instance CircleOfConfusionPostProcess
  75829. * @param name The name of the effect.
  75830. * @param scene The scene the effect belongs to.
  75831. * @param direction The direction the blur should be applied.
  75832. * @param kernel The size of the kernel used to blur.
  75833. * @param options The required width/height ratio to downsize to before computing the render pass.
  75834. * @param camera The camera to apply the render pass to.
  75835. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75836. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75837. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75838. * @param engine The engine which the post process will be applied. (default: current engine)
  75839. * @param reusable If the post process can be reused on the same frame. (default: false)
  75840. * @param textureType Type of textures used when performing the post process. (default: 0)
  75841. * @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)
  75842. */
  75843. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75844. if (imageToBlur === void 0) { imageToBlur = null; }
  75845. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75846. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75847. if (blockCompilation === void 0) { blockCompilation = false; }
  75848. 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;
  75849. _this.direction = direction;
  75850. _this.onApplyObservable.add(function (effect) {
  75851. if (imageToBlur != null) {
  75852. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75853. }
  75854. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75855. if (scene.activeCamera) {
  75856. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75857. }
  75858. });
  75859. return _this;
  75860. }
  75861. return DepthOfFieldBlurPostProcess;
  75862. }(BABYLON.BlurPostProcess));
  75863. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75864. })(BABYLON || (BABYLON = {}));
  75865. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75866. var BABYLON;
  75867. (function (BABYLON) {
  75868. /**
  75869. * Options to be set when merging outputs from the default pipeline.
  75870. */
  75871. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75872. function DepthOfFieldMergePostProcessOptions() {
  75873. }
  75874. return DepthOfFieldMergePostProcessOptions;
  75875. }());
  75876. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75877. /**
  75878. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75879. */
  75880. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75881. __extends(DepthOfFieldMergePostProcess, _super);
  75882. /**
  75883. * Creates a new instance of DepthOfFieldMergePostProcess
  75884. * @param name The name of the effect.
  75885. * @param originalFromInput Post process which's input will be used for the merge.
  75886. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75887. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75888. * @param options The required width/height ratio to downsize to before computing the render pass.
  75889. * @param camera The camera to apply the render pass to.
  75890. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75891. * @param engine The engine which the post process will be applied. (default: current engine)
  75892. * @param reusable If the post process can be reused on the same frame. (default: false)
  75893. * @param textureType Type of textures used when performing the post process. (default: 0)
  75894. * @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)
  75895. */
  75896. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75897. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75898. if (blockCompilation === void 0) { blockCompilation = false; }
  75899. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75900. _this.blurSteps = blurSteps;
  75901. _this.onApplyObservable.add(function (effect) {
  75902. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75903. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75904. blurSteps.forEach(function (step, index) {
  75905. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75906. });
  75907. });
  75908. if (!blockCompilation) {
  75909. _this.updateEffect();
  75910. }
  75911. return _this;
  75912. }
  75913. /**
  75914. * Updates the effect with the current post process compile time values and recompiles the shader.
  75915. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75916. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75917. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75918. * @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
  75919. * @param onCompiled Called when the shader has been compiled.
  75920. * @param onError Called if there is an error when compiling a shader.
  75921. */
  75922. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75923. if (defines === void 0) { defines = null; }
  75924. if (uniforms === void 0) { uniforms = null; }
  75925. if (samplers === void 0) { samplers = null; }
  75926. if (!defines) {
  75927. defines = "";
  75928. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75929. }
  75930. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75931. };
  75932. return DepthOfFieldMergePostProcess;
  75933. }(BABYLON.PostProcess));
  75934. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75935. })(BABYLON || (BABYLON = {}));
  75936. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75937. var BABYLON;
  75938. (function (BABYLON) {
  75939. /**
  75940. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75941. */
  75942. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75943. __extends(CircleOfConfusionPostProcess, _super);
  75944. /**
  75945. * Creates a new instance CircleOfConfusionPostProcess
  75946. * @param name The name of the effect.
  75947. * @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.
  75948. * @param options The required width/height ratio to downsize to before computing the render pass.
  75949. * @param camera The camera to apply the render pass to.
  75950. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75951. * @param engine The engine which the post process will be applied. (default: current engine)
  75952. * @param reusable If the post process can be reused on the same frame. (default: false)
  75953. * @param textureType Type of textures used when performing the post process. (default: 0)
  75954. * @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)
  75955. */
  75956. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75957. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75958. if (blockCompilation === void 0) { blockCompilation = false; }
  75959. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75960. /**
  75961. * 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.
  75962. */
  75963. _this.lensSize = 50;
  75964. /**
  75965. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75966. */
  75967. _this.fStop = 1.4;
  75968. /**
  75969. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75970. */
  75971. _this.focusDistance = 2000;
  75972. /**
  75973. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75974. */
  75975. _this.focalLength = 50;
  75976. _this._depthTexture = null;
  75977. _this._depthTexture = depthTexture;
  75978. _this.onApplyObservable.add(function (effect) {
  75979. if (!_this._depthTexture) {
  75980. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75981. return;
  75982. }
  75983. effect.setTexture("depthSampler", _this._depthTexture);
  75984. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75985. var aperture = _this.lensSize / _this.fStop;
  75986. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75987. effect.setFloat('focusDistance', _this.focusDistance);
  75988. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75989. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75990. });
  75991. return _this;
  75992. }
  75993. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75994. /**
  75995. * 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.
  75996. */
  75997. set: function (value) {
  75998. this._depthTexture = value;
  75999. },
  76000. enumerable: true,
  76001. configurable: true
  76002. });
  76003. return CircleOfConfusionPostProcess;
  76004. }(BABYLON.PostProcess));
  76005. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  76006. })(BABYLON || (BABYLON = {}));
  76007. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  76008. var BABYLON;
  76009. (function (BABYLON) {
  76010. /**
  76011. * Specifies the level of max blur that should be applied when using the depth of field effect
  76012. */
  76013. var DepthOfFieldEffectBlurLevel;
  76014. (function (DepthOfFieldEffectBlurLevel) {
  76015. /**
  76016. * Subtle blur
  76017. */
  76018. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  76019. /**
  76020. * Medium blur
  76021. */
  76022. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  76023. /**
  76024. * Large blur
  76025. */
  76026. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  76027. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  76028. ;
  76029. /**
  76030. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  76031. */
  76032. var DepthOfFieldEffect = /** @class */ (function (_super) {
  76033. __extends(DepthOfFieldEffect, _super);
  76034. /**
  76035. * Creates a new instance DepthOfFieldEffect
  76036. * @param scene The scene the effect belongs to.
  76037. * @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.
  76038. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76039. * @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)
  76040. */
  76041. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  76042. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  76043. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76044. if (blockCompilation === void 0) { blockCompilation = false; }
  76045. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  76046. return _this._effects;
  76047. }, true) || this;
  76048. /**
  76049. * Internal post processes in depth of field effect
  76050. */
  76051. _this._effects = [];
  76052. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  76053. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76054. // 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)
  76055. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  76056. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  76057. _this._depthOfFieldBlurY = [];
  76058. _this._depthOfFieldBlurX = [];
  76059. var blurCount = 1;
  76060. var kernelSize = 15;
  76061. switch (blurLevel) {
  76062. case DepthOfFieldEffectBlurLevel.High: {
  76063. blurCount = 3;
  76064. kernelSize = 51;
  76065. break;
  76066. }
  76067. case DepthOfFieldEffectBlurLevel.Medium: {
  76068. blurCount = 2;
  76069. kernelSize = 31;
  76070. break;
  76071. }
  76072. default: {
  76073. kernelSize = 15;
  76074. blurCount = 1;
  76075. break;
  76076. }
  76077. }
  76078. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  76079. var ratio = 1.0;
  76080. for (var i = 0; i < blurCount; i++) {
  76081. 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);
  76082. blurY.autoClear = false;
  76083. ratio = 0.75 / Math.pow(2, i);
  76084. 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);
  76085. blurX.autoClear = false;
  76086. _this._depthOfFieldBlurY.push(blurY);
  76087. _this._depthOfFieldBlurX.push(blurX);
  76088. }
  76089. // Set all post processes on the effect.
  76090. _this._effects = [_this._circleOfConfusion];
  76091. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  76092. _this._effects.push(_this._depthOfFieldBlurY[i]);
  76093. _this._effects.push(_this._depthOfFieldBlurX[i]);
  76094. }
  76095. // Merge blurred images with original image based on circleOfConfusion
  76096. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76097. _this._dofMerge.autoClear = false;
  76098. _this._effects.push(_this._dofMerge);
  76099. return _this;
  76100. }
  76101. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  76102. get: function () {
  76103. return this._circleOfConfusion.focalLength;
  76104. },
  76105. /**
  76106. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  76107. */
  76108. set: function (value) {
  76109. this._circleOfConfusion.focalLength = value;
  76110. },
  76111. enumerable: true,
  76112. configurable: true
  76113. });
  76114. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  76115. get: function () {
  76116. return this._circleOfConfusion.fStop;
  76117. },
  76118. /**
  76119. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  76120. */
  76121. set: function (value) {
  76122. this._circleOfConfusion.fStop = value;
  76123. },
  76124. enumerable: true,
  76125. configurable: true
  76126. });
  76127. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  76128. get: function () {
  76129. return this._circleOfConfusion.focusDistance;
  76130. },
  76131. /**
  76132. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  76133. */
  76134. set: function (value) {
  76135. this._circleOfConfusion.focusDistance = value;
  76136. },
  76137. enumerable: true,
  76138. configurable: true
  76139. });
  76140. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  76141. get: function () {
  76142. return this._circleOfConfusion.lensSize;
  76143. },
  76144. /**
  76145. * 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.
  76146. */
  76147. set: function (value) {
  76148. this._circleOfConfusion.lensSize = value;
  76149. },
  76150. enumerable: true,
  76151. configurable: true
  76152. });
  76153. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  76154. /**
  76155. * 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.
  76156. */
  76157. set: function (value) {
  76158. this._circleOfConfusion.depthTexture = value;
  76159. },
  76160. enumerable: true,
  76161. configurable: true
  76162. });
  76163. /**
  76164. * Disposes each of the internal effects for a given camera.
  76165. * @param camera The camera to dispose the effect on.
  76166. */
  76167. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  76168. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76169. this._effects[effectIndex].dispose(camera);
  76170. }
  76171. };
  76172. /**
  76173. * Internal
  76174. */
  76175. DepthOfFieldEffect.prototype._updateEffects = function () {
  76176. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76177. this._effects[effectIndex].updateEffect();
  76178. }
  76179. };
  76180. /**
  76181. * Internal
  76182. * @returns if all the contained post processes are ready.
  76183. */
  76184. DepthOfFieldEffect.prototype._isReady = function () {
  76185. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76186. if (!this._effects[effectIndex].isReady()) {
  76187. return false;
  76188. }
  76189. }
  76190. return true;
  76191. };
  76192. return DepthOfFieldEffect;
  76193. }(BABYLON.PostProcessRenderEffect));
  76194. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  76195. })(BABYLON || (BABYLON = {}));
  76196. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  76197. var BABYLON;
  76198. (function (BABYLON) {
  76199. /**
  76200. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  76201. */
  76202. var BloomMergePostProcess = /** @class */ (function (_super) {
  76203. __extends(BloomMergePostProcess, _super);
  76204. /**
  76205. * Creates a new instance of @see BloomMergePostProcess
  76206. * @param name The name of the effect.
  76207. * @param originalFromInput Post process which's input will be used for the merge.
  76208. * @param blurred Blurred highlights post process which's output will be used.
  76209. * @param weight Weight of the bloom to be added to the original input.
  76210. * @param options The required width/height ratio to downsize to before computing the render pass.
  76211. * @param camera The camera to apply the render pass to.
  76212. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76213. * @param engine The engine which the post process will be applied. (default: current engine)
  76214. * @param reusable If the post process can be reused on the same frame. (default: false)
  76215. * @param textureType Type of textures used when performing the post process. (default: 0)
  76216. * @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)
  76217. */
  76218. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76219. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76220. if (blockCompilation === void 0) { blockCompilation = false; }
  76221. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  76222. _this.weight = weight;
  76223. _this.onApplyObservable.add(function (effect) {
  76224. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  76225. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  76226. effect.setFloat("bloomWeight", _this.weight);
  76227. });
  76228. if (!blockCompilation) {
  76229. _this.updateEffect();
  76230. }
  76231. return _this;
  76232. }
  76233. return BloomMergePostProcess;
  76234. }(BABYLON.PostProcess));
  76235. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  76236. })(BABYLON || (BABYLON = {}));
  76237. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  76238. var BABYLON;
  76239. (function (BABYLON) {
  76240. /**
  76241. * 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.
  76242. */
  76243. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  76244. __extends(ExtractHighlightsPostProcess, _super);
  76245. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76246. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76247. if (blockCompilation === void 0) { blockCompilation = false; }
  76248. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76249. /**
  76250. * The luminance threshold, pixels below this value will be set to black.
  76251. */
  76252. _this.threshold = 0.9;
  76253. /**
  76254. * Internal
  76255. */
  76256. _this._exposure = 1;
  76257. /**
  76258. * Post process which has the input texture to be used when performing highlight extraction
  76259. */
  76260. _this._inputPostProcess = null;
  76261. _this.onApplyObservable.add(function (effect) {
  76262. if (_this._inputPostProcess) {
  76263. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  76264. }
  76265. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  76266. effect.setFloat('exposure', _this._exposure);
  76267. });
  76268. return _this;
  76269. }
  76270. return ExtractHighlightsPostProcess;
  76271. }(BABYLON.PostProcess));
  76272. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  76273. })(BABYLON || (BABYLON = {}));
  76274. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  76275. var BABYLON;
  76276. (function (BABYLON) {
  76277. /**
  76278. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  76279. */
  76280. var BloomEffect = /** @class */ (function (_super) {
  76281. __extends(BloomEffect, _super);
  76282. /**
  76283. * Creates a new instance of @see BloomEffect
  76284. * @param scene The scene the effect belongs to.
  76285. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  76286. * @param bloomKernel The size of the kernel to be used when applying the blur.
  76287. * @param bloomWeight The the strength of bloom.
  76288. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76289. * @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)
  76290. */
  76291. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  76292. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76293. if (blockCompilation === void 0) { blockCompilation = false; }
  76294. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  76295. return _this._effects;
  76296. }, true) || this;
  76297. _this.bloomScale = bloomScale;
  76298. /**
  76299. * Internal
  76300. */
  76301. _this._effects = [];
  76302. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76303. _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);
  76304. _this._blurX.alwaysForcePOT = true;
  76305. _this._blurX.autoClear = false;
  76306. _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);
  76307. _this._blurY.alwaysForcePOT = true;
  76308. _this._blurY.autoClear = false;
  76309. _this.kernel = bloomKernel;
  76310. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  76311. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76312. _this._merge.autoClear = false;
  76313. _this._effects.push(_this._merge);
  76314. return _this;
  76315. }
  76316. Object.defineProperty(BloomEffect.prototype, "threshold", {
  76317. /**
  76318. * The luminance threshold to find bright areas of the image to bloom.
  76319. */
  76320. get: function () {
  76321. return this._downscale.threshold;
  76322. },
  76323. set: function (value) {
  76324. this._downscale.threshold = value;
  76325. },
  76326. enumerable: true,
  76327. configurable: true
  76328. });
  76329. Object.defineProperty(BloomEffect.prototype, "weight", {
  76330. /**
  76331. * The strength of the bloom.
  76332. */
  76333. get: function () {
  76334. return this._merge.weight;
  76335. },
  76336. set: function (value) {
  76337. this._merge.weight = value;
  76338. },
  76339. enumerable: true,
  76340. configurable: true
  76341. });
  76342. Object.defineProperty(BloomEffect.prototype, "kernel", {
  76343. /**
  76344. * Specifies the size of the bloom blur kernel, relative to the final output size
  76345. */
  76346. get: function () {
  76347. return this._blurX.kernel / this.bloomScale;
  76348. },
  76349. set: function (value) {
  76350. this._blurX.kernel = value * this.bloomScale;
  76351. this._blurY.kernel = value * this.bloomScale;
  76352. },
  76353. enumerable: true,
  76354. configurable: true
  76355. });
  76356. /**
  76357. * Disposes each of the internal effects for a given camera.
  76358. * @param camera The camera to dispose the effect on.
  76359. */
  76360. BloomEffect.prototype.disposeEffects = function (camera) {
  76361. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76362. this._effects[effectIndex].dispose(camera);
  76363. }
  76364. };
  76365. /**
  76366. * Internal
  76367. */
  76368. BloomEffect.prototype._updateEffects = function () {
  76369. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76370. this._effects[effectIndex].updateEffect();
  76371. }
  76372. };
  76373. /**
  76374. * Internal
  76375. * @returns if all the contained post processes are ready.
  76376. */
  76377. BloomEffect.prototype._isReady = function () {
  76378. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76379. if (!this._effects[effectIndex].isReady()) {
  76380. return false;
  76381. }
  76382. }
  76383. return true;
  76384. };
  76385. return BloomEffect;
  76386. }(BABYLON.PostProcessRenderEffect));
  76387. BABYLON.BloomEffect = BloomEffect;
  76388. })(BABYLON || (BABYLON = {}));
  76389. //# sourceMappingURL=babylon.bloomEffect.js.map
  76390. var BABYLON;
  76391. (function (BABYLON) {
  76392. /**
  76393. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76394. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76395. */
  76396. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76397. __extends(DefaultRenderingPipeline, _super);
  76398. /**
  76399. * @constructor
  76400. * @param {string} name - The rendering pipeline name (default: "")
  76401. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76402. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76403. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76404. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76405. */
  76406. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76407. if (name === void 0) { name = ""; }
  76408. if (hdr === void 0) { hdr = true; }
  76409. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76410. if (automaticBuild === void 0) { automaticBuild = true; }
  76411. var _this = _super.call(this, scene.getEngine(), name) || this;
  76412. _this._originalCameras = [];
  76413. /**
  76414. * ID of the sharpen post process,
  76415. */
  76416. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76417. /**
  76418. * ID of the image processing post process;
  76419. */
  76420. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76421. /**
  76422. * ID of the Fast Approximate Anti-Aliasing post process;
  76423. */
  76424. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76425. /**
  76426. * ID of the chromatic aberration post process,
  76427. */
  76428. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76429. /**
  76430. * ID of the grain post process
  76431. */
  76432. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76433. /**
  76434. * Glow post process which adds a glow to emmisive areas of the image
  76435. */
  76436. _this._glowLayer = null;
  76437. /**
  76438. * Animations which can be used to tweak settings over a period of time
  76439. */
  76440. _this.animations = [];
  76441. _this._imageProcessingConfigurationObserver = null;
  76442. // Values
  76443. _this._sharpenEnabled = false;
  76444. _this._bloomEnabled = false;
  76445. _this._depthOfFieldEnabled = false;
  76446. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76447. _this._fxaaEnabled = false;
  76448. _this._imageProcessingEnabled = true;
  76449. _this._bloomScale = 0.5;
  76450. _this._chromaticAberrationEnabled = false;
  76451. _this._grainEnabled = false;
  76452. _this._buildAllowed = true;
  76453. _this._resizeObserver = null;
  76454. _this._hardwareScaleLevel = 1.0;
  76455. _this._bloomKernel = 64;
  76456. /**
  76457. * Specifies the weight of the bloom in the final rendering
  76458. */
  76459. _this._bloomWeight = 0.15;
  76460. /**
  76461. * Specifies the luma threshold for the area that will be blurred by the bloom
  76462. */
  76463. _this._bloomThreshold = 0.9;
  76464. _this._samples = 1;
  76465. _this._hasCleared = false;
  76466. _this._prevPostProcess = null;
  76467. _this._prevPrevPostProcess = null;
  76468. _this._cameras = cameras || scene.cameras;
  76469. _this._originalCameras = _this._cameras.slice();
  76470. _this._buildAllowed = automaticBuild;
  76471. // Initialize
  76472. _this._scene = scene;
  76473. var caps = _this._scene.getEngine().getCaps();
  76474. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76475. // Misc
  76476. if (_this._hdr) {
  76477. if (caps.textureHalfFloatRender) {
  76478. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76479. }
  76480. else if (caps.textureFloatRender) {
  76481. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76482. }
  76483. }
  76484. else {
  76485. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76486. }
  76487. // Attach
  76488. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76489. var engine = _this._scene.getEngine();
  76490. // Create post processes before hand so they can be modified before enabled.
  76491. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76492. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76493. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76494. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76495. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76496. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76497. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76498. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76499. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76500. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76501. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76502. _this.bloomKernel = _this.bloomKernel;
  76503. });
  76504. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76505. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76506. });
  76507. _this._buildPipeline();
  76508. return _this;
  76509. }
  76510. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76511. get: function () {
  76512. return this._sharpenEnabled;
  76513. },
  76514. /**
  76515. * Enable or disable the sharpen process from the pipeline
  76516. */
  76517. set: function (enabled) {
  76518. if (this._sharpenEnabled === enabled) {
  76519. return;
  76520. }
  76521. this._sharpenEnabled = enabled;
  76522. this._buildPipeline();
  76523. },
  76524. enumerable: true,
  76525. configurable: true
  76526. });
  76527. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76528. /**
  76529. * Specifies the size of the bloom blur kernel, relative to the final output size
  76530. */
  76531. get: function () {
  76532. return this._bloomKernel;
  76533. },
  76534. set: function (value) {
  76535. this._bloomKernel = value;
  76536. this.bloom.kernel = value / this._hardwareScaleLevel;
  76537. },
  76538. enumerable: true,
  76539. configurable: true
  76540. });
  76541. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76542. get: function () {
  76543. return this._bloomWeight;
  76544. },
  76545. /**
  76546. * The strength of the bloom.
  76547. */
  76548. set: function (value) {
  76549. if (this._bloomWeight === value) {
  76550. return;
  76551. }
  76552. this.bloom.weight = value;
  76553. this._bloomWeight = value;
  76554. },
  76555. enumerable: true,
  76556. configurable: true
  76557. });
  76558. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76559. get: function () {
  76560. return this._bloomThreshold;
  76561. },
  76562. /**
  76563. * The strength of the bloom.
  76564. */
  76565. set: function (value) {
  76566. if (this._bloomThreshold === value) {
  76567. return;
  76568. }
  76569. this.bloom.threshold = value;
  76570. this._bloomThreshold = value;
  76571. },
  76572. enumerable: true,
  76573. configurable: true
  76574. });
  76575. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76576. get: function () {
  76577. return this._bloomScale;
  76578. },
  76579. /**
  76580. * The scale of the bloom, lower value will provide better performance.
  76581. */
  76582. set: function (value) {
  76583. if (this._bloomScale === value) {
  76584. return;
  76585. }
  76586. this._bloomScale = value;
  76587. // recreate bloom and dispose old as this setting is not dynamic
  76588. this._rebuildBloom();
  76589. this._buildPipeline();
  76590. },
  76591. enumerable: true,
  76592. configurable: true
  76593. });
  76594. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76595. get: function () {
  76596. return this._bloomEnabled;
  76597. },
  76598. /**
  76599. * Enable or disable the bloom from the pipeline
  76600. */
  76601. set: function (enabled) {
  76602. if (this._bloomEnabled === enabled) {
  76603. return;
  76604. }
  76605. this._bloomEnabled = enabled;
  76606. this._buildPipeline();
  76607. },
  76608. enumerable: true,
  76609. configurable: true
  76610. });
  76611. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76612. // recreate bloom and dispose old as this setting is not dynamic
  76613. var oldBloom = this.bloom;
  76614. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76615. this.bloom.threshold = oldBloom.threshold;
  76616. for (var i = 0; i < this._cameras.length; i++) {
  76617. oldBloom.disposeEffects(this._cameras[i]);
  76618. }
  76619. };
  76620. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76621. /**
  76622. * If the depth of field is enabled.
  76623. */
  76624. get: function () {
  76625. return this._depthOfFieldEnabled;
  76626. },
  76627. set: function (enabled) {
  76628. if (this._depthOfFieldEnabled === enabled) {
  76629. return;
  76630. }
  76631. this._depthOfFieldEnabled = enabled;
  76632. this._buildPipeline();
  76633. },
  76634. enumerable: true,
  76635. configurable: true
  76636. });
  76637. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76638. /**
  76639. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76640. */
  76641. get: function () {
  76642. return this._depthOfFieldBlurLevel;
  76643. },
  76644. set: function (value) {
  76645. if (this._depthOfFieldBlurLevel === value) {
  76646. return;
  76647. }
  76648. this._depthOfFieldBlurLevel = value;
  76649. // recreate dof and dispose old as this setting is not dynamic
  76650. var oldDof = this.depthOfField;
  76651. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76652. this.depthOfField.focalLength = oldDof.focalLength;
  76653. this.depthOfField.focusDistance = oldDof.focusDistance;
  76654. this.depthOfField.fStop = oldDof.fStop;
  76655. this.depthOfField.lensSize = oldDof.lensSize;
  76656. for (var i = 0; i < this._cameras.length; i++) {
  76657. oldDof.disposeEffects(this._cameras[i]);
  76658. }
  76659. this._buildPipeline();
  76660. },
  76661. enumerable: true,
  76662. configurable: true
  76663. });
  76664. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76665. get: function () {
  76666. return this._fxaaEnabled;
  76667. },
  76668. /**
  76669. * If the anti aliasing is enabled.
  76670. */
  76671. set: function (enabled) {
  76672. if (this._fxaaEnabled === enabled) {
  76673. return;
  76674. }
  76675. this._fxaaEnabled = enabled;
  76676. this._buildPipeline();
  76677. },
  76678. enumerable: true,
  76679. configurable: true
  76680. });
  76681. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76682. get: function () {
  76683. return this._samples;
  76684. },
  76685. /**
  76686. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76687. */
  76688. set: function (sampleCount) {
  76689. if (this._samples === sampleCount) {
  76690. return;
  76691. }
  76692. this._samples = sampleCount;
  76693. this._buildPipeline();
  76694. },
  76695. enumerable: true,
  76696. configurable: true
  76697. });
  76698. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76699. get: function () {
  76700. return this._imageProcessingEnabled;
  76701. },
  76702. /**
  76703. * If image processing is enabled.
  76704. */
  76705. set: function (enabled) {
  76706. if (this._imageProcessingEnabled === enabled) {
  76707. return;
  76708. }
  76709. this._imageProcessingEnabled = enabled;
  76710. this._buildPipeline();
  76711. },
  76712. enumerable: true,
  76713. configurable: true
  76714. });
  76715. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76716. get: function () {
  76717. return this._glowLayer == null;
  76718. },
  76719. /**
  76720. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76721. */
  76722. set: function (enabled) {
  76723. if (enabled && !this._glowLayer) {
  76724. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76725. }
  76726. else if (!enabled && this._glowLayer) {
  76727. this._glowLayer.dispose();
  76728. this._glowLayer = null;
  76729. }
  76730. },
  76731. enumerable: true,
  76732. configurable: true
  76733. });
  76734. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76735. get: function () {
  76736. return this._chromaticAberrationEnabled;
  76737. },
  76738. /**
  76739. * Enable or disable the chromaticAberration process from the pipeline
  76740. */
  76741. set: function (enabled) {
  76742. if (this._chromaticAberrationEnabled === enabled) {
  76743. return;
  76744. }
  76745. this._chromaticAberrationEnabled = enabled;
  76746. this._buildPipeline();
  76747. },
  76748. enumerable: true,
  76749. configurable: true
  76750. });
  76751. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76752. get: function () {
  76753. return this._grainEnabled;
  76754. },
  76755. /**
  76756. * Enable or disable the grain process from the pipeline
  76757. */
  76758. set: function (enabled) {
  76759. if (this._grainEnabled === enabled) {
  76760. return;
  76761. }
  76762. this._grainEnabled = enabled;
  76763. this._buildPipeline();
  76764. },
  76765. enumerable: true,
  76766. configurable: true
  76767. });
  76768. /**
  76769. * Force the compilation of the entire pipeline.
  76770. */
  76771. DefaultRenderingPipeline.prototype.prepare = function () {
  76772. var previousState = this._buildAllowed;
  76773. this._buildAllowed = true;
  76774. this._buildPipeline();
  76775. this._buildAllowed = previousState;
  76776. };
  76777. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76778. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76779. if (this._hasCleared) {
  76780. postProcess.autoClear = false;
  76781. }
  76782. else {
  76783. postProcess.autoClear = true;
  76784. this._scene.autoClear = false;
  76785. this._hasCleared = true;
  76786. }
  76787. if (!skipTextureSharing) {
  76788. if (this._prevPrevPostProcess) {
  76789. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76790. }
  76791. else {
  76792. postProcess.useOwnOutput();
  76793. }
  76794. if (this._prevPostProcess) {
  76795. this._prevPrevPostProcess = this._prevPostProcess;
  76796. }
  76797. this._prevPostProcess = postProcess;
  76798. }
  76799. };
  76800. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76801. var _this = this;
  76802. if (!this._buildAllowed) {
  76803. return;
  76804. }
  76805. this._scene.autoClear = true;
  76806. var engine = this._scene.getEngine();
  76807. this._disposePostProcesses();
  76808. if (this._cameras !== null) {
  76809. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76810. // get back cameras to be used to reattach pipeline
  76811. this._cameras = this._originalCameras.slice();
  76812. }
  76813. this._reset();
  76814. this._prevPostProcess = null;
  76815. this._prevPrevPostProcess = null;
  76816. this._hasCleared = false;
  76817. if (this.depthOfFieldEnabled) {
  76818. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76819. this.depthOfField.depthTexture = depthTexture;
  76820. if (!this.depthOfField._isReady()) {
  76821. this.depthOfField._updateEffects();
  76822. }
  76823. this.addEffect(this.depthOfField);
  76824. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76825. }
  76826. if (this.bloomEnabled) {
  76827. if (!this.bloom._isReady()) {
  76828. this.bloom._updateEffects();
  76829. }
  76830. this.addEffect(this.bloom);
  76831. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76832. }
  76833. if (this._imageProcessingEnabled) {
  76834. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76835. if (this._hdr) {
  76836. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76837. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76838. }
  76839. else {
  76840. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76841. }
  76842. }
  76843. if (this.sharpenEnabled) {
  76844. if (!this.sharpen.isReady()) {
  76845. this.sharpen.updateEffect();
  76846. }
  76847. this.addEffect(this._sharpenEffect);
  76848. this._setAutoClearAndTextureSharing(this.sharpen);
  76849. }
  76850. if (this.grainEnabled) {
  76851. if (!this.grain.isReady()) {
  76852. this.grain.updateEffect();
  76853. }
  76854. this.addEffect(this._grainEffect);
  76855. this._setAutoClearAndTextureSharing(this.grain);
  76856. }
  76857. if (this.chromaticAberrationEnabled) {
  76858. if (!this.chromaticAberration.isReady()) {
  76859. this.chromaticAberration.updateEffect();
  76860. }
  76861. this.addEffect(this._chromaticAberrationEffect);
  76862. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76863. }
  76864. if (this.fxaaEnabled) {
  76865. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76866. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76867. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76868. }
  76869. if (this._cameras !== null) {
  76870. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76871. }
  76872. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76873. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76874. }
  76875. };
  76876. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76877. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76878. for (var i = 0; i < this._cameras.length; i++) {
  76879. var camera = this._cameras[i];
  76880. if (this.imageProcessing) {
  76881. this.imageProcessing.dispose(camera);
  76882. }
  76883. if (this.fxaa) {
  76884. this.fxaa.dispose(camera);
  76885. }
  76886. // These are created in the constructor and should not be disposed on every pipeline change
  76887. if (disposeNonRecreated) {
  76888. if (this.sharpen) {
  76889. this.sharpen.dispose(camera);
  76890. }
  76891. if (this.depthOfField) {
  76892. this.depthOfField.disposeEffects(camera);
  76893. }
  76894. if (this.bloom) {
  76895. this.bloom.disposeEffects(camera);
  76896. }
  76897. if (this.chromaticAberration) {
  76898. this.chromaticAberration.dispose(camera);
  76899. }
  76900. if (this.grain) {
  76901. this.grain.dispose(camera);
  76902. }
  76903. if (this._glowLayer) {
  76904. this._glowLayer.dispose();
  76905. }
  76906. }
  76907. }
  76908. this.imageProcessing = null;
  76909. this.fxaa = null;
  76910. if (disposeNonRecreated) {
  76911. this.sharpen = null;
  76912. this._sharpenEffect = null;
  76913. this.depthOfField = null;
  76914. this.bloom = null;
  76915. this.chromaticAberration = null;
  76916. this._chromaticAberrationEffect = null;
  76917. this.grain = null;
  76918. this._grainEffect = null;
  76919. this._glowLayer = null;
  76920. }
  76921. };
  76922. /**
  76923. * Dispose of the pipeline and stop all post processes
  76924. */
  76925. DefaultRenderingPipeline.prototype.dispose = function () {
  76926. this._disposePostProcesses(true);
  76927. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76928. this._scene.autoClear = true;
  76929. if (this._resizeObserver) {
  76930. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76931. this._resizeObserver = null;
  76932. }
  76933. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76934. _super.prototype.dispose.call(this);
  76935. };
  76936. /**
  76937. * Serialize the rendering pipeline (Used when exporting)
  76938. * @returns the serialized object
  76939. */
  76940. DefaultRenderingPipeline.prototype.serialize = function () {
  76941. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76942. serializationObject.customType = "DefaultRenderingPipeline";
  76943. return serializationObject;
  76944. };
  76945. /**
  76946. * Parse the serialized pipeline
  76947. * @param source Source pipeline.
  76948. * @param scene The scene to load the pipeline to.
  76949. * @param rootUrl The URL of the serialized pipeline.
  76950. * @returns An instantiated pipeline from the serialized object.
  76951. */
  76952. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76953. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76954. };
  76955. __decorate([
  76956. BABYLON.serialize()
  76957. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76958. __decorate([
  76959. BABYLON.serialize()
  76960. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76961. __decorate([
  76962. BABYLON.serialize()
  76963. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76964. __decorate([
  76965. BABYLON.serialize()
  76966. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76967. __decorate([
  76968. BABYLON.serialize()
  76969. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76970. __decorate([
  76971. BABYLON.serialize()
  76972. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76973. __decorate([
  76974. BABYLON.serialize()
  76975. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76976. __decorate([
  76977. BABYLON.serialize()
  76978. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76979. __decorate([
  76980. BABYLON.serialize()
  76981. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76982. __decorate([
  76983. BABYLON.serialize()
  76984. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76985. __decorate([
  76986. BABYLON.serialize()
  76987. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76988. __decorate([
  76989. BABYLON.serialize()
  76990. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76991. __decorate([
  76992. BABYLON.serialize()
  76993. ], DefaultRenderingPipeline.prototype, "samples", null);
  76994. __decorate([
  76995. BABYLON.serialize()
  76996. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76997. __decorate([
  76998. BABYLON.serialize()
  76999. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  77000. __decorate([
  77001. BABYLON.serialize()
  77002. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  77003. __decorate([
  77004. BABYLON.serialize()
  77005. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  77006. return DefaultRenderingPipeline;
  77007. }(BABYLON.PostProcessRenderPipeline));
  77008. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  77009. })(BABYLON || (BABYLON = {}));
  77010. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  77011. var BABYLON;
  77012. (function (BABYLON) {
  77013. /**
  77014. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  77015. */
  77016. var GeometryBufferRenderer = /** @class */ (function () {
  77017. /**
  77018. * Creates a new G Buffer for the scene
  77019. * @param scene The scene the buffer belongs to
  77020. * @param ratio How big is the buffer related to the main canvas.
  77021. */
  77022. function GeometryBufferRenderer(scene, ratio) {
  77023. if (ratio === void 0) { ratio = 1; }
  77024. this._enablePosition = false;
  77025. this._scene = scene;
  77026. this._ratio = ratio;
  77027. // Render target
  77028. this._createRenderTargets();
  77029. }
  77030. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  77031. /**
  77032. * Set the render list (meshes to be rendered) used in the G buffer.
  77033. */
  77034. set: function (meshes) {
  77035. this._multiRenderTarget.renderList = meshes;
  77036. },
  77037. enumerable: true,
  77038. configurable: true
  77039. });
  77040. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  77041. /**
  77042. * Gets wether or not G buffer are supported by the running hardware.
  77043. * This requires draw buffer supports
  77044. */
  77045. get: function () {
  77046. return this._multiRenderTarget.isSupported;
  77047. },
  77048. enumerable: true,
  77049. configurable: true
  77050. });
  77051. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  77052. /**
  77053. * Gets wether or not position are enabled for the G buffer.
  77054. */
  77055. get: function () {
  77056. return this._enablePosition;
  77057. },
  77058. /**
  77059. * Sets wether or not position are enabled for the G buffer.
  77060. */
  77061. set: function (enable) {
  77062. this._enablePosition = enable;
  77063. this.dispose();
  77064. this._createRenderTargets();
  77065. },
  77066. enumerable: true,
  77067. configurable: true
  77068. });
  77069. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  77070. /**
  77071. * Gets the scene associated with the buffer.
  77072. */
  77073. get: function () {
  77074. return this._scene;
  77075. },
  77076. enumerable: true,
  77077. configurable: true
  77078. });
  77079. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  77080. /**
  77081. * Gets the ratio used by the buffer during its creation.
  77082. * How big is the buffer related to the main canvas.
  77083. */
  77084. get: function () {
  77085. return this._ratio;
  77086. },
  77087. enumerable: true,
  77088. configurable: true
  77089. });
  77090. /**
  77091. * Checks wether everything is ready to render a submesh to the G buffer.
  77092. * @param subMesh the submesh to check readiness for
  77093. * @param useInstances is the mesh drawn using instance or not
  77094. * @returns true if ready otherwise false
  77095. */
  77096. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  77097. var material = subMesh.getMaterial();
  77098. if (material && material.disableDepthWrite) {
  77099. return false;
  77100. }
  77101. var defines = [];
  77102. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  77103. var mesh = subMesh.getMesh();
  77104. // Alpha test
  77105. if (material && material.needAlphaTesting()) {
  77106. defines.push("#define ALPHATEST");
  77107. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77108. attribs.push(BABYLON.VertexBuffer.UVKind);
  77109. defines.push("#define UV1");
  77110. }
  77111. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77112. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77113. defines.push("#define UV2");
  77114. }
  77115. }
  77116. // Buffers
  77117. if (this._enablePosition) {
  77118. defines.push("#define POSITION");
  77119. }
  77120. // Bones
  77121. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77122. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77123. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77124. if (mesh.numBoneInfluencers > 4) {
  77125. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77126. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77127. }
  77128. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77129. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77130. }
  77131. else {
  77132. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77133. }
  77134. // Instances
  77135. if (useInstances) {
  77136. defines.push("#define INSTANCES");
  77137. attribs.push("world0");
  77138. attribs.push("world1");
  77139. attribs.push("world2");
  77140. attribs.push("world3");
  77141. }
  77142. // Get correct effect
  77143. var join = defines.join("\n");
  77144. if (this._cachedDefines !== join) {
  77145. this._cachedDefines = join;
  77146. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  77147. }
  77148. return this._effect.isReady();
  77149. };
  77150. /**
  77151. * Gets the current underlying G Buffer.
  77152. * @returns the buffer
  77153. */
  77154. GeometryBufferRenderer.prototype.getGBuffer = function () {
  77155. return this._multiRenderTarget;
  77156. };
  77157. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  77158. /**
  77159. * Gets the number of samples used to render the buffer (anti aliasing).
  77160. */
  77161. get: function () {
  77162. return this._multiRenderTarget.samples;
  77163. },
  77164. /**
  77165. * Sets the number of samples used to render the buffer (anti aliasing).
  77166. */
  77167. set: function (value) {
  77168. this._multiRenderTarget.samples = value;
  77169. },
  77170. enumerable: true,
  77171. configurable: true
  77172. });
  77173. /**
  77174. * Disposes the renderer and frees up associated resources.
  77175. */
  77176. GeometryBufferRenderer.prototype.dispose = function () {
  77177. this.getGBuffer().dispose();
  77178. };
  77179. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  77180. var _this = this;
  77181. var engine = this._scene.getEngine();
  77182. var count = this._enablePosition ? 3 : 2;
  77183. 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 });
  77184. if (!this.isSupported) {
  77185. return;
  77186. }
  77187. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77188. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77189. this._multiRenderTarget.refreshRate = 1;
  77190. this._multiRenderTarget.renderParticles = false;
  77191. this._multiRenderTarget.renderList = null;
  77192. // set default depth value to 1.0 (far away)
  77193. this._multiRenderTarget.onClearObservable.add(function (engine) {
  77194. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  77195. });
  77196. // Custom render function
  77197. var renderSubMesh = function (subMesh) {
  77198. var mesh = subMesh.getRenderingMesh();
  77199. var scene = _this._scene;
  77200. var engine = scene.getEngine();
  77201. var material = subMesh.getMaterial();
  77202. if (!material) {
  77203. return;
  77204. }
  77205. // Culling
  77206. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77207. // Managing instances
  77208. var batch = mesh._getInstancesRenderList(subMesh._id);
  77209. if (batch.mustReturn) {
  77210. return;
  77211. }
  77212. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77213. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  77214. engine.enableEffect(_this._effect);
  77215. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77216. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77217. _this._effect.setMatrix("view", scene.getViewMatrix());
  77218. // Alpha test
  77219. if (material && material.needAlphaTesting()) {
  77220. var alphaTexture = material.getAlphaTestTexture();
  77221. if (alphaTexture) {
  77222. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77223. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77224. }
  77225. }
  77226. // Bones
  77227. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77228. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77229. }
  77230. // Draw
  77231. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77232. }
  77233. };
  77234. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77235. var index;
  77236. if (depthOnlySubMeshes.length) {
  77237. engine.setColorWrite(false);
  77238. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77239. renderSubMesh(depthOnlySubMeshes.data[index]);
  77240. }
  77241. engine.setColorWrite(true);
  77242. }
  77243. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77244. renderSubMesh(opaqueSubMeshes.data[index]);
  77245. }
  77246. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77247. renderSubMesh(alphaTestSubMeshes.data[index]);
  77248. }
  77249. };
  77250. };
  77251. return GeometryBufferRenderer;
  77252. }());
  77253. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  77254. })(BABYLON || (BABYLON = {}));
  77255. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  77256. var BABYLON;
  77257. (function (BABYLON) {
  77258. var RefractionPostProcess = /** @class */ (function (_super) {
  77259. __extends(RefractionPostProcess, _super);
  77260. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  77261. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  77262. _this.color = color;
  77263. _this.depth = depth;
  77264. _this.colorLevel = colorLevel;
  77265. _this._ownRefractionTexture = true;
  77266. _this.onActivateObservable.add(function (cam) {
  77267. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  77268. });
  77269. _this.onApplyObservable.add(function (effect) {
  77270. effect.setColor3("baseColor", _this.color);
  77271. effect.setFloat("depth", _this.depth);
  77272. effect.setFloat("colorLevel", _this.colorLevel);
  77273. effect.setTexture("refractionSampler", _this._refTexture);
  77274. });
  77275. return _this;
  77276. }
  77277. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  77278. /**
  77279. * Gets or sets the refraction texture
  77280. * Please note that you are responsible for disposing the texture if you set it manually
  77281. */
  77282. get: function () {
  77283. return this._refTexture;
  77284. },
  77285. set: function (value) {
  77286. if (this._refTexture && this._ownRefractionTexture) {
  77287. this._refTexture.dispose();
  77288. }
  77289. this._refTexture = value;
  77290. this._ownRefractionTexture = false;
  77291. },
  77292. enumerable: true,
  77293. configurable: true
  77294. });
  77295. // Methods
  77296. RefractionPostProcess.prototype.dispose = function (camera) {
  77297. if (this._refTexture && this._ownRefractionTexture) {
  77298. this._refTexture.dispose();
  77299. this._refTexture = null;
  77300. }
  77301. _super.prototype.dispose.call(this, camera);
  77302. };
  77303. return RefractionPostProcess;
  77304. }(BABYLON.PostProcess));
  77305. BABYLON.RefractionPostProcess = RefractionPostProcess;
  77306. })(BABYLON || (BABYLON = {}));
  77307. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  77308. var BABYLON;
  77309. (function (BABYLON) {
  77310. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  77311. __extends(BlackAndWhitePostProcess, _super);
  77312. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  77313. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  77314. _this.degree = 1;
  77315. _this.onApplyObservable.add(function (effect) {
  77316. effect.setFloat("degree", _this.degree);
  77317. });
  77318. return _this;
  77319. }
  77320. return BlackAndWhitePostProcess;
  77321. }(BABYLON.PostProcess));
  77322. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  77323. })(BABYLON || (BABYLON = {}));
  77324. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  77325. var BABYLON;
  77326. (function (BABYLON) {
  77327. /**
  77328. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  77329. * input texture to perform effects such as edge detection or sharpening
  77330. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  77331. */
  77332. var ConvolutionPostProcess = /** @class */ (function (_super) {
  77333. __extends(ConvolutionPostProcess, _super);
  77334. /**
  77335. * Creates a new instance ConvolutionPostProcess
  77336. * @param name The name of the effect.
  77337. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  77338. * @param options The required width/height ratio to downsize to before computing the render pass.
  77339. * @param camera The camera to apply the render pass to.
  77340. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77341. * @param engine The engine which the post process will be applied. (default: current engine)
  77342. * @param reusable If the post process can be reused on the same frame. (default: false)
  77343. * @param textureType Type of textures used when performing the post process. (default: 0)
  77344. */
  77345. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  77346. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77347. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77348. _this.kernel = kernel;
  77349. _this.onApply = function (effect) {
  77350. effect.setFloat2("screenSize", _this.width, _this.height);
  77351. effect.setArray("kernel", _this.kernel);
  77352. };
  77353. return _this;
  77354. }
  77355. // Statics
  77356. /**
  77357. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77358. */
  77359. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  77360. /**
  77361. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77362. */
  77363. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  77364. /**
  77365. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77366. */
  77367. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  77368. /**
  77369. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77370. */
  77371. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  77372. /**
  77373. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77374. */
  77375. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  77376. /**
  77377. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77378. */
  77379. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  77380. return ConvolutionPostProcess;
  77381. }(BABYLON.PostProcess));
  77382. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  77383. })(BABYLON || (BABYLON = {}));
  77384. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  77385. var BABYLON;
  77386. (function (BABYLON) {
  77387. var FilterPostProcess = /** @class */ (function (_super) {
  77388. __extends(FilterPostProcess, _super);
  77389. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  77390. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  77391. _this.kernelMatrix = kernelMatrix;
  77392. _this.onApply = function (effect) {
  77393. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  77394. };
  77395. return _this;
  77396. }
  77397. return FilterPostProcess;
  77398. }(BABYLON.PostProcess));
  77399. BABYLON.FilterPostProcess = FilterPostProcess;
  77400. })(BABYLON || (BABYLON = {}));
  77401. //# sourceMappingURL=babylon.filterPostProcess.js.map
  77402. var BABYLON;
  77403. (function (BABYLON) {
  77404. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  77405. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  77406. __extends(VolumetricLightScatteringPostProcess, _super);
  77407. /**
  77408. * @constructor
  77409. * @param {string} name - The post-process name
  77410. * @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)
  77411. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  77412. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  77413. * @param {number} samples - The post-process quality, default 100
  77414. * @param {number} samplingMode - The post-process filtering mode
  77415. * @param {BABYLON.Engine} engine - The babylon engine
  77416. * @param {boolean} reusable - If the post-process is reusable
  77417. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  77418. */
  77419. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  77420. if (samples === void 0) { samples = 100; }
  77421. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77422. 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;
  77423. _this._screenCoordinates = BABYLON.Vector2.Zero();
  77424. /**
  77425. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  77426. */
  77427. _this.customMeshPosition = BABYLON.Vector3.Zero();
  77428. /**
  77429. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  77430. */
  77431. _this.useCustomMeshPosition = false;
  77432. /**
  77433. * If the post-process should inverse the light scattering direction
  77434. */
  77435. _this.invert = true;
  77436. /**
  77437. * Array containing the excluded meshes not rendered in the internal pass
  77438. */
  77439. _this.excludedMeshes = new Array();
  77440. /**
  77441. * Controls the overall intensity of the post-process
  77442. */
  77443. _this.exposure = 0.3;
  77444. /**
  77445. * Dissipates each sample's contribution in range [0, 1]
  77446. */
  77447. _this.decay = 0.96815;
  77448. /**
  77449. * Controls the overall intensity of each sample
  77450. */
  77451. _this.weight = 0.58767;
  77452. /**
  77453. * Controls the density of each sample
  77454. */
  77455. _this.density = 0.926;
  77456. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  77457. engine = scene.getEngine();
  77458. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  77459. // Configure mesh
  77460. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  77461. // Configure
  77462. _this._createPass(scene, ratio.passRatio || ratio);
  77463. _this.onActivate = function (camera) {
  77464. if (!_this.isSupported) {
  77465. _this.dispose(camera);
  77466. }
  77467. _this.onActivate = null;
  77468. };
  77469. _this.onApplyObservable.add(function (effect) {
  77470. _this._updateMeshScreenCoordinates(scene);
  77471. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  77472. effect.setFloat("exposure", _this.exposure);
  77473. effect.setFloat("decay", _this.decay);
  77474. effect.setFloat("weight", _this.weight);
  77475. effect.setFloat("density", _this.density);
  77476. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  77477. });
  77478. return _this;
  77479. }
  77480. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  77481. get: function () {
  77482. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77483. return false;
  77484. },
  77485. set: function (useDiffuseColor) {
  77486. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77487. },
  77488. enumerable: true,
  77489. configurable: true
  77490. });
  77491. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  77492. return "VolumetricLightScatteringPostProcess";
  77493. };
  77494. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  77495. var mesh = subMesh.getMesh();
  77496. // Render this.mesh as default
  77497. if (mesh === this.mesh && mesh.material) {
  77498. return mesh.material.isReady(mesh);
  77499. }
  77500. var defines = [];
  77501. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77502. var material = subMesh.getMaterial();
  77503. // Alpha test
  77504. if (material) {
  77505. if (material.needAlphaTesting()) {
  77506. defines.push("#define ALPHATEST");
  77507. }
  77508. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77509. attribs.push(BABYLON.VertexBuffer.UVKind);
  77510. defines.push("#define UV1");
  77511. }
  77512. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77513. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77514. defines.push("#define UV2");
  77515. }
  77516. }
  77517. // Bones
  77518. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77519. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77520. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77521. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77522. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77523. }
  77524. else {
  77525. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77526. }
  77527. // Instances
  77528. if (useInstances) {
  77529. defines.push("#define INSTANCES");
  77530. attribs.push("world0");
  77531. attribs.push("world1");
  77532. attribs.push("world2");
  77533. attribs.push("world3");
  77534. }
  77535. // Get correct effect
  77536. var join = defines.join("\n");
  77537. if (this._cachedDefines !== join) {
  77538. this._cachedDefines = join;
  77539. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  77540. }
  77541. return this._volumetricLightScatteringPass.isReady();
  77542. };
  77543. /**
  77544. * Sets the new light position for light scattering effect
  77545. * @param {BABYLON.Vector3} The new custom light position
  77546. */
  77547. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  77548. this.customMeshPosition = position;
  77549. };
  77550. /**
  77551. * Returns the light position for light scattering effect
  77552. * @return {BABYLON.Vector3} The custom light position
  77553. */
  77554. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  77555. return this.customMeshPosition;
  77556. };
  77557. /**
  77558. * Disposes the internal assets and detaches the post-process from the camera
  77559. */
  77560. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  77561. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  77562. if (rttIndex !== -1) {
  77563. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  77564. }
  77565. this._volumetricLightScatteringRTT.dispose();
  77566. _super.prototype.dispose.call(this, camera);
  77567. };
  77568. /**
  77569. * Returns the render target texture used by the post-process
  77570. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  77571. */
  77572. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  77573. return this._volumetricLightScatteringRTT;
  77574. };
  77575. // Private methods
  77576. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  77577. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  77578. return true;
  77579. }
  77580. return false;
  77581. };
  77582. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  77583. var _this = this;
  77584. var engine = scene.getEngine();
  77585. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  77586. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77587. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77588. this._volumetricLightScatteringRTT.renderList = null;
  77589. this._volumetricLightScatteringRTT.renderParticles = false;
  77590. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  77591. var camera = this.getCamera();
  77592. if (camera) {
  77593. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77594. }
  77595. else {
  77596. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77597. }
  77598. // Custom render function for submeshes
  77599. var renderSubMesh = function (subMesh) {
  77600. var mesh = subMesh.getRenderingMesh();
  77601. if (_this._meshExcluded(mesh)) {
  77602. return;
  77603. }
  77604. var material = subMesh.getMaterial();
  77605. if (!material) {
  77606. return;
  77607. }
  77608. var scene = mesh.getScene();
  77609. var engine = scene.getEngine();
  77610. // Culling
  77611. engine.setState(material.backFaceCulling);
  77612. // Managing instances
  77613. var batch = mesh._getInstancesRenderList(subMesh._id);
  77614. if (batch.mustReturn) {
  77615. return;
  77616. }
  77617. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77618. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  77619. var effect = _this._volumetricLightScatteringPass;
  77620. if (mesh === _this.mesh) {
  77621. if (subMesh.effect) {
  77622. effect = subMesh.effect;
  77623. }
  77624. else {
  77625. effect = material.getEffect();
  77626. }
  77627. }
  77628. engine.enableEffect(effect);
  77629. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  77630. if (mesh === _this.mesh) {
  77631. material.bind(mesh.getWorldMatrix(), mesh);
  77632. }
  77633. else {
  77634. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  77635. // Alpha test
  77636. if (material && material.needAlphaTesting()) {
  77637. var alphaTexture = material.getAlphaTestTexture();
  77638. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  77639. if (alphaTexture) {
  77640. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77641. }
  77642. }
  77643. // Bones
  77644. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77645. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77646. }
  77647. }
  77648. // Draw
  77649. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  77650. }
  77651. };
  77652. // Render target texture callbacks
  77653. var savedSceneClearColor;
  77654. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  77655. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  77656. savedSceneClearColor = scene.clearColor;
  77657. scene.clearColor = sceneClearColor;
  77658. });
  77659. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  77660. scene.clearColor = savedSceneClearColor;
  77661. });
  77662. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77663. var engine = scene.getEngine();
  77664. var index;
  77665. if (depthOnlySubMeshes.length) {
  77666. engine.setColorWrite(false);
  77667. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77668. renderSubMesh(depthOnlySubMeshes.data[index]);
  77669. }
  77670. engine.setColorWrite(true);
  77671. }
  77672. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77673. renderSubMesh(opaqueSubMeshes.data[index]);
  77674. }
  77675. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77676. renderSubMesh(alphaTestSubMeshes.data[index]);
  77677. }
  77678. if (transparentSubMeshes.length) {
  77679. // Sort sub meshes
  77680. for (index = 0; index < transparentSubMeshes.length; index++) {
  77681. var submesh = transparentSubMeshes.data[index];
  77682. var boundingInfo = submesh.getBoundingInfo();
  77683. if (boundingInfo && scene.activeCamera) {
  77684. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  77685. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  77686. }
  77687. }
  77688. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  77689. sortedArray.sort(function (a, b) {
  77690. // Alpha index first
  77691. if (a._alphaIndex > b._alphaIndex) {
  77692. return 1;
  77693. }
  77694. if (a._alphaIndex < b._alphaIndex) {
  77695. return -1;
  77696. }
  77697. // Then distance to camera
  77698. if (a._distanceToCamera < b._distanceToCamera) {
  77699. return 1;
  77700. }
  77701. if (a._distanceToCamera > b._distanceToCamera) {
  77702. return -1;
  77703. }
  77704. return 0;
  77705. });
  77706. // Render sub meshes
  77707. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  77708. for (index = 0; index < sortedArray.length; index++) {
  77709. renderSubMesh(sortedArray[index]);
  77710. }
  77711. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77712. }
  77713. };
  77714. };
  77715. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  77716. var transform = scene.getTransformMatrix();
  77717. var meshPosition;
  77718. if (this.useCustomMeshPosition) {
  77719. meshPosition = this.customMeshPosition;
  77720. }
  77721. else if (this.attachedNode) {
  77722. meshPosition = this.attachedNode.position;
  77723. }
  77724. else {
  77725. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  77726. }
  77727. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  77728. this._screenCoordinates.x = pos.x / this._viewPort.width;
  77729. this._screenCoordinates.y = pos.y / this._viewPort.height;
  77730. if (this.invert)
  77731. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  77732. };
  77733. // Static methods
  77734. /**
  77735. * Creates a default mesh for the Volumeric Light Scattering post-process
  77736. * @param {string} The mesh name
  77737. * @param {BABYLON.Scene} The scene where to create the mesh
  77738. * @return {BABYLON.Mesh} the default mesh
  77739. */
  77740. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  77741. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  77742. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  77743. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  77744. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  77745. mesh.material = material;
  77746. return mesh;
  77747. };
  77748. __decorate([
  77749. BABYLON.serializeAsVector3()
  77750. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  77751. __decorate([
  77752. BABYLON.serialize()
  77753. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  77754. __decorate([
  77755. BABYLON.serialize()
  77756. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  77757. __decorate([
  77758. BABYLON.serializeAsMeshReference()
  77759. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  77760. __decorate([
  77761. BABYLON.serialize()
  77762. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  77763. __decorate([
  77764. BABYLON.serialize()
  77765. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  77766. __decorate([
  77767. BABYLON.serialize()
  77768. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  77769. __decorate([
  77770. BABYLON.serialize()
  77771. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  77772. __decorate([
  77773. BABYLON.serialize()
  77774. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  77775. return VolumetricLightScatteringPostProcess;
  77776. }(BABYLON.PostProcess));
  77777. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  77778. })(BABYLON || (BABYLON = {}));
  77779. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  77780. //
  77781. // This post-process allows the modification of rendered colors by using
  77782. // a 'look-up table' (LUT). This effect is also called Color Grading.
  77783. //
  77784. // The object needs to be provided an url to a texture containing the color
  77785. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  77786. // Use an image editing software to tweak the LUT to match your needs.
  77787. //
  77788. // For an example of a color LUT, see here:
  77789. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  77790. // For explanations on color grading, see here:
  77791. // http://udn.epicgames.com/Three/ColorGrading.html
  77792. //
  77793. var BABYLON;
  77794. (function (BABYLON) {
  77795. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  77796. __extends(ColorCorrectionPostProcess, _super);
  77797. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  77798. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  77799. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77800. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  77801. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77802. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77803. _this.onApply = function (effect) {
  77804. effect.setTexture("colorTable", _this._colorTableTexture);
  77805. };
  77806. return _this;
  77807. }
  77808. return ColorCorrectionPostProcess;
  77809. }(BABYLON.PostProcess));
  77810. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  77811. })(BABYLON || (BABYLON = {}));
  77812. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  77813. var BABYLON;
  77814. (function (BABYLON) {
  77815. /** Defines operator used for tonemapping */
  77816. var TonemappingOperator;
  77817. (function (TonemappingOperator) {
  77818. /** Hable */
  77819. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77820. /** Reinhard */
  77821. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77822. /** HejiDawson */
  77823. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77824. /** Photographic */
  77825. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77826. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77827. ;
  77828. /**
  77829. * Defines a post process to apply tone mapping
  77830. */
  77831. var TonemapPostProcess = /** @class */ (function (_super) {
  77832. __extends(TonemapPostProcess, _super);
  77833. /**
  77834. * Creates a new TonemapPostProcess
  77835. * @param name defines the name of the postprocess
  77836. * @param _operator defines the operator to use
  77837. * @param exposureAdjustment defines the required exposure adjustement
  77838. * @param camera defines the camera to use (can be null)
  77839. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77840. * @param engine defines the hosting engine (can be ignore if camera is set)
  77841. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77842. */
  77843. function TonemapPostProcess(name, _operator,
  77844. /** Defines the required exposure adjustement */
  77845. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77846. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77847. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77848. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77849. _this._operator = _operator;
  77850. _this.exposureAdjustment = exposureAdjustment;
  77851. var defines = "#define ";
  77852. if (_this._operator === TonemappingOperator.Hable)
  77853. defines += "HABLE_TONEMAPPING";
  77854. else if (_this._operator === TonemappingOperator.Reinhard)
  77855. defines += "REINHARD_TONEMAPPING";
  77856. else if (_this._operator === TonemappingOperator.HejiDawson)
  77857. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77858. else if (_this._operator === TonemappingOperator.Photographic)
  77859. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77860. //sadly a second call to create the effect.
  77861. _this.updateEffect(defines);
  77862. _this.onApply = function (effect) {
  77863. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77864. };
  77865. return _this;
  77866. }
  77867. return TonemapPostProcess;
  77868. }(BABYLON.PostProcess));
  77869. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77870. })(BABYLON || (BABYLON = {}));
  77871. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77872. var BABYLON;
  77873. (function (BABYLON) {
  77874. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77875. __extends(DisplayPassPostProcess, _super);
  77876. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77877. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77878. }
  77879. return DisplayPassPostProcess;
  77880. }(BABYLON.PostProcess));
  77881. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77882. })(BABYLON || (BABYLON = {}));
  77883. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77884. var BABYLON;
  77885. (function (BABYLON) {
  77886. var HighlightsPostProcess = /** @class */ (function (_super) {
  77887. __extends(HighlightsPostProcess, _super);
  77888. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77889. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77890. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77891. }
  77892. return HighlightsPostProcess;
  77893. }(BABYLON.PostProcess));
  77894. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77895. })(BABYLON || (BABYLON = {}));
  77896. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77897. var BABYLON;
  77898. (function (BABYLON) {
  77899. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77900. __extends(ImageProcessingPostProcess, _super);
  77901. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77902. if (camera === void 0) { camera = null; }
  77903. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77904. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77905. _this._fromLinearSpace = true;
  77906. /**
  77907. * Defines cache preventing GC.
  77908. */
  77909. _this._defines = {
  77910. IMAGEPROCESSING: false,
  77911. VIGNETTE: false,
  77912. VIGNETTEBLENDMODEMULTIPLY: false,
  77913. VIGNETTEBLENDMODEOPAQUE: false,
  77914. TONEMAPPING: false,
  77915. CONTRAST: false,
  77916. COLORCURVES: false,
  77917. COLORGRADING: false,
  77918. COLORGRADING3D: false,
  77919. FROMLINEARSPACE: false,
  77920. SAMPLER3DGREENDEPTH: false,
  77921. SAMPLER3DBGRMAP: false,
  77922. IMAGEPROCESSINGPOSTPROCESS: false,
  77923. EXPOSURE: false,
  77924. };
  77925. // Setup the configuration as forced by the constructor. This would then not force the
  77926. // scene materials output in linear space and let untouched the default forward pass.
  77927. if (imageProcessingConfiguration) {
  77928. imageProcessingConfiguration.applyByPostProcess = true;
  77929. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77930. // This will cause the shader to be compiled
  77931. _this.fromLinearSpace = false;
  77932. }
  77933. // Setup the default processing configuration to the scene.
  77934. else {
  77935. _this._attachImageProcessingConfiguration(null, true);
  77936. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77937. }
  77938. _this.onApply = function (effect) {
  77939. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77940. };
  77941. return _this;
  77942. }
  77943. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77944. /**
  77945. * Gets the image processing configuration used either in this material.
  77946. */
  77947. get: function () {
  77948. return this._imageProcessingConfiguration;
  77949. },
  77950. /**
  77951. * Sets the Default image processing configuration used either in the this material.
  77952. *
  77953. * If sets to null, the scene one is in use.
  77954. */
  77955. set: function (value) {
  77956. this._attachImageProcessingConfiguration(value);
  77957. },
  77958. enumerable: true,
  77959. configurable: true
  77960. });
  77961. /**
  77962. * Attaches a new image processing configuration to the PBR Material.
  77963. * @param configuration
  77964. */
  77965. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77966. var _this = this;
  77967. if (doNotBuild === void 0) { doNotBuild = false; }
  77968. if (configuration === this._imageProcessingConfiguration) {
  77969. return;
  77970. }
  77971. // Detaches observer.
  77972. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77973. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77974. }
  77975. // Pick the scene configuration if needed.
  77976. if (!configuration) {
  77977. var scene = null;
  77978. var engine = this.getEngine();
  77979. var camera = this.getCamera();
  77980. if (camera) {
  77981. scene = camera.getScene();
  77982. }
  77983. else if (engine && engine.scenes) {
  77984. var scenes = engine.scenes;
  77985. scene = scenes[scenes.length - 1];
  77986. }
  77987. else {
  77988. scene = BABYLON.Engine.LastCreatedScene;
  77989. }
  77990. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77991. }
  77992. else {
  77993. this._imageProcessingConfiguration = configuration;
  77994. }
  77995. // Attaches observer.
  77996. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77997. _this._updateParameters();
  77998. });
  77999. // Ensure the effect will be rebuilt.
  78000. if (!doNotBuild) {
  78001. this._updateParameters();
  78002. }
  78003. };
  78004. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  78005. /**
  78006. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78007. */
  78008. get: function () {
  78009. return this.imageProcessingConfiguration.colorCurves;
  78010. },
  78011. /**
  78012. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78013. */
  78014. set: function (value) {
  78015. this.imageProcessingConfiguration.colorCurves = value;
  78016. },
  78017. enumerable: true,
  78018. configurable: true
  78019. });
  78020. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  78021. /**
  78022. * Gets wether the color curves effect is enabled.
  78023. */
  78024. get: function () {
  78025. return this.imageProcessingConfiguration.colorCurvesEnabled;
  78026. },
  78027. /**
  78028. * Sets wether the color curves effect is enabled.
  78029. */
  78030. set: function (value) {
  78031. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  78032. },
  78033. enumerable: true,
  78034. configurable: true
  78035. });
  78036. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  78037. /**
  78038. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  78039. */
  78040. get: function () {
  78041. return this.imageProcessingConfiguration.colorGradingTexture;
  78042. },
  78043. /**
  78044. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  78045. */
  78046. set: function (value) {
  78047. this.imageProcessingConfiguration.colorGradingTexture = value;
  78048. },
  78049. enumerable: true,
  78050. configurable: true
  78051. });
  78052. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  78053. /**
  78054. * Gets wether the color grading effect is enabled.
  78055. */
  78056. get: function () {
  78057. return this.imageProcessingConfiguration.colorGradingEnabled;
  78058. },
  78059. /**
  78060. * Gets wether the color grading effect is enabled.
  78061. */
  78062. set: function (value) {
  78063. this.imageProcessingConfiguration.colorGradingEnabled = value;
  78064. },
  78065. enumerable: true,
  78066. configurable: true
  78067. });
  78068. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  78069. /**
  78070. * Gets exposure used in the effect.
  78071. */
  78072. get: function () {
  78073. return this.imageProcessingConfiguration.exposure;
  78074. },
  78075. /**
  78076. * Sets exposure used in the effect.
  78077. */
  78078. set: function (value) {
  78079. this.imageProcessingConfiguration.exposure = value;
  78080. },
  78081. enumerable: true,
  78082. configurable: true
  78083. });
  78084. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  78085. /**
  78086. * Gets wether tonemapping is enabled or not.
  78087. */
  78088. get: function () {
  78089. return this._imageProcessingConfiguration.toneMappingEnabled;
  78090. },
  78091. /**
  78092. * Sets wether tonemapping is enabled or not
  78093. */
  78094. set: function (value) {
  78095. this._imageProcessingConfiguration.toneMappingEnabled = value;
  78096. },
  78097. enumerable: true,
  78098. configurable: true
  78099. });
  78100. ;
  78101. ;
  78102. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  78103. /**
  78104. * Gets contrast used in the effect.
  78105. */
  78106. get: function () {
  78107. return this.imageProcessingConfiguration.contrast;
  78108. },
  78109. /**
  78110. * Sets contrast used in the effect.
  78111. */
  78112. set: function (value) {
  78113. this.imageProcessingConfiguration.contrast = value;
  78114. },
  78115. enumerable: true,
  78116. configurable: true
  78117. });
  78118. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  78119. /**
  78120. * Gets Vignette stretch size.
  78121. */
  78122. get: function () {
  78123. return this.imageProcessingConfiguration.vignetteStretch;
  78124. },
  78125. /**
  78126. * Sets Vignette stretch size.
  78127. */
  78128. set: function (value) {
  78129. this.imageProcessingConfiguration.vignetteStretch = value;
  78130. },
  78131. enumerable: true,
  78132. configurable: true
  78133. });
  78134. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  78135. /**
  78136. * Gets Vignette centre X Offset.
  78137. */
  78138. get: function () {
  78139. return this.imageProcessingConfiguration.vignetteCentreX;
  78140. },
  78141. /**
  78142. * Sets Vignette centre X Offset.
  78143. */
  78144. set: function (value) {
  78145. this.imageProcessingConfiguration.vignetteCentreX = value;
  78146. },
  78147. enumerable: true,
  78148. configurable: true
  78149. });
  78150. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  78151. /**
  78152. * Gets Vignette centre Y Offset.
  78153. */
  78154. get: function () {
  78155. return this.imageProcessingConfiguration.vignetteCentreY;
  78156. },
  78157. /**
  78158. * Sets Vignette centre Y Offset.
  78159. */
  78160. set: function (value) {
  78161. this.imageProcessingConfiguration.vignetteCentreY = value;
  78162. },
  78163. enumerable: true,
  78164. configurable: true
  78165. });
  78166. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  78167. /**
  78168. * Gets Vignette weight or intensity of the vignette effect.
  78169. */
  78170. get: function () {
  78171. return this.imageProcessingConfiguration.vignetteWeight;
  78172. },
  78173. /**
  78174. * Sets Vignette weight or intensity of the vignette effect.
  78175. */
  78176. set: function (value) {
  78177. this.imageProcessingConfiguration.vignetteWeight = value;
  78178. },
  78179. enumerable: true,
  78180. configurable: true
  78181. });
  78182. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  78183. /**
  78184. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78185. * if vignetteEnabled is set to true.
  78186. */
  78187. get: function () {
  78188. return this.imageProcessingConfiguration.vignetteColor;
  78189. },
  78190. /**
  78191. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78192. * if vignetteEnabled is set to true.
  78193. */
  78194. set: function (value) {
  78195. this.imageProcessingConfiguration.vignetteColor = value;
  78196. },
  78197. enumerable: true,
  78198. configurable: true
  78199. });
  78200. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  78201. /**
  78202. * Gets Camera field of view used by the Vignette effect.
  78203. */
  78204. get: function () {
  78205. return this.imageProcessingConfiguration.vignetteCameraFov;
  78206. },
  78207. /**
  78208. * Sets Camera field of view used by the Vignette effect.
  78209. */
  78210. set: function (value) {
  78211. this.imageProcessingConfiguration.vignetteCameraFov = value;
  78212. },
  78213. enumerable: true,
  78214. configurable: true
  78215. });
  78216. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  78217. /**
  78218. * Gets the vignette blend mode allowing different kind of effect.
  78219. */
  78220. get: function () {
  78221. return this.imageProcessingConfiguration.vignetteBlendMode;
  78222. },
  78223. /**
  78224. * Sets the vignette blend mode allowing different kind of effect.
  78225. */
  78226. set: function (value) {
  78227. this.imageProcessingConfiguration.vignetteBlendMode = value;
  78228. },
  78229. enumerable: true,
  78230. configurable: true
  78231. });
  78232. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  78233. /**
  78234. * Gets wether the vignette effect is enabled.
  78235. */
  78236. get: function () {
  78237. return this.imageProcessingConfiguration.vignetteEnabled;
  78238. },
  78239. /**
  78240. * Sets wether the vignette effect is enabled.
  78241. */
  78242. set: function (value) {
  78243. this.imageProcessingConfiguration.vignetteEnabled = value;
  78244. },
  78245. enumerable: true,
  78246. configurable: true
  78247. });
  78248. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  78249. /**
  78250. * Gets wether the input of the processing is in Gamma or Linear Space.
  78251. */
  78252. get: function () {
  78253. return this._fromLinearSpace;
  78254. },
  78255. /**
  78256. * Sets wether the input of the processing is in Gamma or Linear Space.
  78257. */
  78258. set: function (value) {
  78259. if (this._fromLinearSpace === value) {
  78260. return;
  78261. }
  78262. this._fromLinearSpace = value;
  78263. this._updateParameters();
  78264. },
  78265. enumerable: true,
  78266. configurable: true
  78267. });
  78268. ImageProcessingPostProcess.prototype.getClassName = function () {
  78269. return "ImageProcessingPostProcess";
  78270. };
  78271. ImageProcessingPostProcess.prototype._updateParameters = function () {
  78272. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  78273. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  78274. var defines = "";
  78275. for (var define in this._defines) {
  78276. if (this._defines[define]) {
  78277. defines += "#define " + define + ";\r\n";
  78278. }
  78279. }
  78280. var samplers = ["textureSampler"];
  78281. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  78282. var uniforms = ["scale"];
  78283. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  78284. this.updateEffect(defines, uniforms, samplers);
  78285. };
  78286. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  78287. _super.prototype.dispose.call(this, camera);
  78288. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78289. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78290. }
  78291. this.imageProcessingConfiguration.applyByPostProcess = false;
  78292. };
  78293. __decorate([
  78294. BABYLON.serialize()
  78295. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  78296. return ImageProcessingPostProcess;
  78297. }(BABYLON.PostProcess));
  78298. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  78299. })(BABYLON || (BABYLON = {}));
  78300. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  78301. var BABYLON;
  78302. (function (BABYLON) {
  78303. /**
  78304. * Class used to store bone information
  78305. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78306. */
  78307. var Bone = /** @class */ (function (_super) {
  78308. __extends(Bone, _super);
  78309. /**
  78310. * Create a new bone
  78311. * @param name defines the bone name
  78312. * @param skeleton defines the parent skeleton
  78313. * @param parentBone defines the parent (can be null if the bone is the root)
  78314. * @param localMatrix defines the local matrix
  78315. * @param restPose defines the rest pose matrix
  78316. * @param baseMatrix defines the base matrix
  78317. * @param index defines index of the bone in the hiearchy
  78318. */
  78319. function Bone(
  78320. /**
  78321. * defines the bone name
  78322. */
  78323. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  78324. if (parentBone === void 0) { parentBone = null; }
  78325. if (localMatrix === void 0) { localMatrix = null; }
  78326. if (restPose === void 0) { restPose = null; }
  78327. if (baseMatrix === void 0) { baseMatrix = null; }
  78328. if (index === void 0) { index = null; }
  78329. var _this = _super.call(this, name, skeleton.getScene()) || this;
  78330. _this.name = name;
  78331. /**
  78332. * Gets the list of child bones
  78333. */
  78334. _this.children = new Array();
  78335. /** Gets the animations associated with this bone */
  78336. _this.animations = new Array();
  78337. /**
  78338. * @hidden Internal only
  78339. * Set this value to map this bone to a different index in the transform matrices
  78340. * Set this value to -1 to exclude the bone from the transform matrices
  78341. */
  78342. _this._index = null;
  78343. _this._absoluteTransform = new BABYLON.Matrix();
  78344. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  78345. _this._scalingDeterminant = 1;
  78346. _this._worldTransform = new BABYLON.Matrix();
  78347. _this._needToDecompose = true;
  78348. _this._needToCompose = false;
  78349. _this._skeleton = skeleton;
  78350. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  78351. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  78352. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  78353. _this._index = index;
  78354. skeleton.bones.push(_this);
  78355. _this.setParent(parentBone, false);
  78356. if (baseMatrix || localMatrix) {
  78357. _this._updateDifferenceMatrix();
  78358. }
  78359. return _this;
  78360. }
  78361. Object.defineProperty(Bone.prototype, "_matrix", {
  78362. /** @hidden */
  78363. get: function () {
  78364. this._compose();
  78365. return this._localMatrix;
  78366. },
  78367. /** @hidden */
  78368. set: function (value) {
  78369. this._localMatrix.copyFrom(value);
  78370. this._needToDecompose = true;
  78371. },
  78372. enumerable: true,
  78373. configurable: true
  78374. });
  78375. // Members
  78376. /**
  78377. * Gets the parent skeleton
  78378. * @returns a skeleton
  78379. */
  78380. Bone.prototype.getSkeleton = function () {
  78381. return this._skeleton;
  78382. };
  78383. /**
  78384. * Gets parent bone
  78385. * @returns a bone or null if the bone is the root of the bone hierarchy
  78386. */
  78387. Bone.prototype.getParent = function () {
  78388. return this._parent;
  78389. };
  78390. /**
  78391. * Sets the parent bone
  78392. * @param parent defines the parent (can be null if the bone is the root)
  78393. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78394. */
  78395. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  78396. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78397. if (this._parent === parent) {
  78398. return;
  78399. }
  78400. if (this._parent) {
  78401. var index = this._parent.children.indexOf(this);
  78402. if (index !== -1) {
  78403. this._parent.children.splice(index, 1);
  78404. }
  78405. }
  78406. this._parent = parent;
  78407. if (this._parent) {
  78408. this._parent.children.push(this);
  78409. }
  78410. if (updateDifferenceMatrix) {
  78411. this._updateDifferenceMatrix();
  78412. }
  78413. this.markAsDirty();
  78414. };
  78415. /**
  78416. * Gets the local matrix
  78417. * @returns a matrix
  78418. */
  78419. Bone.prototype.getLocalMatrix = function () {
  78420. this._compose();
  78421. return this._localMatrix;
  78422. };
  78423. /**
  78424. * Gets the base matrix (initial matrix which remains unchanged)
  78425. * @returns a matrix
  78426. */
  78427. Bone.prototype.getBaseMatrix = function () {
  78428. return this._baseMatrix;
  78429. };
  78430. /**
  78431. * Gets the rest pose matrix
  78432. * @returns a matrix
  78433. */
  78434. Bone.prototype.getRestPose = function () {
  78435. return this._restPose;
  78436. };
  78437. /**
  78438. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  78439. */
  78440. Bone.prototype.getWorldMatrix = function () {
  78441. return this._worldTransform;
  78442. };
  78443. /**
  78444. * Sets the local matrix to rest pose matrix
  78445. */
  78446. Bone.prototype.returnToRest = function () {
  78447. this.updateMatrix(this._restPose.clone());
  78448. };
  78449. /**
  78450. * Gets the inverse of the absolute transform matrix.
  78451. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  78452. * @returns a matrix
  78453. */
  78454. Bone.prototype.getInvertedAbsoluteTransform = function () {
  78455. return this._invertedAbsoluteTransform;
  78456. };
  78457. /**
  78458. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  78459. * @returns a matrix
  78460. */
  78461. Bone.prototype.getAbsoluteTransform = function () {
  78462. return this._absoluteTransform;
  78463. };
  78464. Object.defineProperty(Bone.prototype, "position", {
  78465. // Properties (matches AbstractMesh properties)
  78466. /** Gets or sets current position (in local space) */
  78467. get: function () {
  78468. this._decompose();
  78469. return this._localPosition;
  78470. },
  78471. set: function (newPosition) {
  78472. this._decompose();
  78473. this._localPosition.copyFrom(newPosition);
  78474. this._markAsDirtyAndCompose();
  78475. },
  78476. enumerable: true,
  78477. configurable: true
  78478. });
  78479. Object.defineProperty(Bone.prototype, "rotation", {
  78480. /** Gets or sets current rotation (in local space) */
  78481. get: function () {
  78482. return this.getRotation();
  78483. },
  78484. set: function (newRotation) {
  78485. this.setRotation(newRotation);
  78486. },
  78487. enumerable: true,
  78488. configurable: true
  78489. });
  78490. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  78491. /** Gets or sets current rotation quaternion (in local space) */
  78492. get: function () {
  78493. this._decompose();
  78494. return this._localRotation;
  78495. },
  78496. set: function (newRotation) {
  78497. this.setRotationQuaternion(newRotation);
  78498. },
  78499. enumerable: true,
  78500. configurable: true
  78501. });
  78502. Object.defineProperty(Bone.prototype, "scaling", {
  78503. /** Gets or sets current scaling (in local space) */
  78504. get: function () {
  78505. return this.getScale();
  78506. },
  78507. set: function (newScaling) {
  78508. this.setScale(newScaling);
  78509. },
  78510. enumerable: true,
  78511. configurable: true
  78512. });
  78513. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  78514. /**
  78515. * Gets the animation properties override
  78516. */
  78517. get: function () {
  78518. return this._skeleton.animationPropertiesOverride;
  78519. },
  78520. enumerable: true,
  78521. configurable: true
  78522. });
  78523. // Methods
  78524. Bone.prototype._decompose = function () {
  78525. if (!this._needToDecompose) {
  78526. return;
  78527. }
  78528. this._needToDecompose = false;
  78529. if (!this._localScaling) {
  78530. this._localScaling = BABYLON.Vector3.Zero();
  78531. this._localRotation = BABYLON.Quaternion.Zero();
  78532. this._localPosition = BABYLON.Vector3.Zero();
  78533. }
  78534. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  78535. };
  78536. Bone.prototype._compose = function () {
  78537. if (!this._needToCompose) {
  78538. return;
  78539. }
  78540. this._needToCompose = false;
  78541. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  78542. };
  78543. /**
  78544. * Update the base and local matrices
  78545. * @param matrix defines the new base or local matrix
  78546. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78547. * @param updateLocalMatrix defines if the local matrix should be updated
  78548. */
  78549. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  78550. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78551. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  78552. this._baseMatrix.copyFrom(matrix);
  78553. if (updateDifferenceMatrix) {
  78554. this._updateDifferenceMatrix();
  78555. }
  78556. if (updateLocalMatrix) {
  78557. this._localMatrix.copyFrom(matrix);
  78558. this._markAsDirtyAndDecompose();
  78559. }
  78560. else {
  78561. this.markAsDirty();
  78562. }
  78563. };
  78564. /** @hidden */
  78565. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  78566. if (updateChildren === void 0) { updateChildren = true; }
  78567. if (!rootMatrix) {
  78568. rootMatrix = this._baseMatrix;
  78569. }
  78570. if (this._parent) {
  78571. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78572. }
  78573. else {
  78574. this._absoluteTransform.copyFrom(rootMatrix);
  78575. }
  78576. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  78577. if (updateChildren) {
  78578. for (var index = 0; index < this.children.length; index++) {
  78579. this.children[index]._updateDifferenceMatrix();
  78580. }
  78581. }
  78582. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  78583. };
  78584. /**
  78585. * Flag the bone as dirty (Forcing it to update everything)
  78586. */
  78587. Bone.prototype.markAsDirty = function () {
  78588. this._currentRenderId++;
  78589. this._childRenderId++;
  78590. this._skeleton._markAsDirty();
  78591. };
  78592. Bone.prototype._markAsDirtyAndCompose = function () {
  78593. this.markAsDirty();
  78594. this._needToCompose = true;
  78595. };
  78596. Bone.prototype._markAsDirtyAndDecompose = function () {
  78597. this.markAsDirty();
  78598. this._needToDecompose = true;
  78599. };
  78600. /**
  78601. * Copy an animation range from another bone
  78602. * @param source defines the source bone
  78603. * @param rangeName defines the range name to copy
  78604. * @param frameOffset defines the frame offset
  78605. * @param rescaleAsRequired defines if rescaling must be applied if required
  78606. * @param skelDimensionsRatio defines the scaling ratio
  78607. * @returns true if operation was successful
  78608. */
  78609. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  78610. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78611. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  78612. // all animation may be coming from a library skeleton, so may need to create animation
  78613. if (this.animations.length === 0) {
  78614. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  78615. this.animations[0].setKeys([]);
  78616. }
  78617. // get animation info / verify there is such a range from the source bone
  78618. var sourceRange = source.animations[0].getRange(rangeName);
  78619. if (!sourceRange) {
  78620. return false;
  78621. }
  78622. var from = sourceRange.from;
  78623. var to = sourceRange.to;
  78624. var sourceKeys = source.animations[0].getKeys();
  78625. // rescaling prep
  78626. var sourceBoneLength = source.length;
  78627. var sourceParent = source.getParent();
  78628. var parent = this.getParent();
  78629. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  78630. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  78631. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  78632. var destKeys = this.animations[0].getKeys();
  78633. // loop vars declaration
  78634. var orig;
  78635. var origTranslation;
  78636. var mat;
  78637. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  78638. orig = sourceKeys[key];
  78639. if (orig.frame >= from && orig.frame <= to) {
  78640. if (rescaleAsRequired) {
  78641. mat = orig.value.clone();
  78642. // scale based on parent ratio, when bone has parent
  78643. if (parentScalingReqd) {
  78644. origTranslation = mat.getTranslation();
  78645. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  78646. // scale based on skeleton dimension ratio when root bone, and value is passed
  78647. }
  78648. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  78649. origTranslation = mat.getTranslation();
  78650. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  78651. // use original when root bone, and no data for skelDimensionsRatio
  78652. }
  78653. else {
  78654. mat = orig.value;
  78655. }
  78656. }
  78657. else {
  78658. mat = orig.value;
  78659. }
  78660. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  78661. }
  78662. }
  78663. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  78664. return true;
  78665. };
  78666. /**
  78667. * Translate the bone in local or world space
  78668. * @param vec The amount to translate the bone
  78669. * @param space The space that the translation is in
  78670. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78671. */
  78672. Bone.prototype.translate = function (vec, space, mesh) {
  78673. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78674. var lm = this.getLocalMatrix();
  78675. if (space == BABYLON.Space.LOCAL) {
  78676. lm.m[12] += vec.x;
  78677. lm.m[13] += vec.y;
  78678. lm.m[14] += vec.z;
  78679. }
  78680. else {
  78681. var wm = null;
  78682. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78683. if (mesh) {
  78684. wm = mesh.getWorldMatrix();
  78685. }
  78686. this._skeleton.computeAbsoluteTransforms();
  78687. var tmat = Bone._tmpMats[0];
  78688. var tvec = Bone._tmpVecs[0];
  78689. if (this._parent) {
  78690. if (mesh && wm) {
  78691. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78692. tmat.multiplyToRef(wm, tmat);
  78693. }
  78694. else {
  78695. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78696. }
  78697. }
  78698. tmat.m[12] = 0;
  78699. tmat.m[13] = 0;
  78700. tmat.m[14] = 0;
  78701. tmat.invert();
  78702. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  78703. lm.m[12] += tvec.x;
  78704. lm.m[13] += tvec.y;
  78705. lm.m[14] += tvec.z;
  78706. }
  78707. this._markAsDirtyAndDecompose();
  78708. };
  78709. /**
  78710. * Set the postion of the bone in local or world space
  78711. * @param position The position to set the bone
  78712. * @param space The space that the position is in
  78713. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78714. */
  78715. Bone.prototype.setPosition = function (position, space, mesh) {
  78716. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78717. var lm = this.getLocalMatrix();
  78718. if (space == BABYLON.Space.LOCAL) {
  78719. lm.m[12] = position.x;
  78720. lm.m[13] = position.y;
  78721. lm.m[14] = position.z;
  78722. }
  78723. else {
  78724. var wm = null;
  78725. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78726. if (mesh) {
  78727. wm = mesh.getWorldMatrix();
  78728. }
  78729. this._skeleton.computeAbsoluteTransforms();
  78730. var tmat = Bone._tmpMats[0];
  78731. var vec = Bone._tmpVecs[0];
  78732. if (this._parent) {
  78733. if (mesh && wm) {
  78734. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78735. tmat.multiplyToRef(wm, tmat);
  78736. }
  78737. else {
  78738. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78739. }
  78740. }
  78741. tmat.invert();
  78742. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  78743. lm.m[12] = vec.x;
  78744. lm.m[13] = vec.y;
  78745. lm.m[14] = vec.z;
  78746. }
  78747. this._markAsDirtyAndDecompose();
  78748. };
  78749. /**
  78750. * Set the absolute position of the bone (world space)
  78751. * @param position The position to set the bone
  78752. * @param mesh The mesh that this bone is attached to
  78753. */
  78754. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  78755. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  78756. };
  78757. /**
  78758. * Scale the bone on the x, y and z axes (in local space)
  78759. * @param x The amount to scale the bone on the x axis
  78760. * @param y The amount to scale the bone on the y axis
  78761. * @param z The amount to scale the bone on the z axis
  78762. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  78763. */
  78764. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  78765. if (scaleChildren === void 0) { scaleChildren = false; }
  78766. var locMat = this.getLocalMatrix();
  78767. // Apply new scaling on top of current local matrix
  78768. var scaleMat = Bone._tmpMats[0];
  78769. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  78770. scaleMat.multiplyToRef(locMat, locMat);
  78771. // Invert scaling matrix and apply the inverse to all children
  78772. scaleMat.invert();
  78773. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  78774. var child = _a[_i];
  78775. var cm = child.getLocalMatrix();
  78776. cm.multiplyToRef(scaleMat, cm);
  78777. cm.m[12] *= x;
  78778. cm.m[13] *= y;
  78779. cm.m[14] *= z;
  78780. child._markAsDirtyAndDecompose();
  78781. }
  78782. this._markAsDirtyAndDecompose();
  78783. if (scaleChildren) {
  78784. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  78785. var child = _c[_b];
  78786. child.scale(x, y, z, scaleChildren);
  78787. }
  78788. }
  78789. };
  78790. /**
  78791. * Set the bone scaling in local space
  78792. * @param scale defines the scaling vector
  78793. */
  78794. Bone.prototype.setScale = function (scale) {
  78795. this._decompose();
  78796. this._localScaling.copyFrom(scale);
  78797. this._markAsDirtyAndCompose();
  78798. };
  78799. /**
  78800. * Gets the current scaling in local space
  78801. * @returns the current scaling vector
  78802. */
  78803. Bone.prototype.getScale = function () {
  78804. this._decompose();
  78805. return this._localScaling;
  78806. };
  78807. /**
  78808. * Gets the current scaling in local space and stores it in a target vector
  78809. * @param result defines the target vector
  78810. */
  78811. Bone.prototype.getScaleToRef = function (result) {
  78812. this._decompose();
  78813. result.copyFrom(this._localScaling);
  78814. };
  78815. /**
  78816. * Set the yaw, pitch, and roll of the bone in local or world space
  78817. * @param yaw The rotation of the bone on the y axis
  78818. * @param pitch The rotation of the bone on the x axis
  78819. * @param roll The rotation of the bone on the z axis
  78820. * @param space The space that the axes of rotation are in
  78821. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78822. */
  78823. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78824. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78825. if (space === BABYLON.Space.LOCAL) {
  78826. var quat = Bone._tmpQuat;
  78827. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78828. this.setRotationQuaternion(quat, space, mesh);
  78829. return;
  78830. }
  78831. var rotMatInv = Bone._tmpMats[0];
  78832. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78833. return;
  78834. }
  78835. var rotMat = Bone._tmpMats[1];
  78836. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78837. rotMatInv.multiplyToRef(rotMat, rotMat);
  78838. this._rotateWithMatrix(rotMat, space, mesh);
  78839. };
  78840. /**
  78841. * Add a rotation to the bone on an axis in local or world space
  78842. * @param axis The axis to rotate the bone on
  78843. * @param amount The amount to rotate the bone
  78844. * @param space The space that the axis is in
  78845. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78846. */
  78847. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78848. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78849. var rmat = Bone._tmpMats[0];
  78850. rmat.m[12] = 0;
  78851. rmat.m[13] = 0;
  78852. rmat.m[14] = 0;
  78853. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78854. this._rotateWithMatrix(rmat, space, mesh);
  78855. };
  78856. /**
  78857. * Set the rotation of the bone to a particular axis angle in local or world space
  78858. * @param axis The axis to rotate the bone on
  78859. * @param angle The angle that the bone should be rotated to
  78860. * @param space The space that the axis is in
  78861. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78862. */
  78863. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78864. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78865. if (space === BABYLON.Space.LOCAL) {
  78866. var quat = Bone._tmpQuat;
  78867. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78868. this.setRotationQuaternion(quat, space, mesh);
  78869. return;
  78870. }
  78871. var rotMatInv = Bone._tmpMats[0];
  78872. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78873. return;
  78874. }
  78875. var rotMat = Bone._tmpMats[1];
  78876. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78877. rotMatInv.multiplyToRef(rotMat, rotMat);
  78878. this._rotateWithMatrix(rotMat, space, mesh);
  78879. };
  78880. /**
  78881. * Set the euler rotation of the bone in local of world space
  78882. * @param rotation The euler rotation that the bone should be set to
  78883. * @param space The space that the rotation is in
  78884. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78885. */
  78886. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78887. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78888. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78889. };
  78890. /**
  78891. * Set the quaternion rotation of the bone in local of world space
  78892. * @param quat The quaternion rotation that the bone should be set to
  78893. * @param space The space that the rotation is in
  78894. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78895. */
  78896. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78897. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78898. if (space === BABYLON.Space.LOCAL) {
  78899. this._decompose();
  78900. this._localRotation.copyFrom(quat);
  78901. this._markAsDirtyAndCompose();
  78902. return;
  78903. }
  78904. var rotMatInv = Bone._tmpMats[0];
  78905. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78906. return;
  78907. }
  78908. var rotMat = Bone._tmpMats[1];
  78909. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78910. rotMatInv.multiplyToRef(rotMat, rotMat);
  78911. this._rotateWithMatrix(rotMat, space, mesh);
  78912. };
  78913. /**
  78914. * Set the rotation matrix of the bone in local of world space
  78915. * @param rotMat The rotation matrix that the bone should be set to
  78916. * @param space The space that the rotation is in
  78917. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78918. */
  78919. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78920. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78921. if (space === BABYLON.Space.LOCAL) {
  78922. var quat = Bone._tmpQuat;
  78923. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78924. this.setRotationQuaternion(quat, space, mesh);
  78925. return;
  78926. }
  78927. var rotMatInv = Bone._tmpMats[0];
  78928. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78929. return;
  78930. }
  78931. var rotMat2 = Bone._tmpMats[1];
  78932. rotMat2.copyFrom(rotMat);
  78933. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78934. this._rotateWithMatrix(rotMat2, space, mesh);
  78935. };
  78936. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78937. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78938. var lmat = this.getLocalMatrix();
  78939. var lx = lmat.m[12];
  78940. var ly = lmat.m[13];
  78941. var lz = lmat.m[14];
  78942. var parent = this.getParent();
  78943. var parentScale = Bone._tmpMats[3];
  78944. var parentScaleInv = Bone._tmpMats[4];
  78945. if (parent && space == BABYLON.Space.WORLD) {
  78946. if (mesh) {
  78947. parentScale.copyFrom(mesh.getWorldMatrix());
  78948. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78949. }
  78950. else {
  78951. parentScale.copyFrom(parent.getAbsoluteTransform());
  78952. }
  78953. parentScaleInv.copyFrom(parentScale);
  78954. parentScaleInv.invert();
  78955. lmat.multiplyToRef(parentScale, lmat);
  78956. lmat.multiplyToRef(rmat, lmat);
  78957. lmat.multiplyToRef(parentScaleInv, lmat);
  78958. }
  78959. else {
  78960. if (space == BABYLON.Space.WORLD && mesh) {
  78961. parentScale.copyFrom(mesh.getWorldMatrix());
  78962. parentScaleInv.copyFrom(parentScale);
  78963. parentScaleInv.invert();
  78964. lmat.multiplyToRef(parentScale, lmat);
  78965. lmat.multiplyToRef(rmat, lmat);
  78966. lmat.multiplyToRef(parentScaleInv, lmat);
  78967. }
  78968. else {
  78969. lmat.multiplyToRef(rmat, lmat);
  78970. }
  78971. }
  78972. lmat.m[12] = lx;
  78973. lmat.m[13] = ly;
  78974. lmat.m[14] = lz;
  78975. this.computeAbsoluteTransforms();
  78976. this._markAsDirtyAndDecompose();
  78977. };
  78978. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78979. var scaleMatrix = Bone._tmpMats[2];
  78980. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78981. if (mesh) {
  78982. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78983. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78984. }
  78985. rotMatInv.invert();
  78986. if (isNaN(rotMatInv.m[0])) {
  78987. // Matrix failed to invert.
  78988. // This can happen if scale is zero for example.
  78989. return false;
  78990. }
  78991. scaleMatrix.m[0] *= this._scalingDeterminant;
  78992. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78993. return true;
  78994. };
  78995. /**
  78996. * Get the position of the bone in local or world space
  78997. * @param space The space that the returned position is in
  78998. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78999. * @returns The position of the bone
  79000. */
  79001. Bone.prototype.getPosition = function (space, mesh) {
  79002. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79003. if (mesh === void 0) { mesh = null; }
  79004. var pos = BABYLON.Vector3.Zero();
  79005. this.getPositionToRef(space, mesh, pos);
  79006. return pos;
  79007. };
  79008. /**
  79009. * Copy the position of the bone to a vector3 in local or world space
  79010. * @param space The space that the returned position is in
  79011. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79012. * @param result The vector3 to copy the position to
  79013. */
  79014. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  79015. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79016. if (space == BABYLON.Space.LOCAL) {
  79017. var lm = this.getLocalMatrix();
  79018. result.x = lm.m[12];
  79019. result.y = lm.m[13];
  79020. result.z = lm.m[14];
  79021. }
  79022. else {
  79023. var wm = null;
  79024. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79025. if (mesh) {
  79026. wm = mesh.getWorldMatrix();
  79027. }
  79028. this._skeleton.computeAbsoluteTransforms();
  79029. var tmat = Bone._tmpMats[0];
  79030. if (mesh && wm) {
  79031. tmat.copyFrom(this.getAbsoluteTransform());
  79032. tmat.multiplyToRef(wm, tmat);
  79033. }
  79034. else {
  79035. tmat = this.getAbsoluteTransform();
  79036. }
  79037. result.x = tmat.m[12];
  79038. result.y = tmat.m[13];
  79039. result.z = tmat.m[14];
  79040. }
  79041. };
  79042. /**
  79043. * Get the absolute position of the bone (world space)
  79044. * @param mesh The mesh that this bone is attached to
  79045. * @returns The absolute position of the bone
  79046. */
  79047. Bone.prototype.getAbsolutePosition = function (mesh) {
  79048. if (mesh === void 0) { mesh = null; }
  79049. var pos = BABYLON.Vector3.Zero();
  79050. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  79051. return pos;
  79052. };
  79053. /**
  79054. * Copy the absolute position of the bone (world space) to the result param
  79055. * @param mesh The mesh that this bone is attached to
  79056. * @param result The vector3 to copy the absolute position to
  79057. */
  79058. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  79059. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  79060. };
  79061. /**
  79062. * Compute the absolute transforms of this bone and its children
  79063. */
  79064. Bone.prototype.computeAbsoluteTransforms = function () {
  79065. this._compose();
  79066. if (this._parent) {
  79067. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79068. }
  79069. else {
  79070. this._absoluteTransform.copyFrom(this._localMatrix);
  79071. var poseMatrix = this._skeleton.getPoseMatrix();
  79072. if (poseMatrix) {
  79073. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  79074. }
  79075. }
  79076. var children = this.children;
  79077. var len = children.length;
  79078. for (var i = 0; i < len; i++) {
  79079. children[i].computeAbsoluteTransforms();
  79080. }
  79081. };
  79082. /**
  79083. * Get the world direction from an axis that is in the local space of the bone
  79084. * @param localAxis The local direction that is used to compute the world direction
  79085. * @param mesh The mesh that this bone is attached to
  79086. * @returns The world direction
  79087. */
  79088. Bone.prototype.getDirection = function (localAxis, mesh) {
  79089. if (mesh === void 0) { mesh = null; }
  79090. var result = BABYLON.Vector3.Zero();
  79091. this.getDirectionToRef(localAxis, mesh, result);
  79092. return result;
  79093. };
  79094. /**
  79095. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  79096. * @param localAxis The local direction that is used to compute the world direction
  79097. * @param mesh The mesh that this bone is attached to
  79098. * @param result The vector3 that the world direction will be copied to
  79099. */
  79100. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  79101. if (mesh === void 0) { mesh = null; }
  79102. var wm = null;
  79103. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79104. if (mesh) {
  79105. wm = mesh.getWorldMatrix();
  79106. }
  79107. this._skeleton.computeAbsoluteTransforms();
  79108. var mat = Bone._tmpMats[0];
  79109. mat.copyFrom(this.getAbsoluteTransform());
  79110. if (mesh && wm) {
  79111. mat.multiplyToRef(wm, mat);
  79112. }
  79113. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  79114. result.normalize();
  79115. };
  79116. /**
  79117. * Get the euler rotation of the bone in local or world space
  79118. * @param space The space that the rotation should be in
  79119. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79120. * @returns The euler rotation
  79121. */
  79122. Bone.prototype.getRotation = function (space, mesh) {
  79123. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79124. if (mesh === void 0) { mesh = null; }
  79125. var result = BABYLON.Vector3.Zero();
  79126. this.getRotationToRef(space, mesh, result);
  79127. return result;
  79128. };
  79129. /**
  79130. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  79131. * @param space The space that the rotation should be in
  79132. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79133. * @param result The vector3 that the rotation should be copied to
  79134. */
  79135. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  79136. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79137. if (mesh === void 0) { mesh = null; }
  79138. var quat = Bone._tmpQuat;
  79139. this.getRotationQuaternionToRef(space, mesh, quat);
  79140. quat.toEulerAnglesToRef(result);
  79141. };
  79142. /**
  79143. * Get the quaternion rotation of the bone in either local or world space
  79144. * @param space The space that the rotation should be in
  79145. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79146. * @returns The quaternion rotation
  79147. */
  79148. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  79149. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79150. if (mesh === void 0) { mesh = null; }
  79151. var result = BABYLON.Quaternion.Identity();
  79152. this.getRotationQuaternionToRef(space, mesh, result);
  79153. return result;
  79154. };
  79155. /**
  79156. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  79157. * @param space The space that the rotation should be in
  79158. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79159. * @param result The quaternion that the rotation should be copied to
  79160. */
  79161. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  79162. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79163. if (mesh === void 0) { mesh = null; }
  79164. if (space == BABYLON.Space.LOCAL) {
  79165. this._decompose();
  79166. result.copyFrom(this._localRotation);
  79167. }
  79168. else {
  79169. var mat = Bone._tmpMats[0];
  79170. var amat = this.getAbsoluteTransform();
  79171. if (mesh) {
  79172. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79173. }
  79174. else {
  79175. mat.copyFrom(amat);
  79176. }
  79177. mat.m[0] *= this._scalingDeterminant;
  79178. mat.m[1] *= this._scalingDeterminant;
  79179. mat.m[2] *= this._scalingDeterminant;
  79180. mat.decompose(undefined, result, undefined);
  79181. }
  79182. };
  79183. /**
  79184. * Get the rotation matrix of the bone in local or world space
  79185. * @param space The space that the rotation should be in
  79186. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79187. * @returns The rotation matrix
  79188. */
  79189. Bone.prototype.getRotationMatrix = function (space, mesh) {
  79190. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79191. var result = BABYLON.Matrix.Identity();
  79192. this.getRotationMatrixToRef(space, mesh, result);
  79193. return result;
  79194. };
  79195. /**
  79196. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  79197. * @param space The space that the rotation should be in
  79198. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79199. * @param result The quaternion that the rotation should be copied to
  79200. */
  79201. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  79202. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79203. if (space == BABYLON.Space.LOCAL) {
  79204. this.getLocalMatrix().getRotationMatrixToRef(result);
  79205. }
  79206. else {
  79207. var mat = Bone._tmpMats[0];
  79208. var amat = this.getAbsoluteTransform();
  79209. if (mesh) {
  79210. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79211. }
  79212. else {
  79213. mat.copyFrom(amat);
  79214. }
  79215. mat.m[0] *= this._scalingDeterminant;
  79216. mat.m[1] *= this._scalingDeterminant;
  79217. mat.m[2] *= this._scalingDeterminant;
  79218. mat.getRotationMatrixToRef(result);
  79219. }
  79220. };
  79221. /**
  79222. * Get the world position of a point that is in the local space of the bone
  79223. * @param position The local position
  79224. * @param mesh The mesh that this bone is attached to
  79225. * @returns The world position
  79226. */
  79227. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  79228. if (mesh === void 0) { mesh = null; }
  79229. var result = BABYLON.Vector3.Zero();
  79230. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  79231. return result;
  79232. };
  79233. /**
  79234. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  79235. * @param position The local position
  79236. * @param mesh The mesh that this bone is attached to
  79237. * @param result The vector3 that the world position should be copied to
  79238. */
  79239. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  79240. if (mesh === void 0) { mesh = null; }
  79241. var wm = null;
  79242. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79243. if (mesh) {
  79244. wm = mesh.getWorldMatrix();
  79245. }
  79246. this._skeleton.computeAbsoluteTransforms();
  79247. var tmat = Bone._tmpMats[0];
  79248. if (mesh && wm) {
  79249. tmat.copyFrom(this.getAbsoluteTransform());
  79250. tmat.multiplyToRef(wm, tmat);
  79251. }
  79252. else {
  79253. tmat = this.getAbsoluteTransform();
  79254. }
  79255. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79256. };
  79257. /**
  79258. * Get the local position of a point that is in world space
  79259. * @param position The world position
  79260. * @param mesh The mesh that this bone is attached to
  79261. * @returns The local position
  79262. */
  79263. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  79264. if (mesh === void 0) { mesh = null; }
  79265. var result = BABYLON.Vector3.Zero();
  79266. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  79267. return result;
  79268. };
  79269. /**
  79270. * Get the local position of a point that is in world space and copy it to the result param
  79271. * @param position The world position
  79272. * @param mesh The mesh that this bone is attached to
  79273. * @param result The vector3 that the local position should be copied to
  79274. */
  79275. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  79276. if (mesh === void 0) { mesh = null; }
  79277. var wm = null;
  79278. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79279. if (mesh) {
  79280. wm = mesh.getWorldMatrix();
  79281. }
  79282. this._skeleton.computeAbsoluteTransforms();
  79283. var tmat = Bone._tmpMats[0];
  79284. tmat.copyFrom(this.getAbsoluteTransform());
  79285. if (mesh && wm) {
  79286. tmat.multiplyToRef(wm, tmat);
  79287. }
  79288. tmat.invert();
  79289. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79290. };
  79291. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79292. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  79293. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79294. return Bone;
  79295. }(BABYLON.Node));
  79296. BABYLON.Bone = Bone;
  79297. })(BABYLON || (BABYLON = {}));
  79298. //# sourceMappingURL=babylon.bone.js.map
  79299. var BABYLON;
  79300. (function (BABYLON) {
  79301. /**
  79302. * Class used to apply inverse kinematics to bones
  79303. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  79304. */
  79305. var BoneIKController = /** @class */ (function () {
  79306. /**
  79307. * Creates a new BoneIKController
  79308. * @param mesh defines the mesh to control
  79309. * @param bone defines the bone to control
  79310. * @param options defines options to set up the controller
  79311. */
  79312. function BoneIKController(mesh, bone, options) {
  79313. /**
  79314. * Gets or sets the target position
  79315. */
  79316. this.targetPosition = BABYLON.Vector3.Zero();
  79317. /**
  79318. * Gets or sets the pole target position
  79319. */
  79320. this.poleTargetPosition = BABYLON.Vector3.Zero();
  79321. /**
  79322. * Gets or sets the pole target local offset
  79323. */
  79324. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  79325. /**
  79326. * Gets or sets the pole angle
  79327. */
  79328. this.poleAngle = 0;
  79329. /**
  79330. * 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)
  79331. */
  79332. this.slerpAmount = 1;
  79333. this._bone1Quat = BABYLON.Quaternion.Identity();
  79334. this._bone1Mat = BABYLON.Matrix.Identity();
  79335. this._bone2Ang = Math.PI;
  79336. this._maxAngle = Math.PI;
  79337. this._rightHandedSystem = false;
  79338. this._bendAxis = BABYLON.Vector3.Right();
  79339. this._slerping = false;
  79340. this._adjustRoll = 0;
  79341. this._bone2 = bone;
  79342. this._bone1 = bone.getParent();
  79343. if (!this._bone1) {
  79344. return;
  79345. }
  79346. this.mesh = mesh;
  79347. var bonePos = bone.getPosition();
  79348. if (bone.getAbsoluteTransform().determinant() > 0) {
  79349. this._rightHandedSystem = true;
  79350. this._bendAxis.x = 0;
  79351. this._bendAxis.y = 0;
  79352. this._bendAxis.z = -1;
  79353. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  79354. this._adjustRoll = Math.PI * .5;
  79355. this._bendAxis.z = 1;
  79356. }
  79357. }
  79358. if (this._bone1.length) {
  79359. var boneScale1 = this._bone1.getScale();
  79360. var boneScale2 = this._bone2.getScale();
  79361. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  79362. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  79363. }
  79364. else if (this._bone1.children[0]) {
  79365. mesh.computeWorldMatrix(true);
  79366. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  79367. var pos2 = this._bone2.getAbsolutePosition(mesh);
  79368. var pos3 = this._bone1.getAbsolutePosition(mesh);
  79369. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  79370. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  79371. }
  79372. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  79373. this.maxAngle = Math.PI;
  79374. if (options) {
  79375. if (options.targetMesh) {
  79376. this.targetMesh = options.targetMesh;
  79377. this.targetMesh.computeWorldMatrix(true);
  79378. }
  79379. if (options.poleTargetMesh) {
  79380. this.poleTargetMesh = options.poleTargetMesh;
  79381. this.poleTargetMesh.computeWorldMatrix(true);
  79382. }
  79383. else if (options.poleTargetBone) {
  79384. this.poleTargetBone = options.poleTargetBone;
  79385. }
  79386. else if (this._bone1.getParent()) {
  79387. this.poleTargetBone = this._bone1.getParent();
  79388. }
  79389. if (options.poleTargetLocalOffset) {
  79390. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  79391. }
  79392. if (options.poleAngle) {
  79393. this.poleAngle = options.poleAngle;
  79394. }
  79395. if (options.bendAxis) {
  79396. this._bendAxis.copyFrom(options.bendAxis);
  79397. }
  79398. if (options.maxAngle) {
  79399. this.maxAngle = options.maxAngle;
  79400. }
  79401. if (options.slerpAmount) {
  79402. this.slerpAmount = options.slerpAmount;
  79403. }
  79404. }
  79405. }
  79406. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  79407. /**
  79408. * Gets or sets maximum allowed angle
  79409. */
  79410. get: function () {
  79411. return this._maxAngle;
  79412. },
  79413. set: function (value) {
  79414. this._setMaxAngle(value);
  79415. },
  79416. enumerable: true,
  79417. configurable: true
  79418. });
  79419. BoneIKController.prototype._setMaxAngle = function (ang) {
  79420. if (ang < 0) {
  79421. ang = 0;
  79422. }
  79423. if (ang > Math.PI || ang == undefined) {
  79424. ang = Math.PI;
  79425. }
  79426. this._maxAngle = ang;
  79427. var a = this._bone1Length;
  79428. var b = this._bone2Length;
  79429. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  79430. };
  79431. /**
  79432. * Force the controller to update the bones
  79433. */
  79434. BoneIKController.prototype.update = function () {
  79435. var bone1 = this._bone1;
  79436. if (!bone1) {
  79437. return;
  79438. }
  79439. var target = this.targetPosition;
  79440. var poleTarget = this.poleTargetPosition;
  79441. var mat1 = BoneIKController._tmpMats[0];
  79442. var mat2 = BoneIKController._tmpMats[1];
  79443. if (this.targetMesh) {
  79444. target.copyFrom(this.targetMesh.getAbsolutePosition());
  79445. }
  79446. if (this.poleTargetBone) {
  79447. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  79448. }
  79449. else if (this.poleTargetMesh) {
  79450. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  79451. }
  79452. var bonePos = BoneIKController._tmpVecs[0];
  79453. var zaxis = BoneIKController._tmpVecs[1];
  79454. var xaxis = BoneIKController._tmpVecs[2];
  79455. var yaxis = BoneIKController._tmpVecs[3];
  79456. var upAxis = BoneIKController._tmpVecs[4];
  79457. var _tmpQuat = BoneIKController._tmpQuat;
  79458. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  79459. poleTarget.subtractToRef(bonePos, upAxis);
  79460. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  79461. upAxis.y = 1;
  79462. }
  79463. else {
  79464. upAxis.normalize();
  79465. }
  79466. target.subtractToRef(bonePos, yaxis);
  79467. yaxis.normalize();
  79468. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  79469. zaxis.normalize();
  79470. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  79471. xaxis.normalize();
  79472. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  79473. var a = this._bone1Length;
  79474. var b = this._bone2Length;
  79475. var c = BABYLON.Vector3.Distance(bonePos, target);
  79476. if (this._maxReach > 0) {
  79477. c = Math.min(this._maxReach, c);
  79478. }
  79479. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  79480. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  79481. if (acosa > 1) {
  79482. acosa = 1;
  79483. }
  79484. if (acosb > 1) {
  79485. acosb = 1;
  79486. }
  79487. if (acosa < -1) {
  79488. acosa = -1;
  79489. }
  79490. if (acosb < -1) {
  79491. acosb = -1;
  79492. }
  79493. var angA = Math.acos(acosa);
  79494. var angB = Math.acos(acosb);
  79495. var angC = -angA - angB;
  79496. if (this._rightHandedSystem) {
  79497. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  79498. mat2.multiplyToRef(mat1, mat1);
  79499. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  79500. mat2.multiplyToRef(mat1, mat1);
  79501. }
  79502. else {
  79503. var _tmpVec = BoneIKController._tmpVecs[5];
  79504. _tmpVec.copyFrom(this._bendAxis);
  79505. _tmpVec.x *= -1;
  79506. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  79507. mat2.multiplyToRef(mat1, mat1);
  79508. }
  79509. if (this.poleAngle) {
  79510. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  79511. mat1.multiplyToRef(mat2, mat1);
  79512. }
  79513. if (this._bone1) {
  79514. if (this.slerpAmount < 1) {
  79515. if (!this._slerping) {
  79516. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  79517. }
  79518. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  79519. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  79520. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  79521. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  79522. this._slerping = true;
  79523. }
  79524. else {
  79525. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  79526. this._bone1Mat.copyFrom(mat1);
  79527. this._slerping = false;
  79528. }
  79529. }
  79530. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  79531. this._bone2Ang = angC;
  79532. };
  79533. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79534. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  79535. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79536. return BoneIKController;
  79537. }());
  79538. BABYLON.BoneIKController = BoneIKController;
  79539. })(BABYLON || (BABYLON = {}));
  79540. //# sourceMappingURL=babylon.boneIKController.js.map
  79541. var BABYLON;
  79542. (function (BABYLON) {
  79543. /**
  79544. * Class used to make a bone look toward a point in space
  79545. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  79546. */
  79547. var BoneLookController = /** @class */ (function () {
  79548. /**
  79549. * Create a BoneLookController
  79550. * @param mesh the mesh that the bone belongs to
  79551. * @param bone the bone that will be looking to the target
  79552. * @param target the target Vector3 to look at
  79553. * @param settings optional settings:
  79554. * * maxYaw: the maximum angle the bone will yaw to
  79555. * * minYaw: the minimum angle the bone will yaw to
  79556. * * maxPitch: the maximum angle the bone will pitch to
  79557. * * minPitch: the minimum angle the bone will yaw to
  79558. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  79559. * * upAxis: the up axis of the coordinate system
  79560. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  79561. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  79562. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  79563. * * adjustYaw: used to make an adjustment to the yaw of the bone
  79564. * * adjustPitch: used to make an adjustment to the pitch of the bone
  79565. * * adjustRoll: used to make an adjustment to the roll of the bone
  79566. **/
  79567. function BoneLookController(mesh, bone, target, options) {
  79568. /**
  79569. * The up axis of the coordinate system that is used when the bone is rotated
  79570. */
  79571. this.upAxis = BABYLON.Vector3.Up();
  79572. /**
  79573. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  79574. */
  79575. this.upAxisSpace = BABYLON.Space.LOCAL;
  79576. /**
  79577. * Used to make an adjustment to the yaw of the bone
  79578. */
  79579. this.adjustYaw = 0;
  79580. /**
  79581. * Used to make an adjustment to the pitch of the bone
  79582. */
  79583. this.adjustPitch = 0;
  79584. /**
  79585. * Used to make an adjustment to the roll of the bone
  79586. */
  79587. this.adjustRoll = 0;
  79588. /**
  79589. * 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)
  79590. */
  79591. this.slerpAmount = 1;
  79592. this._boneQuat = BABYLON.Quaternion.Identity();
  79593. this._slerping = false;
  79594. this._firstFrameSkipped = false;
  79595. this._fowardAxis = BABYLON.Vector3.Forward();
  79596. this.mesh = mesh;
  79597. this.bone = bone;
  79598. this.target = target;
  79599. if (options) {
  79600. if (options.adjustYaw) {
  79601. this.adjustYaw = options.adjustYaw;
  79602. }
  79603. if (options.adjustPitch) {
  79604. this.adjustPitch = options.adjustPitch;
  79605. }
  79606. if (options.adjustRoll) {
  79607. this.adjustRoll = options.adjustRoll;
  79608. }
  79609. if (options.maxYaw != null) {
  79610. this.maxYaw = options.maxYaw;
  79611. }
  79612. else {
  79613. this.maxYaw = Math.PI;
  79614. }
  79615. if (options.minYaw != null) {
  79616. this.minYaw = options.minYaw;
  79617. }
  79618. else {
  79619. this.minYaw = -Math.PI;
  79620. }
  79621. if (options.maxPitch != null) {
  79622. this.maxPitch = options.maxPitch;
  79623. }
  79624. else {
  79625. this.maxPitch = Math.PI;
  79626. }
  79627. if (options.minPitch != null) {
  79628. this.minPitch = options.minPitch;
  79629. }
  79630. else {
  79631. this.minPitch = -Math.PI;
  79632. }
  79633. if (options.slerpAmount != null) {
  79634. this.slerpAmount = options.slerpAmount;
  79635. }
  79636. if (options.upAxis != null) {
  79637. this.upAxis = options.upAxis;
  79638. }
  79639. if (options.upAxisSpace != null) {
  79640. this.upAxisSpace = options.upAxisSpace;
  79641. }
  79642. if (options.yawAxis != null || options.pitchAxis != null) {
  79643. var newYawAxis = BABYLON.Axis.Y;
  79644. var newPitchAxis = BABYLON.Axis.X;
  79645. if (options.yawAxis != null) {
  79646. newYawAxis = options.yawAxis.clone();
  79647. newYawAxis.normalize();
  79648. }
  79649. if (options.pitchAxis != null) {
  79650. newPitchAxis = options.pitchAxis.clone();
  79651. newPitchAxis.normalize();
  79652. }
  79653. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  79654. this._transformYawPitch = BABYLON.Matrix.Identity();
  79655. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  79656. this._transformYawPitchInv = this._transformYawPitch.clone();
  79657. this._transformYawPitch.invert();
  79658. }
  79659. }
  79660. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  79661. this.upAxisSpace = BABYLON.Space.LOCAL;
  79662. }
  79663. }
  79664. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  79665. /**
  79666. * Gets or sets the minimum yaw angle that the bone can look to
  79667. */
  79668. get: function () {
  79669. return this._minYaw;
  79670. },
  79671. set: function (value) {
  79672. this._minYaw = value;
  79673. this._minYawSin = Math.sin(value);
  79674. this._minYawCos = Math.cos(value);
  79675. if (this._maxYaw != null) {
  79676. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79677. this._yawRange = this._maxYaw - this._minYaw;
  79678. }
  79679. },
  79680. enumerable: true,
  79681. configurable: true
  79682. });
  79683. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  79684. /**
  79685. * Gets or sets the maximum yaw angle that the bone can look to
  79686. */
  79687. get: function () {
  79688. return this._maxYaw;
  79689. },
  79690. set: function (value) {
  79691. this._maxYaw = value;
  79692. this._maxYawSin = Math.sin(value);
  79693. this._maxYawCos = Math.cos(value);
  79694. if (this._minYaw != null) {
  79695. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79696. this._yawRange = this._maxYaw - this._minYaw;
  79697. }
  79698. },
  79699. enumerable: true,
  79700. configurable: true
  79701. });
  79702. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  79703. /**
  79704. * Gets or sets the minimum pitch angle that the bone can look to
  79705. */
  79706. get: function () {
  79707. return this._minPitch;
  79708. },
  79709. set: function (value) {
  79710. this._minPitch = value;
  79711. this._minPitchTan = Math.tan(value);
  79712. },
  79713. enumerable: true,
  79714. configurable: true
  79715. });
  79716. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  79717. /**
  79718. * Gets or sets the maximum pitch angle that the bone can look to
  79719. */
  79720. get: function () {
  79721. return this._maxPitch;
  79722. },
  79723. set: function (value) {
  79724. this._maxPitch = value;
  79725. this._maxPitchTan = Math.tan(value);
  79726. },
  79727. enumerable: true,
  79728. configurable: true
  79729. });
  79730. /**
  79731. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  79732. */
  79733. BoneLookController.prototype.update = function () {
  79734. //skip the first frame when slerping so that the mesh rotation is correct
  79735. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  79736. this._firstFrameSkipped = true;
  79737. return;
  79738. }
  79739. var bone = this.bone;
  79740. var bonePos = BoneLookController._tmpVecs[0];
  79741. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  79742. var target = this.target;
  79743. var _tmpMat1 = BoneLookController._tmpMats[0];
  79744. var _tmpMat2 = BoneLookController._tmpMats[1];
  79745. var mesh = this.mesh;
  79746. var parentBone = bone.getParent();
  79747. var upAxis = BoneLookController._tmpVecs[1];
  79748. upAxis.copyFrom(this.upAxis);
  79749. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  79750. if (this._transformYawPitch) {
  79751. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  79752. }
  79753. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  79754. }
  79755. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  79756. mesh.getDirectionToRef(upAxis, upAxis);
  79757. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  79758. upAxis.normalize();
  79759. }
  79760. }
  79761. var checkYaw = false;
  79762. var checkPitch = false;
  79763. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  79764. checkYaw = true;
  79765. }
  79766. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  79767. checkPitch = true;
  79768. }
  79769. if (checkYaw || checkPitch) {
  79770. var spaceMat = BoneLookController._tmpMats[2];
  79771. var spaceMatInv = BoneLookController._tmpMats[3];
  79772. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  79773. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  79774. }
  79775. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  79776. spaceMat.copyFrom(mesh.getWorldMatrix());
  79777. }
  79778. else {
  79779. var forwardAxis = BoneLookController._tmpVecs[2];
  79780. forwardAxis.copyFrom(this._fowardAxis);
  79781. if (this._transformYawPitch) {
  79782. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  79783. }
  79784. if (parentBone) {
  79785. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  79786. }
  79787. else {
  79788. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  79789. }
  79790. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  79791. rightAxis.normalize();
  79792. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  79793. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  79794. }
  79795. spaceMat.invertToRef(spaceMatInv);
  79796. var xzlen = null;
  79797. if (checkPitch) {
  79798. var localTarget = BoneLookController._tmpVecs[3];
  79799. target.subtractToRef(bonePos, localTarget);
  79800. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79801. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79802. var pitch = Math.atan2(localTarget.y, xzlen);
  79803. var newPitch = pitch;
  79804. if (pitch > this._maxPitch) {
  79805. localTarget.y = this._maxPitchTan * xzlen;
  79806. newPitch = this._maxPitch;
  79807. }
  79808. else if (pitch < this._minPitch) {
  79809. localTarget.y = this._minPitchTan * xzlen;
  79810. newPitch = this._minPitch;
  79811. }
  79812. if (pitch != newPitch) {
  79813. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79814. localTarget.addInPlace(bonePos);
  79815. target = localTarget;
  79816. }
  79817. }
  79818. if (checkYaw) {
  79819. var localTarget = BoneLookController._tmpVecs[4];
  79820. target.subtractToRef(bonePos, localTarget);
  79821. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79822. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79823. var newYaw = yaw;
  79824. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79825. if (xzlen == null) {
  79826. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79827. }
  79828. if (this._yawRange > Math.PI) {
  79829. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79830. localTarget.z = this._maxYawCos * xzlen;
  79831. localTarget.x = this._maxYawSin * xzlen;
  79832. newYaw = this._maxYaw;
  79833. }
  79834. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79835. localTarget.z = this._minYawCos * xzlen;
  79836. localTarget.x = this._minYawSin * xzlen;
  79837. newYaw = this._minYaw;
  79838. }
  79839. }
  79840. else {
  79841. if (yaw > this._maxYaw) {
  79842. localTarget.z = this._maxYawCos * xzlen;
  79843. localTarget.x = this._maxYawSin * xzlen;
  79844. newYaw = this._maxYaw;
  79845. }
  79846. else if (yaw < this._minYaw) {
  79847. localTarget.z = this._minYawCos * xzlen;
  79848. localTarget.x = this._minYawSin * xzlen;
  79849. newYaw = this._minYaw;
  79850. }
  79851. }
  79852. }
  79853. if (this._slerping && this._yawRange > Math.PI) {
  79854. //are we going to be crossing into the min/max region?
  79855. var boneFwd = BoneLookController._tmpVecs[8];
  79856. boneFwd.copyFrom(BABYLON.Axis.Z);
  79857. if (this._transformYawPitch) {
  79858. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79859. }
  79860. var boneRotMat = BoneLookController._tmpMats[4];
  79861. this._boneQuat.toRotationMatrix(boneRotMat);
  79862. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79863. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79864. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79865. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79866. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79867. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79868. if (angBtwTar > angBtwMidYaw) {
  79869. if (xzlen == null) {
  79870. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79871. }
  79872. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79873. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79874. if (angBtwMin < angBtwMax) {
  79875. newYaw = boneYaw + Math.PI * .75;
  79876. localTarget.z = Math.cos(newYaw) * xzlen;
  79877. localTarget.x = Math.sin(newYaw) * xzlen;
  79878. }
  79879. else {
  79880. newYaw = boneYaw - Math.PI * .75;
  79881. localTarget.z = Math.cos(newYaw) * xzlen;
  79882. localTarget.x = Math.sin(newYaw) * xzlen;
  79883. }
  79884. }
  79885. }
  79886. if (yaw != newYaw) {
  79887. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79888. localTarget.addInPlace(bonePos);
  79889. target = localTarget;
  79890. }
  79891. }
  79892. }
  79893. var zaxis = BoneLookController._tmpVecs[5];
  79894. var xaxis = BoneLookController._tmpVecs[6];
  79895. var yaxis = BoneLookController._tmpVecs[7];
  79896. var _tmpQuat = BoneLookController._tmpQuat;
  79897. target.subtractToRef(bonePos, zaxis);
  79898. zaxis.normalize();
  79899. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79900. xaxis.normalize();
  79901. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79902. yaxis.normalize();
  79903. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79904. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79905. return;
  79906. }
  79907. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79908. return;
  79909. }
  79910. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79911. return;
  79912. }
  79913. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79914. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79915. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79916. }
  79917. if (this.slerpAmount < 1) {
  79918. if (!this._slerping) {
  79919. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79920. }
  79921. if (this._transformYawPitch) {
  79922. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79923. }
  79924. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79925. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79926. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79927. this._slerping = true;
  79928. }
  79929. else {
  79930. if (this._transformYawPitch) {
  79931. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79932. }
  79933. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79934. this._slerping = false;
  79935. }
  79936. };
  79937. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79938. var angDiff = ang2 - ang1;
  79939. angDiff %= Math.PI * 2;
  79940. if (angDiff > Math.PI) {
  79941. angDiff -= Math.PI * 2;
  79942. }
  79943. else if (angDiff < -Math.PI) {
  79944. angDiff += Math.PI * 2;
  79945. }
  79946. return angDiff;
  79947. };
  79948. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79949. ang1 %= (2 * Math.PI);
  79950. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79951. ang2 %= (2 * Math.PI);
  79952. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79953. var ab = 0;
  79954. if (ang1 < ang2) {
  79955. ab = ang2 - ang1;
  79956. }
  79957. else {
  79958. ab = ang1 - ang2;
  79959. }
  79960. if (ab > Math.PI) {
  79961. ab = Math.PI * 2 - ab;
  79962. }
  79963. return ab;
  79964. };
  79965. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79966. ang %= (2 * Math.PI);
  79967. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79968. ang1 %= (2 * Math.PI);
  79969. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79970. ang2 %= (2 * Math.PI);
  79971. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79972. if (ang1 < ang2) {
  79973. if (ang > ang1 && ang < ang2) {
  79974. return true;
  79975. }
  79976. }
  79977. else {
  79978. if (ang > ang2 && ang < ang1) {
  79979. return true;
  79980. }
  79981. }
  79982. return false;
  79983. };
  79984. 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()];
  79985. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79986. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79987. return BoneLookController;
  79988. }());
  79989. BABYLON.BoneLookController = BoneLookController;
  79990. })(BABYLON || (BABYLON = {}));
  79991. //# sourceMappingURL=babylon.boneLookController.js.map
  79992. var BABYLON;
  79993. (function (BABYLON) {
  79994. /**
  79995. * Class used to handle skinning animations
  79996. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79997. */
  79998. var Skeleton = /** @class */ (function () {
  79999. /**
  80000. * Creates a new skeleton
  80001. * @param name defines the skeleton name
  80002. * @param id defines the skeleton Id
  80003. * @param scene defines the hosting scene
  80004. */
  80005. function Skeleton(
  80006. /** defines the skeleton name */
  80007. name,
  80008. /** defines the skeleton Id */
  80009. id, scene) {
  80010. this.name = name;
  80011. this.id = id;
  80012. /**
  80013. * Gets the list of child bones
  80014. */
  80015. this.bones = new Array();
  80016. /**
  80017. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  80018. */
  80019. this.needInitialSkinMatrix = false;
  80020. this._isDirty = true;
  80021. this._meshesWithPoseMatrix = new Array();
  80022. this._identity = BABYLON.Matrix.Identity();
  80023. this._ranges = {};
  80024. this._lastAbsoluteTransformsUpdateId = -1;
  80025. /**
  80026. * Specifies if the skeleton should be serialized
  80027. */
  80028. this.doNotSerialize = false;
  80029. this._animationPropertiesOverride = null;
  80030. // Events
  80031. /**
  80032. * An observable triggered before computing the skeleton's matrices
  80033. */
  80034. this.onBeforeComputeObservable = new BABYLON.Observable();
  80035. this.bones = [];
  80036. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80037. scene.skeletons.push(this);
  80038. //make sure it will recalculate the matrix next time prepare is called.
  80039. this._isDirty = true;
  80040. }
  80041. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  80042. /**
  80043. * Gets or sets the animation properties override
  80044. */
  80045. get: function () {
  80046. if (!this._animationPropertiesOverride) {
  80047. return this._scene.animationPropertiesOverride;
  80048. }
  80049. return this._animationPropertiesOverride;
  80050. },
  80051. set: function (value) {
  80052. this._animationPropertiesOverride = value;
  80053. },
  80054. enumerable: true,
  80055. configurable: true
  80056. });
  80057. // Members
  80058. /**
  80059. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  80060. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  80061. * @returns a Float32Array containing matrices data
  80062. */
  80063. Skeleton.prototype.getTransformMatrices = function (mesh) {
  80064. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  80065. return mesh._bonesTransformMatrices;
  80066. }
  80067. if (!this._transformMatrices) {
  80068. this.prepare();
  80069. }
  80070. return this._transformMatrices;
  80071. };
  80072. /**
  80073. * Gets the current hosting scene
  80074. * @returns a scene object
  80075. */
  80076. Skeleton.prototype.getScene = function () {
  80077. return this._scene;
  80078. };
  80079. // Methods
  80080. /**
  80081. * Gets a string representing the current skeleton data
  80082. * @param fullDetails defines a boolean indicating if we want a verbose version
  80083. * @returns a string representing the current skeleton data
  80084. */
  80085. Skeleton.prototype.toString = function (fullDetails) {
  80086. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  80087. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  80088. if (fullDetails) {
  80089. ret += ", Ranges: {";
  80090. var first = true;
  80091. for (var name_1 in this._ranges) {
  80092. if (first) {
  80093. ret += ", ";
  80094. first = false;
  80095. }
  80096. ret += name_1;
  80097. }
  80098. ret += "}";
  80099. }
  80100. return ret;
  80101. };
  80102. /**
  80103. * Get bone's index searching by name
  80104. * @param name defines bone's name to search for
  80105. * @return the indice of the bone. Returns -1 if not found
  80106. */
  80107. Skeleton.prototype.getBoneIndexByName = function (name) {
  80108. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  80109. if (this.bones[boneIndex].name === name) {
  80110. return boneIndex;
  80111. }
  80112. }
  80113. return -1;
  80114. };
  80115. /**
  80116. * Creater a new animation range
  80117. * @param name defines the name of the range
  80118. * @param from defines the start key
  80119. * @param to defines the end key
  80120. */
  80121. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  80122. // check name not already in use
  80123. if (!this._ranges[name]) {
  80124. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  80125. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80126. if (this.bones[i].animations[0]) {
  80127. this.bones[i].animations[0].createRange(name, from, to);
  80128. }
  80129. }
  80130. }
  80131. };
  80132. /**
  80133. * Delete a specific animation range
  80134. * @param name defines the name of the range
  80135. * @param deleteFrames defines if frames must be removed as well
  80136. */
  80137. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  80138. if (deleteFrames === void 0) { deleteFrames = true; }
  80139. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80140. if (this.bones[i].animations[0]) {
  80141. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  80142. }
  80143. }
  80144. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  80145. };
  80146. /**
  80147. * Gets a specific animation range
  80148. * @param name defines the name of the range to look for
  80149. * @returns the requested animation range or null if not found
  80150. */
  80151. Skeleton.prototype.getAnimationRange = function (name) {
  80152. return this._ranges[name];
  80153. };
  80154. /**
  80155. * Gets the list of all animation ranges defined on this skeleton
  80156. * @returns an array
  80157. */
  80158. Skeleton.prototype.getAnimationRanges = function () {
  80159. var animationRanges = [];
  80160. var name;
  80161. var i = 0;
  80162. for (name in this._ranges) {
  80163. animationRanges[i] = this._ranges[name];
  80164. i++;
  80165. }
  80166. return animationRanges;
  80167. };
  80168. /**
  80169. * Copy animation range from a source skeleton.
  80170. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  80171. * @param source defines the source skeleton
  80172. * @param name defines the name of the range to copy
  80173. * @param rescaleAsRequired defines if rescaling must be applied if required
  80174. * @returns true if operation was successful
  80175. */
  80176. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  80177. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  80178. if (this._ranges[name] || !source.getAnimationRange(name)) {
  80179. return false;
  80180. }
  80181. var ret = true;
  80182. var frameOffset = this._getHighestAnimationFrame() + 1;
  80183. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  80184. var boneDict = {};
  80185. var sourceBones = source.bones;
  80186. var nBones;
  80187. var i;
  80188. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  80189. boneDict[sourceBones[i].name] = sourceBones[i];
  80190. }
  80191. if (this.bones.length !== sourceBones.length) {
  80192. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  80193. ret = false;
  80194. }
  80195. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  80196. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  80197. var boneName = this.bones[i].name;
  80198. var sourceBone = boneDict[boneName];
  80199. if (sourceBone) {
  80200. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  80201. }
  80202. else {
  80203. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  80204. ret = false;
  80205. }
  80206. }
  80207. // do not call createAnimationRange(), since it also is done to bones, which was already done
  80208. var range = source.getAnimationRange(name);
  80209. if (range) {
  80210. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  80211. }
  80212. return ret;
  80213. };
  80214. /**
  80215. * Forces the skeleton to go to rest pose
  80216. */
  80217. Skeleton.prototype.returnToRest = function () {
  80218. for (var index = 0; index < this.bones.length; index++) {
  80219. this.bones[index].returnToRest();
  80220. }
  80221. };
  80222. Skeleton.prototype._getHighestAnimationFrame = function () {
  80223. var ret = 0;
  80224. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80225. if (this.bones[i].animations[0]) {
  80226. var highest = this.bones[i].animations[0].getHighestFrame();
  80227. if (ret < highest) {
  80228. ret = highest;
  80229. }
  80230. }
  80231. }
  80232. return ret;
  80233. };
  80234. /**
  80235. * Begin a specific animation range
  80236. * @param name defines the name of the range to start
  80237. * @param loop defines if looping must be turned on (false by default)
  80238. * @param speedRatio defines the speed ratio to apply (1 by default)
  80239. * @param onAnimationEnd defines a callback which will be called when animation will end
  80240. * @returns a new animatable
  80241. */
  80242. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  80243. var range = this.getAnimationRange(name);
  80244. if (!range) {
  80245. return null;
  80246. }
  80247. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  80248. };
  80249. /** @hidden */
  80250. Skeleton.prototype._markAsDirty = function () {
  80251. this._isDirty = true;
  80252. };
  80253. /** @hidden */
  80254. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  80255. this._meshesWithPoseMatrix.push(mesh);
  80256. };
  80257. /** @hidden */
  80258. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  80259. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  80260. if (index > -1) {
  80261. this._meshesWithPoseMatrix.splice(index, 1);
  80262. }
  80263. };
  80264. /** @hidden */
  80265. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  80266. this.onBeforeComputeObservable.notifyObservers(this);
  80267. for (var index = 0; index < this.bones.length; index++) {
  80268. var bone = this.bones[index];
  80269. var parentBone = bone.getParent();
  80270. if (parentBone) {
  80271. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  80272. }
  80273. else {
  80274. if (initialSkinMatrix) {
  80275. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  80276. }
  80277. else {
  80278. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  80279. }
  80280. }
  80281. if (bone._index !== -1) {
  80282. var mappedIndex = bone._index === null ? index : bone._index;
  80283. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  80284. }
  80285. }
  80286. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  80287. };
  80288. /**
  80289. * Build all resources required to render a skeleton
  80290. */
  80291. Skeleton.prototype.prepare = function () {
  80292. if (!this._isDirty) {
  80293. return;
  80294. }
  80295. if (this.needInitialSkinMatrix) {
  80296. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  80297. var mesh = this._meshesWithPoseMatrix[index];
  80298. var poseMatrix = mesh.getPoseMatrix();
  80299. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  80300. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80301. }
  80302. if (this._synchronizedWithMesh !== mesh) {
  80303. this._synchronizedWithMesh = mesh;
  80304. // Prepare bones
  80305. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  80306. var bone = this.bones[boneIndex];
  80307. if (!bone.getParent()) {
  80308. var matrix = bone.getBaseMatrix();
  80309. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  80310. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  80311. }
  80312. }
  80313. }
  80314. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  80315. }
  80316. }
  80317. else {
  80318. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  80319. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80320. }
  80321. this._computeTransformMatrices(this._transformMatrices, null);
  80322. }
  80323. this._isDirty = false;
  80324. this._scene._activeBones.addCount(this.bones.length, false);
  80325. };
  80326. /**
  80327. * Gets the list of animatables currently running for this skeleton
  80328. * @returns an array of animatables
  80329. */
  80330. Skeleton.prototype.getAnimatables = function () {
  80331. if (!this._animatables || this._animatables.length !== this.bones.length) {
  80332. this._animatables = [];
  80333. for (var index = 0; index < this.bones.length; index++) {
  80334. this._animatables.push(this.bones[index]);
  80335. }
  80336. }
  80337. return this._animatables;
  80338. };
  80339. /**
  80340. * Clone the current skeleton
  80341. * @param name defines the name of the new skeleton
  80342. * @param id defines the id of the enw skeleton
  80343. * @returns the new skeleton
  80344. */
  80345. Skeleton.prototype.clone = function (name, id) {
  80346. var result = new Skeleton(name, id || name, this._scene);
  80347. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80348. for (var index = 0; index < this.bones.length; index++) {
  80349. var source = this.bones[index];
  80350. var parentBone = null;
  80351. var parent_1 = source.getParent();
  80352. if (parent_1) {
  80353. var parentIndex = this.bones.indexOf(parent_1);
  80354. parentBone = result.bones[parentIndex];
  80355. }
  80356. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  80357. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  80358. }
  80359. if (this._ranges) {
  80360. result._ranges = {};
  80361. for (var rangeName in this._ranges) {
  80362. var range = this._ranges[rangeName];
  80363. if (range) {
  80364. result._ranges[rangeName] = range.clone();
  80365. }
  80366. }
  80367. }
  80368. this._isDirty = true;
  80369. return result;
  80370. };
  80371. /**
  80372. * Enable animation blending for this skeleton
  80373. * @param blendingSpeed defines the blending speed to apply
  80374. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  80375. */
  80376. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  80377. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  80378. this.bones.forEach(function (bone) {
  80379. bone.animations.forEach(function (animation) {
  80380. animation.enableBlending = true;
  80381. animation.blendingSpeed = blendingSpeed;
  80382. });
  80383. });
  80384. };
  80385. /**
  80386. * Releases all resources associated with the current skeleton
  80387. */
  80388. Skeleton.prototype.dispose = function () {
  80389. this._meshesWithPoseMatrix = [];
  80390. // Animations
  80391. this.getScene().stopAnimation(this);
  80392. // Remove from scene
  80393. this.getScene().removeSkeleton(this);
  80394. };
  80395. /**
  80396. * Serialize the skeleton in a JSON object
  80397. * @returns a JSON object
  80398. */
  80399. Skeleton.prototype.serialize = function () {
  80400. var serializationObject = {};
  80401. serializationObject.name = this.name;
  80402. serializationObject.id = this.id;
  80403. if (this.dimensionsAtRest) {
  80404. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  80405. }
  80406. serializationObject.bones = [];
  80407. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80408. for (var index = 0; index < this.bones.length; index++) {
  80409. var bone = this.bones[index];
  80410. var parent_2 = bone.getParent();
  80411. var serializedBone = {
  80412. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  80413. name: bone.name,
  80414. matrix: bone.getBaseMatrix().toArray(),
  80415. rest: bone.getRestPose().toArray()
  80416. };
  80417. serializationObject.bones.push(serializedBone);
  80418. if (bone.length) {
  80419. serializedBone.length = bone.length;
  80420. }
  80421. if (bone.metadata) {
  80422. serializedBone.metadata = bone.metadata;
  80423. }
  80424. if (bone.animations && bone.animations.length > 0) {
  80425. serializedBone.animation = bone.animations[0].serialize();
  80426. }
  80427. serializationObject.ranges = [];
  80428. for (var name in this._ranges) {
  80429. var source = this._ranges[name];
  80430. if (!source) {
  80431. continue;
  80432. }
  80433. var range = {};
  80434. range.name = name;
  80435. range.from = source.from;
  80436. range.to = source.to;
  80437. serializationObject.ranges.push(range);
  80438. }
  80439. }
  80440. return serializationObject;
  80441. };
  80442. /**
  80443. * Creates a new skeleton from serialized data
  80444. * @param parsedSkeleton defines the serialized data
  80445. * @param scene defines the hosting scene
  80446. * @returns a new skeleton
  80447. */
  80448. Skeleton.Parse = function (parsedSkeleton, scene) {
  80449. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  80450. if (parsedSkeleton.dimensionsAtRest) {
  80451. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  80452. }
  80453. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  80454. var index;
  80455. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  80456. var parsedBone = parsedSkeleton.bones[index];
  80457. var parentBone = null;
  80458. if (parsedBone.parentBoneIndex > -1) {
  80459. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  80460. }
  80461. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  80462. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  80463. if (parsedBone.length) {
  80464. bone.length = parsedBone.length;
  80465. }
  80466. if (parsedBone.metadata) {
  80467. bone.metadata = parsedBone.metadata;
  80468. }
  80469. if (parsedBone.animation) {
  80470. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  80471. }
  80472. }
  80473. // placed after bones, so createAnimationRange can cascade down
  80474. if (parsedSkeleton.ranges) {
  80475. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  80476. var data = parsedSkeleton.ranges[index];
  80477. skeleton.createAnimationRange(data.name, data.from, data.to);
  80478. }
  80479. }
  80480. return skeleton;
  80481. };
  80482. /**
  80483. * Compute all node absolute transforms
  80484. * @param forceUpdate defines if computation must be done even if cache is up to date
  80485. */
  80486. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  80487. if (forceUpdate === void 0) { forceUpdate = false; }
  80488. var renderId = this._scene.getRenderId();
  80489. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  80490. this.bones[0].computeAbsoluteTransforms();
  80491. this._lastAbsoluteTransformsUpdateId = renderId;
  80492. }
  80493. };
  80494. /**
  80495. * Gets the root pose matrix
  80496. * @returns a matrix
  80497. */
  80498. Skeleton.prototype.getPoseMatrix = function () {
  80499. var poseMatrix = null;
  80500. if (this._meshesWithPoseMatrix.length > 0) {
  80501. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  80502. }
  80503. return poseMatrix;
  80504. };
  80505. /**
  80506. * Sorts bones per internal index
  80507. */
  80508. Skeleton.prototype.sortBones = function () {
  80509. var bones = new Array();
  80510. var visited = new Array(this.bones.length);
  80511. for (var index = 0; index < this.bones.length; index++) {
  80512. this._sortBones(index, bones, visited);
  80513. }
  80514. this.bones = bones;
  80515. };
  80516. Skeleton.prototype._sortBones = function (index, bones, visited) {
  80517. if (visited[index]) {
  80518. return;
  80519. }
  80520. visited[index] = true;
  80521. var bone = this.bones[index];
  80522. if (bone._index === undefined) {
  80523. bone._index = index;
  80524. }
  80525. var parentBone = bone.getParent();
  80526. if (parentBone) {
  80527. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  80528. }
  80529. bones.push(bone);
  80530. };
  80531. return Skeleton;
  80532. }());
  80533. BABYLON.Skeleton = Skeleton;
  80534. })(BABYLON || (BABYLON = {}));
  80535. //# sourceMappingURL=babylon.skeleton.js.map
  80536. var BABYLON;
  80537. (function (BABYLON) {
  80538. var SphericalPolynomial = /** @class */ (function () {
  80539. function SphericalPolynomial() {
  80540. this.x = BABYLON.Vector3.Zero();
  80541. this.y = BABYLON.Vector3.Zero();
  80542. this.z = BABYLON.Vector3.Zero();
  80543. this.xx = BABYLON.Vector3.Zero();
  80544. this.yy = BABYLON.Vector3.Zero();
  80545. this.zz = BABYLON.Vector3.Zero();
  80546. this.xy = BABYLON.Vector3.Zero();
  80547. this.yz = BABYLON.Vector3.Zero();
  80548. this.zx = BABYLON.Vector3.Zero();
  80549. }
  80550. SphericalPolynomial.prototype.addAmbient = function (color) {
  80551. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80552. this.xx = this.xx.add(colorVector);
  80553. this.yy = this.yy.add(colorVector);
  80554. this.zz = this.zz.add(colorVector);
  80555. };
  80556. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  80557. var result = new SphericalPolynomial();
  80558. result.x = harmonics.L11.scale(1.02333);
  80559. result.y = harmonics.L1_1.scale(1.02333);
  80560. result.z = harmonics.L10.scale(1.02333);
  80561. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  80562. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  80563. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  80564. result.yz = harmonics.L2_1.scale(0.858086);
  80565. result.zx = harmonics.L21.scale(0.858086);
  80566. result.xy = harmonics.L2_2.scale(0.858086);
  80567. result.scale(1.0 / Math.PI);
  80568. return result;
  80569. };
  80570. SphericalPolynomial.prototype.scale = function (scale) {
  80571. this.x = this.x.scale(scale);
  80572. this.y = this.y.scale(scale);
  80573. this.z = this.z.scale(scale);
  80574. this.xx = this.xx.scale(scale);
  80575. this.yy = this.yy.scale(scale);
  80576. this.zz = this.zz.scale(scale);
  80577. this.yz = this.yz.scale(scale);
  80578. this.zx = this.zx.scale(scale);
  80579. this.xy = this.xy.scale(scale);
  80580. };
  80581. return SphericalPolynomial;
  80582. }());
  80583. BABYLON.SphericalPolynomial = SphericalPolynomial;
  80584. var SphericalHarmonics = /** @class */ (function () {
  80585. function SphericalHarmonics() {
  80586. this.L00 = BABYLON.Vector3.Zero();
  80587. this.L1_1 = BABYLON.Vector3.Zero();
  80588. this.L10 = BABYLON.Vector3.Zero();
  80589. this.L11 = BABYLON.Vector3.Zero();
  80590. this.L2_2 = BABYLON.Vector3.Zero();
  80591. this.L2_1 = BABYLON.Vector3.Zero();
  80592. this.L20 = BABYLON.Vector3.Zero();
  80593. this.L21 = BABYLON.Vector3.Zero();
  80594. this.L22 = BABYLON.Vector3.Zero();
  80595. }
  80596. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  80597. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80598. var c = colorVector.scale(deltaSolidAngle);
  80599. this.L00 = this.L00.add(c.scale(0.282095));
  80600. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  80601. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  80602. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  80603. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  80604. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  80605. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  80606. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  80607. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  80608. };
  80609. SphericalHarmonics.prototype.scale = function (scale) {
  80610. this.L00 = this.L00.scale(scale);
  80611. this.L1_1 = this.L1_1.scale(scale);
  80612. this.L10 = this.L10.scale(scale);
  80613. this.L11 = this.L11.scale(scale);
  80614. this.L2_2 = this.L2_2.scale(scale);
  80615. this.L2_1 = this.L2_1.scale(scale);
  80616. this.L20 = this.L20.scale(scale);
  80617. this.L21 = this.L21.scale(scale);
  80618. this.L22 = this.L22.scale(scale);
  80619. };
  80620. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  80621. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  80622. //
  80623. // E_lm = A_l * L_lm
  80624. //
  80625. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  80626. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  80627. // the scaling factors are given in equation 9.
  80628. // Constant (Band 0)
  80629. this.L00 = this.L00.scale(3.141593);
  80630. // Linear (Band 1)
  80631. this.L1_1 = this.L1_1.scale(2.094395);
  80632. this.L10 = this.L10.scale(2.094395);
  80633. this.L11 = this.L11.scale(2.094395);
  80634. // Quadratic (Band 2)
  80635. this.L2_2 = this.L2_2.scale(0.785398);
  80636. this.L2_1 = this.L2_1.scale(0.785398);
  80637. this.L20 = this.L20.scale(0.785398);
  80638. this.L21 = this.L21.scale(0.785398);
  80639. this.L22 = this.L22.scale(0.785398);
  80640. };
  80641. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  80642. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  80643. // L = (1/pi) * E * rho
  80644. //
  80645. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  80646. this.scale(1.0 / Math.PI);
  80647. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  80648. // (The pixel shader must apply albedo after texture fetches, etc).
  80649. };
  80650. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  80651. var result = new SphericalHarmonics();
  80652. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  80653. result.L1_1 = polynomial.y.scale(0.977204);
  80654. result.L10 = polynomial.z.scale(0.977204);
  80655. result.L11 = polynomial.x.scale(0.977204);
  80656. result.L2_2 = polynomial.xy.scale(1.16538);
  80657. result.L2_1 = polynomial.yz.scale(1.16538);
  80658. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  80659. result.L21 = polynomial.zx.scale(1.16538);
  80660. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  80661. result.scale(Math.PI);
  80662. return result;
  80663. };
  80664. return SphericalHarmonics;
  80665. }());
  80666. BABYLON.SphericalHarmonics = SphericalHarmonics;
  80667. })(BABYLON || (BABYLON = {}));
  80668. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  80669. var BABYLON;
  80670. (function (BABYLON) {
  80671. var FileFaceOrientation = /** @class */ (function () {
  80672. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  80673. this.name = name;
  80674. this.worldAxisForNormal = worldAxisForNormal;
  80675. this.worldAxisForFileX = worldAxisForFileX;
  80676. this.worldAxisForFileY = worldAxisForFileY;
  80677. }
  80678. return FileFaceOrientation;
  80679. }());
  80680. ;
  80681. /**
  80682. * Helper class dealing with the extraction of spherical polynomial dataArray
  80683. * from a cube map.
  80684. */
  80685. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  80686. function CubeMapToSphericalPolynomialTools() {
  80687. }
  80688. /**
  80689. * Converts a texture to the according Spherical Polynomial data.
  80690. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80691. *
  80692. * @param texture The texture to extract the information from.
  80693. * @return The Spherical Polynomial data.
  80694. */
  80695. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  80696. if (!texture.isCube) {
  80697. // Only supports cube Textures currently.
  80698. return null;
  80699. }
  80700. var size = texture.getSize().width;
  80701. var right = texture.readPixels(0);
  80702. var left = texture.readPixels(1);
  80703. var up;
  80704. var down;
  80705. if (texture.isRenderTarget) {
  80706. up = texture.readPixels(3);
  80707. down = texture.readPixels(2);
  80708. }
  80709. else {
  80710. up = texture.readPixels(2);
  80711. down = texture.readPixels(3);
  80712. }
  80713. var front = texture.readPixels(4);
  80714. var back = texture.readPixels(5);
  80715. var gammaSpace = texture.gammaSpace;
  80716. // Always read as RGBA.
  80717. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  80718. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80719. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80720. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80721. }
  80722. var cubeInfo = {
  80723. size: size,
  80724. right: right,
  80725. left: left,
  80726. up: up,
  80727. down: down,
  80728. front: front,
  80729. back: back,
  80730. format: format,
  80731. type: type,
  80732. gammaSpace: gammaSpace,
  80733. };
  80734. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  80735. };
  80736. /**
  80737. * Converts a cubemap to the according Spherical Polynomial data.
  80738. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80739. *
  80740. * @param cubeInfo The Cube map to extract the information from.
  80741. * @return The Spherical Polynomial data.
  80742. */
  80743. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  80744. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  80745. var totalSolidAngle = 0.0;
  80746. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  80747. var du = 2.0 / cubeInfo.size;
  80748. var dv = du;
  80749. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  80750. var minUV = du * 0.5 - 1.0;
  80751. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80752. var fileFace = this.FileFaces[faceIndex];
  80753. var dataArray = cubeInfo[fileFace.name];
  80754. var v = minUV;
  80755. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  80756. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  80757. // Because SP is still linear, so summation is fine in that basis.
  80758. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  80759. for (var y = 0; y < cubeInfo.size; y++) {
  80760. var u = minUV;
  80761. for (var x = 0; x < cubeInfo.size; x++) {
  80762. // World direction (not normalised)
  80763. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  80764. worldDirection.normalize();
  80765. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  80766. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  80767. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  80768. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  80769. // Handle Integer types.
  80770. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80771. r /= 255;
  80772. g /= 255;
  80773. b /= 255;
  80774. }
  80775. // Handle Gamma space textures.
  80776. if (cubeInfo.gammaSpace) {
  80777. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  80778. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  80779. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  80780. }
  80781. var color = new BABYLON.Color3(r, g, b);
  80782. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  80783. totalSolidAngle += deltaSolidAngle;
  80784. u += du;
  80785. }
  80786. v += dv;
  80787. }
  80788. }
  80789. // Solid angle for entire sphere is 4*pi
  80790. var sphereSolidAngle = 4.0 * Math.PI;
  80791. // Adjust the solid angle to allow for how many faces we processed.
  80792. var facesProcessed = 6.0;
  80793. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  80794. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  80795. // This is needed because the numerical integration over the cube uses a
  80796. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  80797. // and also to compensate for accumulative error due to float precision in the summation.
  80798. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  80799. sphericalHarmonics.scale(correctionFactor);
  80800. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  80801. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  80802. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  80803. };
  80804. CubeMapToSphericalPolynomialTools.FileFaces = [
  80805. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  80806. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  80807. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  80808. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  80809. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  80810. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  80811. ];
  80812. return CubeMapToSphericalPolynomialTools;
  80813. }());
  80814. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80815. })(BABYLON || (BABYLON = {}));
  80816. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80817. var BABYLON;
  80818. (function (BABYLON) {
  80819. /**
  80820. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80821. */
  80822. var PanoramaToCubeMapTools = /** @class */ (function () {
  80823. function PanoramaToCubeMapTools() {
  80824. }
  80825. /**
  80826. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80827. *
  80828. * @param float32Array The source data.
  80829. * @param inputWidth The width of the input panorama.
  80830. * @param inputhHeight The height of the input panorama.
  80831. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80832. * @return The cubemap data
  80833. */
  80834. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80835. if (!float32Array) {
  80836. throw "ConvertPanoramaToCubemap: input cannot be null";
  80837. }
  80838. if (float32Array.length != inputWidth * inputHeight * 3) {
  80839. throw "ConvertPanoramaToCubemap: input size is wrong";
  80840. }
  80841. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80842. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80843. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80844. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80845. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80846. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80847. return {
  80848. front: textureFront,
  80849. back: textureBack,
  80850. left: textureLeft,
  80851. right: textureRight,
  80852. up: textureUp,
  80853. down: textureDown,
  80854. size: size,
  80855. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80856. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80857. gammaSpace: false,
  80858. };
  80859. };
  80860. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80861. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80862. var textureArray = new Float32Array(buffer);
  80863. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80864. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80865. var dy = 1 / texSize;
  80866. var fy = 0;
  80867. for (var y = 0; y < texSize; y++) {
  80868. var xv1 = faceData[0];
  80869. var xv2 = faceData[2];
  80870. for (var x = 0; x < texSize; x++) {
  80871. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80872. v.normalize();
  80873. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80874. // 3 channels per pixels
  80875. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80876. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80877. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80878. xv1 = xv1.add(rotDX1);
  80879. xv2 = xv2.add(rotDX2);
  80880. }
  80881. fy += dy;
  80882. }
  80883. return textureArray;
  80884. };
  80885. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80886. var theta = Math.atan2(vDir.z, vDir.x);
  80887. var phi = Math.acos(vDir.y);
  80888. while (theta < -Math.PI)
  80889. theta += 2 * Math.PI;
  80890. while (theta > Math.PI)
  80891. theta -= 2 * Math.PI;
  80892. var dx = theta / Math.PI;
  80893. var dy = phi / Math.PI;
  80894. // recenter.
  80895. dx = dx * 0.5 + 0.5;
  80896. var px = Math.round(dx * inputWidth);
  80897. if (px < 0)
  80898. px = 0;
  80899. else if (px >= inputWidth)
  80900. px = inputWidth - 1;
  80901. var py = Math.round(dy * inputHeight);
  80902. if (py < 0)
  80903. py = 0;
  80904. else if (py >= inputHeight)
  80905. py = inputHeight - 1;
  80906. var inputY = (inputHeight - py - 1);
  80907. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80908. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80909. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80910. return {
  80911. r: r,
  80912. g: g,
  80913. b: b
  80914. };
  80915. };
  80916. PanoramaToCubeMapTools.FACE_FRONT = [
  80917. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80918. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80919. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80920. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80921. ];
  80922. PanoramaToCubeMapTools.FACE_BACK = [
  80923. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80924. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80925. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80926. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80927. ];
  80928. PanoramaToCubeMapTools.FACE_RIGHT = [
  80929. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80930. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80931. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80932. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80933. ];
  80934. PanoramaToCubeMapTools.FACE_LEFT = [
  80935. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80936. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80937. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80938. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80939. ];
  80940. PanoramaToCubeMapTools.FACE_DOWN = [
  80941. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80942. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80943. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80944. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80945. ];
  80946. PanoramaToCubeMapTools.FACE_UP = [
  80947. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80948. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80949. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80950. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80951. ];
  80952. return PanoramaToCubeMapTools;
  80953. }());
  80954. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80955. })(BABYLON || (BABYLON = {}));
  80956. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80957. var BABYLON;
  80958. (function (BABYLON) {
  80959. ;
  80960. /**
  80961. * This groups tools to convert HDR texture to native colors array.
  80962. */
  80963. var HDRTools = /** @class */ (function () {
  80964. function HDRTools() {
  80965. }
  80966. HDRTools.Ldexp = function (mantissa, exponent) {
  80967. if (exponent > 1023) {
  80968. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80969. }
  80970. if (exponent < -1074) {
  80971. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80972. }
  80973. return mantissa * Math.pow(2, exponent);
  80974. };
  80975. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80976. if (exponent > 0) { /*nonzero pixel*/
  80977. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80978. float32array[index + 0] = red * exponent;
  80979. float32array[index + 1] = green * exponent;
  80980. float32array[index + 2] = blue * exponent;
  80981. }
  80982. else {
  80983. float32array[index + 0] = 0;
  80984. float32array[index + 1] = 0;
  80985. float32array[index + 2] = 0;
  80986. }
  80987. };
  80988. HDRTools.readStringLine = function (uint8array, startIndex) {
  80989. var line = "";
  80990. var character = "";
  80991. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80992. character = String.fromCharCode(uint8array[i]);
  80993. if (character == "\n") {
  80994. break;
  80995. }
  80996. line += character;
  80997. }
  80998. return line;
  80999. };
  81000. /**
  81001. * Reads header information from an RGBE texture stored in a native array.
  81002. * More information on this format are available here:
  81003. * https://en.wikipedia.org/wiki/RGBE_image_format
  81004. *
  81005. * @param uint8array The binary file stored in native array.
  81006. * @return The header information.
  81007. */
  81008. HDRTools.RGBE_ReadHeader = function (uint8array) {
  81009. var height = 0;
  81010. var width = 0;
  81011. var line = this.readStringLine(uint8array, 0);
  81012. if (line[0] != '#' || line[1] != '?') {
  81013. throw "Bad HDR Format.";
  81014. }
  81015. var endOfHeader = false;
  81016. var findFormat = false;
  81017. var lineIndex = 0;
  81018. do {
  81019. lineIndex += (line.length + 1);
  81020. line = this.readStringLine(uint8array, lineIndex);
  81021. if (line == "FORMAT=32-bit_rle_rgbe") {
  81022. findFormat = true;
  81023. }
  81024. else if (line.length == 0) {
  81025. endOfHeader = true;
  81026. }
  81027. } while (!endOfHeader);
  81028. if (!findFormat) {
  81029. throw "HDR Bad header format, unsupported FORMAT";
  81030. }
  81031. lineIndex += (line.length + 1);
  81032. line = this.readStringLine(uint8array, lineIndex);
  81033. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  81034. var match = sizeRegexp.exec(line);
  81035. // TODO. Support +Y and -X if needed.
  81036. if (!match || match.length < 3) {
  81037. throw "HDR Bad header format, no size";
  81038. }
  81039. width = parseInt(match[2]);
  81040. height = parseInt(match[1]);
  81041. if (width < 8 || width > 0x7fff) {
  81042. throw "HDR Bad header format, unsupported size";
  81043. }
  81044. lineIndex += (line.length + 1);
  81045. return {
  81046. height: height,
  81047. width: width,
  81048. dataPosition: lineIndex
  81049. };
  81050. };
  81051. /**
  81052. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  81053. * This RGBE texture needs to store the information as a panorama.
  81054. *
  81055. * More information on this format are available here:
  81056. * https://en.wikipedia.org/wiki/RGBE_image_format
  81057. *
  81058. * @param buffer The binary file stored in an array buffer.
  81059. * @param size The expected size of the extracted cubemap.
  81060. * @return The Cube Map information.
  81061. */
  81062. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  81063. var uint8array = new Uint8Array(buffer);
  81064. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  81065. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81066. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  81067. return cubeMapData;
  81068. };
  81069. /**
  81070. * Returns the pixels data extracted from an RGBE texture.
  81071. * This pixels will be stored left to right up to down in the R G B order in one array.
  81072. *
  81073. * More information on this format are available here:
  81074. * https://en.wikipedia.org/wiki/RGBE_image_format
  81075. *
  81076. * @param uint8array The binary file stored in an array buffer.
  81077. * @param hdrInfo The header information of the file.
  81078. * @return The pixels data in RGB right to left up to down order.
  81079. */
  81080. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  81081. // Keep for multi format supports.
  81082. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81083. };
  81084. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  81085. var num_scanlines = hdrInfo.height;
  81086. var scanline_width = hdrInfo.width;
  81087. var a, b, c, d, count;
  81088. var dataIndex = hdrInfo.dataPosition;
  81089. var index = 0, endIndex = 0, i = 0;
  81090. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  81091. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  81092. // 3 channels of 4 bytes per pixel in float.
  81093. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  81094. var resultArray = new Float32Array(resultBuffer);
  81095. // read in each successive scanline
  81096. while (num_scanlines > 0) {
  81097. a = uint8array[dataIndex++];
  81098. b = uint8array[dataIndex++];
  81099. c = uint8array[dataIndex++];
  81100. d = uint8array[dataIndex++];
  81101. if (a != 2 || b != 2 || (c & 0x80)) {
  81102. // this file is not run length encoded
  81103. throw "HDR Bad header format, not RLE";
  81104. }
  81105. if (((c << 8) | d) != scanline_width) {
  81106. throw "HDR Bad header format, wrong scan line width";
  81107. }
  81108. index = 0;
  81109. // read each of the four channels for the scanline into the buffer
  81110. for (i = 0; i < 4; i++) {
  81111. endIndex = (i + 1) * scanline_width;
  81112. while (index < endIndex) {
  81113. a = uint8array[dataIndex++];
  81114. b = uint8array[dataIndex++];
  81115. if (a > 128) {
  81116. // a run of the same value
  81117. count = a - 128;
  81118. if ((count == 0) || (count > endIndex - index)) {
  81119. throw "HDR Bad Format, bad scanline data (run)";
  81120. }
  81121. while (count-- > 0) {
  81122. scanLineArray[index++] = b;
  81123. }
  81124. }
  81125. else {
  81126. // a non-run
  81127. count = a;
  81128. if ((count == 0) || (count > endIndex - index)) {
  81129. throw "HDR Bad Format, bad scanline data (non-run)";
  81130. }
  81131. scanLineArray[index++] = b;
  81132. if (--count > 0) {
  81133. for (var j = 0; j < count; j++) {
  81134. scanLineArray[index++] = uint8array[dataIndex++];
  81135. }
  81136. }
  81137. }
  81138. }
  81139. }
  81140. // now convert data from buffer into floats
  81141. for (i = 0; i < scanline_width; i++) {
  81142. a = scanLineArray[i];
  81143. b = scanLineArray[i + scanline_width];
  81144. c = scanLineArray[i + 2 * scanline_width];
  81145. d = scanLineArray[i + 3 * scanline_width];
  81146. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  81147. }
  81148. num_scanlines--;
  81149. }
  81150. return resultArray;
  81151. };
  81152. return HDRTools;
  81153. }());
  81154. BABYLON.HDRTools = HDRTools;
  81155. })(BABYLON || (BABYLON = {}));
  81156. //# sourceMappingURL=babylon.hdr.js.map
  81157. var BABYLON;
  81158. (function (BABYLON) {
  81159. /**
  81160. * Sets of helpers addressing the serialization and deserialization of environment texture
  81161. * stored in a BabylonJS env file.
  81162. * Those files are usually stored as .env files.
  81163. */
  81164. var EnvironmentTextureTools = /** @class */ (function () {
  81165. function EnvironmentTextureTools() {
  81166. }
  81167. /**
  81168. * Gets the environment info from an env file.
  81169. * @param data The array buffer containing the .env bytes.
  81170. * @returns the environment file info (the json header) if successfully parsed.
  81171. */
  81172. EnvironmentTextureTools.GetEnvInfo = function (data) {
  81173. var dataView = new DataView(data);
  81174. var pos = 0;
  81175. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81176. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  81177. BABYLON.Tools.Error('Not a babylon environment map');
  81178. return null;
  81179. }
  81180. }
  81181. // Read json manifest - collect characters up to null terminator
  81182. var manifestString = '';
  81183. var charCode = 0x00;
  81184. while ((charCode = dataView.getUint8(pos++))) {
  81185. manifestString += String.fromCharCode(charCode);
  81186. }
  81187. var manifest = JSON.parse(manifestString);
  81188. if (manifest.specular) {
  81189. // Extend the header with the position of the payload.
  81190. manifest.specular.specularDataPosition = pos;
  81191. }
  81192. return manifest;
  81193. };
  81194. /**
  81195. * Creates an environment texture from a loaded cube texture.
  81196. * @param texture defines the cube texture to convert in env file
  81197. * @return a promise containing the environment data if succesfull.
  81198. */
  81199. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  81200. var _this = this;
  81201. var internalTexture = texture.getInternalTexture();
  81202. if (!internalTexture) {
  81203. return Promise.reject("The cube texture is invalid.");
  81204. }
  81205. if (!texture._prefiltered) {
  81206. return Promise.reject("The cube texture is invalid (not prefiltered).");
  81207. }
  81208. var engine = internalTexture.getEngine();
  81209. if (engine && engine.premultipliedAlpha) {
  81210. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  81211. }
  81212. var canvas = engine.getRenderingCanvas();
  81213. if (!canvas) {
  81214. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  81215. }
  81216. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81217. if (!engine.getCaps().textureFloatRender) {
  81218. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81219. if (!engine.getCaps().textureHalfFloatRender) {
  81220. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  81221. }
  81222. }
  81223. var cubeWidth = internalTexture.width;
  81224. var hostingScene = new BABYLON.Scene(engine);
  81225. var specularTextures = {};
  81226. var promises = [];
  81227. // Read and collect all mipmaps data from the cube.
  81228. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  81229. mipmapsCount = Math.round(mipmapsCount);
  81230. var _loop_1 = function (i) {
  81231. var faceWidth = Math.pow(2, mipmapsCount - i);
  81232. var _loop_2 = function (face) {
  81233. var data = texture.readPixels(face, i);
  81234. // Creates a temp texture with the face data.
  81235. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  81236. // And rgbdEncode them.
  81237. var promise = new Promise(function (resolve, reject) {
  81238. var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  81239. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81240. rgbdPostProcess.onApply = function (effect) {
  81241. effect._bindTexture("textureSampler", tempTexture);
  81242. };
  81243. // As the process needs to happen on the main canvas, keep track of the current size
  81244. var currentW = engine.getRenderWidth();
  81245. var currentH = engine.getRenderHeight();
  81246. // Set the desired size for the texture
  81247. engine.setSize(faceWidth, faceWidth);
  81248. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  81249. // Reading datas from WebGL
  81250. canvas.toBlob(function (blob) {
  81251. var fileReader = new FileReader();
  81252. fileReader.onload = function (event) {
  81253. var arrayBuffer = event.target.result;
  81254. specularTextures[i * 6 + face] = arrayBuffer;
  81255. resolve();
  81256. };
  81257. fileReader.readAsArrayBuffer(blob);
  81258. });
  81259. // Reapply the previous canvas size
  81260. engine.setSize(currentW, currentH);
  81261. });
  81262. });
  81263. promises.push(promise);
  81264. };
  81265. // All faces of the cube.
  81266. for (var face = 0; face < 6; face++) {
  81267. _loop_2(face);
  81268. }
  81269. };
  81270. for (var i = 0; i <= mipmapsCount; i++) {
  81271. _loop_1(i);
  81272. }
  81273. // Once all the textures haves been collected as RGBD stored in PNGs
  81274. return Promise.all(promises).then(function () {
  81275. // We can delete the hosting scene keeping track of all the creation objects
  81276. hostingScene.dispose();
  81277. // Creates the json header for the env texture
  81278. var info = {
  81279. version: 1,
  81280. width: cubeWidth,
  81281. irradiance: _this._CreateEnvTextureIrradiance(texture),
  81282. specular: {
  81283. mipmaps: []
  81284. }
  81285. };
  81286. // Sets the specular image data information
  81287. var position = 0;
  81288. for (var i = 0; i <= mipmapsCount; i++) {
  81289. for (var face = 0; face < 6; face++) {
  81290. var byteLength = specularTextures[i * 6 + face].byteLength;
  81291. info.specular.mipmaps.push({
  81292. length: byteLength,
  81293. position: position
  81294. });
  81295. position += byteLength;
  81296. }
  81297. }
  81298. // Encode the JSON as an array buffer
  81299. var infoString = JSON.stringify(info);
  81300. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  81301. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  81302. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  81303. infoView[i] = infoString.charCodeAt(i);
  81304. }
  81305. // Ends up with a null terminator for easier parsing
  81306. infoView[infoString.length] = 0x00;
  81307. // Computes the final required size and creates the storage
  81308. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  81309. var finalBuffer = new ArrayBuffer(totalSize);
  81310. var finalBufferView = new Uint8Array(finalBuffer);
  81311. var dataView = new DataView(finalBuffer);
  81312. // Copy the magic bytes identifying the file in
  81313. var pos = 0;
  81314. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81315. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  81316. }
  81317. // Add the json info
  81318. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  81319. pos += infoBuffer.byteLength;
  81320. // Finally inserts the texture data
  81321. for (var i = 0; i <= mipmapsCount; i++) {
  81322. for (var face = 0; face < 6; face++) {
  81323. var dataBuffer = specularTextures[i * 6 + face];
  81324. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  81325. pos += dataBuffer.byteLength;
  81326. }
  81327. }
  81328. // Voila
  81329. return finalBuffer;
  81330. });
  81331. };
  81332. /**
  81333. * Creates a JSON representation of the spherical data.
  81334. * @param texture defines the texture containing the polynomials
  81335. * @return the JSON representation of the spherical info
  81336. */
  81337. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  81338. var polynmials = texture.sphericalPolynomial;
  81339. if (polynmials == null) {
  81340. return null;
  81341. }
  81342. return {
  81343. polynomials: true,
  81344. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  81345. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  81346. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  81347. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  81348. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  81349. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  81350. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  81351. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  81352. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  81353. };
  81354. };
  81355. /**
  81356. * Uploads the texture info contained in the env file to te GPU.
  81357. * @param texture defines the internal texture to upload to
  81358. * @param arrayBuffer defines the buffer cotaining the data to load
  81359. * @param info defines the texture info retrieved through the GetEnvInfo method
  81360. * @returns a promise
  81361. */
  81362. EnvironmentTextureTools.UploadLevelsAsync = function (texture, arrayBuffer, info) {
  81363. if (info.version !== 1) {
  81364. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  81365. }
  81366. var specularInfo = info.specular;
  81367. if (!specularInfo) {
  81368. // Nothing else parsed so far
  81369. return Promise.resolve();
  81370. }
  81371. // Double checks the enclosed info
  81372. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  81373. mipmapsCount = Math.round(mipmapsCount) + 1;
  81374. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  81375. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  81376. }
  81377. // Gets everything ready.
  81378. var engine = texture.getEngine();
  81379. var expandTexture = false;
  81380. var generateNonLODTextures = false;
  81381. var rgbdPostProcess = null;
  81382. var cubeRtt = null;
  81383. var lodTextures = null;
  81384. var caps = engine.getCaps();
  81385. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81386. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81387. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  81388. // Add extra process if texture lod is not supported
  81389. if (!caps.textureLOD) {
  81390. expandTexture = false;
  81391. generateNonLODTextures = true;
  81392. lodTextures = {};
  81393. }
  81394. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  81395. else if (engine.webGLVersion < 2) {
  81396. expandTexture = false;
  81397. }
  81398. // If half float available we can uncompress the texture
  81399. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  81400. expandTexture = true;
  81401. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81402. }
  81403. // If full float available we can uncompress the texture
  81404. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  81405. expandTexture = true;
  81406. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81407. }
  81408. // Expand the texture if possible
  81409. if (expandTexture) {
  81410. // Simply run through the decode PP
  81411. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  81412. texture._isRGBD = false;
  81413. texture.invertY = false;
  81414. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  81415. generateDepthBuffer: false,
  81416. generateMipMaps: true,
  81417. generateStencilBuffer: false,
  81418. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  81419. type: texture.type,
  81420. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  81421. });
  81422. }
  81423. else {
  81424. texture._isRGBD = true;
  81425. texture.invertY = true;
  81426. // In case of missing support, applies the same patch than DDS files.
  81427. if (generateNonLODTextures) {
  81428. var mipSlices = 3;
  81429. var scale = texture._lodGenerationScale;
  81430. var offset = texture._lodGenerationOffset;
  81431. for (var i = 0; i < mipSlices; i++) {
  81432. //compute LOD from even spacing in smoothness (matching shader calculation)
  81433. var smoothness = i / (mipSlices - 1);
  81434. var roughness = 1 - smoothness;
  81435. var minLODIndex = offset; // roughness = 0
  81436. var maxLODIndex = BABYLON.Scalar.Log2(info.width) * scale + offset; // roughness = 1
  81437. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  81438. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  81439. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  81440. glTextureFromLod.isCube = true;
  81441. glTextureFromLod.invertY = true;
  81442. glTextureFromLod.generateMipMaps = false;
  81443. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  81444. // Wrap in a base texture for easy binding.
  81445. var lodTexture = new BABYLON.BaseTexture(null);
  81446. lodTexture.isCube = true;
  81447. lodTexture._texture = glTextureFromLod;
  81448. lodTextures[mipmapIndex] = lodTexture;
  81449. switch (i) {
  81450. case 0:
  81451. texture._lodTextureLow = lodTexture;
  81452. break;
  81453. case 1:
  81454. texture._lodTextureMid = lodTexture;
  81455. break;
  81456. case 2:
  81457. texture._lodTextureHigh = lodTexture;
  81458. break;
  81459. }
  81460. }
  81461. }
  81462. }
  81463. var promises = [];
  81464. var _loop_3 = function (i) {
  81465. var _loop_4 = function (face) {
  81466. // Retrieves the face data
  81467. var imageData = specularInfo.mipmaps[i * 6 + face];
  81468. var bytes = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageData.position, imageData.length);
  81469. // Constructs an image element from bytes
  81470. var blob = new Blob([bytes], { type: 'image/png' });
  81471. var url = URL.createObjectURL(blob);
  81472. var image = new Image();
  81473. image.src = url;
  81474. // Enqueue promise to upload to the texture.
  81475. var promise = new Promise(function (resolve, reject) {
  81476. ;
  81477. image.onload = function () {
  81478. if (expandTexture) {
  81479. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  81480. reject(message);
  81481. }, image);
  81482. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81483. // Uncompress the data to a RTT
  81484. rgbdPostProcess.onApply = function (effect) {
  81485. effect._bindTexture("textureSampler", tempTexture_1);
  81486. effect.setFloat2("scale", 1, 1);
  81487. };
  81488. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  81489. // Cleanup
  81490. engine.restoreDefaultFramebuffer();
  81491. tempTexture_1.dispose();
  81492. window.URL.revokeObjectURL(url);
  81493. resolve();
  81494. });
  81495. }
  81496. else {
  81497. engine._uploadImageToTexture(texture, face, i, image);
  81498. // Upload the face to the none lod texture support
  81499. if (generateNonLODTextures) {
  81500. var lodTexture = lodTextures[i];
  81501. if (lodTexture) {
  81502. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  81503. }
  81504. }
  81505. resolve();
  81506. }
  81507. };
  81508. image.onerror = function (error) {
  81509. reject(error);
  81510. };
  81511. });
  81512. promises.push(promise);
  81513. };
  81514. // All faces
  81515. for (var face = 0; face < 6; face++) {
  81516. _loop_4(face);
  81517. }
  81518. };
  81519. // All mipmaps
  81520. for (var i = 0; i < mipmapsCount; i++) {
  81521. _loop_3(i);
  81522. }
  81523. // Once all done, finishes the cleanup and return
  81524. return Promise.all(promises).then(function () {
  81525. // Relase temp RTT.
  81526. if (cubeRtt) {
  81527. engine._releaseFramebufferObjects(cubeRtt);
  81528. cubeRtt._swapAndDie(texture);
  81529. }
  81530. // Relase temp Post Process.
  81531. if (rgbdPostProcess) {
  81532. rgbdPostProcess.dispose();
  81533. }
  81534. // Flag internal texture as ready in case they are in use.
  81535. if (generateNonLODTextures) {
  81536. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  81537. texture._lodTextureHigh._texture.isReady = true;
  81538. }
  81539. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  81540. texture._lodTextureMid._texture.isReady = true;
  81541. }
  81542. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  81543. texture._lodTextureLow._texture.isReady = true;
  81544. }
  81545. }
  81546. });
  81547. };
  81548. /**
  81549. * Uploads spherical polynomials information to the texture.
  81550. * @param texture defines the texture we are trying to upload the information to
  81551. * @param arrayBuffer defines the array buffer holding the data
  81552. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  81553. */
  81554. EnvironmentTextureTools.UploadPolynomials = function (texture, arrayBuffer, info) {
  81555. if (info.version !== 1) {
  81556. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  81557. }
  81558. var irradianceInfo = info.irradiance;
  81559. if (!irradianceInfo) {
  81560. return;
  81561. }
  81562. //harmonics now represent radiance
  81563. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  81564. if (irradianceInfo.polynomials) {
  81565. EnvironmentTextureTools._UploadSP(irradianceInfo, texture._sphericalPolynomial);
  81566. }
  81567. else {
  81568. // convert From SH to SP.
  81569. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance(irradianceInfo);
  81570. EnvironmentTextureTools._ConvertSHToSP(irradianceInfo, texture._sphericalPolynomial);
  81571. }
  81572. };
  81573. /**
  81574. * Upload spherical polynomial coefficients to the texture
  81575. * @param polynmials Spherical polynmial coefficients (9)
  81576. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  81577. */
  81578. EnvironmentTextureTools._UploadSP = function (polynmials, outPolynomialCoefficents) {
  81579. outPolynomialCoefficents.x.x = polynmials.x[0];
  81580. outPolynomialCoefficents.x.y = polynmials.x[1];
  81581. outPolynomialCoefficents.x.z = polynmials.x[2];
  81582. outPolynomialCoefficents.y.x = polynmials.y[0];
  81583. outPolynomialCoefficents.y.y = polynmials.y[1];
  81584. outPolynomialCoefficents.y.z = polynmials.y[2];
  81585. outPolynomialCoefficents.z.x = polynmials.z[0];
  81586. outPolynomialCoefficents.z.y = polynmials.z[1];
  81587. outPolynomialCoefficents.z.z = polynmials.z[2];
  81588. //xx
  81589. outPolynomialCoefficents.xx.x = polynmials.xx[0];
  81590. outPolynomialCoefficents.xx.y = polynmials.xx[1];
  81591. outPolynomialCoefficents.xx.z = polynmials.xx[2];
  81592. outPolynomialCoefficents.yy.x = polynmials.yy[0];
  81593. outPolynomialCoefficents.yy.y = polynmials.yy[1];
  81594. outPolynomialCoefficents.yy.z = polynmials.yy[2];
  81595. outPolynomialCoefficents.zz.x = polynmials.zz[0];
  81596. outPolynomialCoefficents.zz.y = polynmials.zz[1];
  81597. outPolynomialCoefficents.zz.z = polynmials.zz[2];
  81598. //yz
  81599. outPolynomialCoefficents.yz.x = polynmials.yz[0];
  81600. outPolynomialCoefficents.yz.y = polynmials.yz[1];
  81601. outPolynomialCoefficents.yz.z = polynmials.yz[2];
  81602. outPolynomialCoefficents.zx.x = polynmials.zx[0];
  81603. outPolynomialCoefficents.zx.y = polynmials.zx[1];
  81604. outPolynomialCoefficents.zx.z = polynmials.zx[2];
  81605. outPolynomialCoefficents.xy.x = polynmials.xy[0];
  81606. outPolynomialCoefficents.xy.y = polynmials.xy[1];
  81607. outPolynomialCoefficents.xy.z = polynmials.xy[2];
  81608. };
  81609. /**
  81610. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81611. * L = (1/pi) * E * rho
  81612. *
  81613. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81614. * @param harmonics Spherical harmonic coefficients (9)
  81615. */
  81616. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  81617. var scaleFactor = 1 / Math.PI;
  81618. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81619. // (The pixel shader must apply albedo after texture fetches, etc).
  81620. harmonics.l00[0] *= scaleFactor;
  81621. harmonics.l00[1] *= scaleFactor;
  81622. harmonics.l00[2] *= scaleFactor;
  81623. harmonics.l1_1[0] *= scaleFactor;
  81624. harmonics.l1_1[1] *= scaleFactor;
  81625. harmonics.l1_1[2] *= scaleFactor;
  81626. harmonics.l10[0] *= scaleFactor;
  81627. harmonics.l10[1] *= scaleFactor;
  81628. harmonics.l10[2] *= scaleFactor;
  81629. harmonics.l11[0] *= scaleFactor;
  81630. harmonics.l11[1] *= scaleFactor;
  81631. harmonics.l11[2] *= scaleFactor;
  81632. harmonics.l2_2[0] *= scaleFactor;
  81633. harmonics.l2_2[1] *= scaleFactor;
  81634. harmonics.l2_2[2] *= scaleFactor;
  81635. harmonics.l2_1[0] *= scaleFactor;
  81636. harmonics.l2_1[1] *= scaleFactor;
  81637. harmonics.l2_1[2] *= scaleFactor;
  81638. harmonics.l20[0] *= scaleFactor;
  81639. harmonics.l20[1] *= scaleFactor;
  81640. harmonics.l20[2] *= scaleFactor;
  81641. harmonics.l21[0] *= scaleFactor;
  81642. harmonics.l21[1] *= scaleFactor;
  81643. harmonics.l21[2] *= scaleFactor;
  81644. harmonics.l22[0] *= scaleFactor;
  81645. harmonics.l22[1] *= scaleFactor;
  81646. harmonics.l22[2] *= scaleFactor;
  81647. };
  81648. /**
  81649. * Convert spherical harmonics to spherical polynomial coefficients
  81650. * @param harmonics Spherical harmonic coefficients (9)
  81651. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  81652. */
  81653. EnvironmentTextureTools._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  81654. var rPi = 1 / Math.PI;
  81655. //x
  81656. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  81657. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  81658. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  81659. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  81660. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  81661. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  81662. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  81663. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  81664. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  81665. //xx
  81666. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  81667. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  81668. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  81669. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  81670. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  81671. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  81672. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  81673. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  81674. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  81675. //yz
  81676. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  81677. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  81678. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  81679. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  81680. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  81681. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  81682. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  81683. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  81684. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  81685. };
  81686. /**
  81687. * Magic number identifying the env file.
  81688. */
  81689. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  81690. return EnvironmentTextureTools;
  81691. }());
  81692. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  81693. })(BABYLON || (BABYLON = {}));
  81694. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  81695. var BABYLON;
  81696. (function (BABYLON) {
  81697. /**
  81698. * This represents a texture coming from an HDR input.
  81699. *
  81700. * The only supported format is currently panorama picture stored in RGBE format.
  81701. * Example of such files can be found on HDRLib: http://hdrlib.com/
  81702. */
  81703. var HDRCubeTexture = /** @class */ (function (_super) {
  81704. __extends(HDRCubeTexture, _super);
  81705. /**
  81706. * Instantiates an HDRTexture from the following parameters.
  81707. *
  81708. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  81709. * @param scene The scene the texture will be used in
  81710. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  81711. * @param noMipmap Forces to not generate the mipmap if true
  81712. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  81713. * @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)
  81714. * @param reserved Reserved flag for internal use.
  81715. */
  81716. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  81717. if (noMipmap === void 0) { noMipmap = false; }
  81718. if (generateHarmonics === void 0) { generateHarmonics = true; }
  81719. if (gammaSpace === void 0) { gammaSpace = false; }
  81720. if (reserved === void 0) { reserved = false; }
  81721. if (onLoad === void 0) { onLoad = null; }
  81722. if (onError === void 0) { onError = null; }
  81723. var _this = _super.call(this, scene) || this;
  81724. _this._generateHarmonics = true;
  81725. _this._onLoad = null;
  81726. _this._onError = null;
  81727. /**
  81728. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  81729. */
  81730. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  81731. _this._isBlocking = true;
  81732. _this._rotationY = 0;
  81733. /**
  81734. * Gets or sets the center of the bounding box associated with the cube texture
  81735. * It must define where the camera used to render the texture was set
  81736. */
  81737. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  81738. if (!url) {
  81739. return _this;
  81740. }
  81741. _this.name = url;
  81742. _this.url = url;
  81743. _this.hasAlpha = false;
  81744. _this.isCube = true;
  81745. _this._textureMatrix = BABYLON.Matrix.Identity();
  81746. _this._onLoad = onLoad;
  81747. _this._onError = onError;
  81748. _this.gammaSpace = gammaSpace;
  81749. _this._noMipmap = noMipmap;
  81750. _this._size = size;
  81751. _this._texture = _this._getFromCache(url, _this._noMipmap);
  81752. if (!_this._texture) {
  81753. if (!scene.useDelayedTextureLoading) {
  81754. _this.loadTexture();
  81755. }
  81756. else {
  81757. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  81758. }
  81759. }
  81760. return _this;
  81761. }
  81762. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  81763. /**
  81764. * Gets wether or not the texture is blocking during loading.
  81765. */
  81766. get: function () {
  81767. return this._isBlocking;
  81768. },
  81769. /**
  81770. * Sets wether or not the texture is blocking during loading.
  81771. */
  81772. set: function (value) {
  81773. this._isBlocking = value;
  81774. },
  81775. enumerable: true,
  81776. configurable: true
  81777. });
  81778. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  81779. /**
  81780. * Gets texture matrix rotation angle around Y axis radians.
  81781. */
  81782. get: function () {
  81783. return this._rotationY;
  81784. },
  81785. /**
  81786. * Sets texture matrix rotation angle around Y axis in radians.
  81787. */
  81788. set: function (value) {
  81789. this._rotationY = value;
  81790. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  81791. },
  81792. enumerable: true,
  81793. configurable: true
  81794. });
  81795. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  81796. get: function () {
  81797. return this._boundingBoxSize;
  81798. },
  81799. /**
  81800. * Gets or sets the size of the bounding box associated with the cube texture
  81801. * When defined, the cubemap will switch to local mode
  81802. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  81803. * @example https://www.babylonjs-playground.com/#RNASML
  81804. */
  81805. set: function (value) {
  81806. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  81807. return;
  81808. }
  81809. this._boundingBoxSize = value;
  81810. var scene = this.getScene();
  81811. if (scene) {
  81812. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  81813. }
  81814. },
  81815. enumerable: true,
  81816. configurable: true
  81817. });
  81818. /**
  81819. * Occurs when the file is raw .hdr file.
  81820. */
  81821. HDRCubeTexture.prototype.loadTexture = function () {
  81822. var _this = this;
  81823. var callback = function (buffer) {
  81824. _this.lodGenerationOffset = 0.0;
  81825. _this.lodGenerationScale = 0.8;
  81826. var scene = _this.getScene();
  81827. if (!scene) {
  81828. return null;
  81829. }
  81830. // Extract the raw linear data.
  81831. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  81832. // Generate harmonics if needed.
  81833. if (_this._generateHarmonics) {
  81834. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  81835. _this.sphericalPolynomial = sphericalPolynomial;
  81836. }
  81837. var results = [];
  81838. var byteArray = null;
  81839. // Push each faces.
  81840. for (var j = 0; j < 6; j++) {
  81841. // Create uintarray fallback.
  81842. if (!scene.getEngine().getCaps().textureFloat) {
  81843. // 3 channels of 1 bytes per pixel in bytes.
  81844. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  81845. byteArray = new Uint8Array(byteBuffer);
  81846. }
  81847. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  81848. // If special cases.
  81849. if (_this.gammaSpace || byteArray) {
  81850. for (var i = 0; i < _this._size * _this._size; i++) {
  81851. // Put in gamma space if requested.
  81852. if (_this.gammaSpace) {
  81853. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  81854. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  81855. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  81856. }
  81857. // Convert to int texture for fallback.
  81858. if (byteArray) {
  81859. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  81860. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  81861. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  81862. // May use luminance instead if the result is not accurate.
  81863. var max = Math.max(Math.max(r, g), b);
  81864. if (max > 255) {
  81865. var scale = 255 / max;
  81866. r *= scale;
  81867. g *= scale;
  81868. b *= scale;
  81869. }
  81870. byteArray[(i * 3) + 0] = r;
  81871. byteArray[(i * 3) + 1] = g;
  81872. byteArray[(i * 3) + 2] = b;
  81873. }
  81874. }
  81875. }
  81876. if (byteArray) {
  81877. results.push(byteArray);
  81878. }
  81879. else {
  81880. results.push(dataFace);
  81881. }
  81882. }
  81883. return results;
  81884. };
  81885. var scene = this.getScene();
  81886. if (scene) {
  81887. 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);
  81888. }
  81889. };
  81890. HDRCubeTexture.prototype.clone = function () {
  81891. var scene = this.getScene();
  81892. if (!scene) {
  81893. return this;
  81894. }
  81895. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  81896. // Base texture
  81897. newTexture.level = this.level;
  81898. newTexture.wrapU = this.wrapU;
  81899. newTexture.wrapV = this.wrapV;
  81900. newTexture.coordinatesIndex = this.coordinatesIndex;
  81901. newTexture.coordinatesMode = this.coordinatesMode;
  81902. return newTexture;
  81903. };
  81904. // Methods
  81905. HDRCubeTexture.prototype.delayLoad = function () {
  81906. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  81907. return;
  81908. }
  81909. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  81910. this._texture = this._getFromCache(this.url, this._noMipmap);
  81911. if (!this._texture) {
  81912. this.loadTexture();
  81913. }
  81914. };
  81915. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  81916. return this._textureMatrix;
  81917. };
  81918. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  81919. this._textureMatrix = value;
  81920. };
  81921. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  81922. var texture = null;
  81923. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  81924. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  81925. texture.name = parsedTexture.name;
  81926. texture.hasAlpha = parsedTexture.hasAlpha;
  81927. texture.level = parsedTexture.level;
  81928. texture.coordinatesMode = parsedTexture.coordinatesMode;
  81929. texture.isBlocking = parsedTexture.isBlocking;
  81930. }
  81931. if (texture) {
  81932. if (parsedTexture.boundingBoxPosition) {
  81933. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  81934. }
  81935. if (parsedTexture.boundingBoxSize) {
  81936. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  81937. }
  81938. if (parsedTexture.rotationY) {
  81939. texture.rotationY = parsedTexture.rotationY;
  81940. }
  81941. }
  81942. return texture;
  81943. };
  81944. HDRCubeTexture.prototype.serialize = function () {
  81945. if (!this.name) {
  81946. return null;
  81947. }
  81948. var serializationObject = {};
  81949. serializationObject.name = this.name;
  81950. serializationObject.hasAlpha = this.hasAlpha;
  81951. serializationObject.isCube = true;
  81952. serializationObject.level = this.level;
  81953. serializationObject.size = this._size;
  81954. serializationObject.coordinatesMode = this.coordinatesMode;
  81955. serializationObject.useInGammaSpace = this.gammaSpace;
  81956. serializationObject.generateHarmonics = this._generateHarmonics;
  81957. serializationObject.customType = "BABYLON.HDRCubeTexture";
  81958. serializationObject.noMipmap = this._noMipmap;
  81959. serializationObject.isBlocking = this._isBlocking;
  81960. serializationObject.rotationY = this._rotationY;
  81961. return serializationObject;
  81962. };
  81963. HDRCubeTexture._facesMapping = [
  81964. "right",
  81965. "left",
  81966. "up",
  81967. "down",
  81968. "front",
  81969. "back"
  81970. ];
  81971. return HDRCubeTexture;
  81972. }(BABYLON.BaseTexture));
  81973. BABYLON.HDRCubeTexture = HDRCubeTexture;
  81974. })(BABYLON || (BABYLON = {}));
  81975. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  81976. var BABYLON;
  81977. (function (BABYLON) {
  81978. var IndexedVector2 = /** @class */ (function (_super) {
  81979. __extends(IndexedVector2, _super);
  81980. function IndexedVector2(original, index) {
  81981. var _this = _super.call(this, original.x, original.y) || this;
  81982. _this.index = index;
  81983. return _this;
  81984. }
  81985. return IndexedVector2;
  81986. }(BABYLON.Vector2));
  81987. var PolygonPoints = /** @class */ (function () {
  81988. function PolygonPoints() {
  81989. this.elements = new Array();
  81990. }
  81991. PolygonPoints.prototype.add = function (originalPoints) {
  81992. var _this = this;
  81993. var result = new Array();
  81994. originalPoints.forEach(function (point) {
  81995. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  81996. var newPoint = new IndexedVector2(point, _this.elements.length);
  81997. result.push(newPoint);
  81998. _this.elements.push(newPoint);
  81999. }
  82000. });
  82001. return result;
  82002. };
  82003. PolygonPoints.prototype.computeBounds = function () {
  82004. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82005. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82006. this.elements.forEach(function (point) {
  82007. // x
  82008. if (point.x < lmin.x) {
  82009. lmin.x = point.x;
  82010. }
  82011. else if (point.x > lmax.x) {
  82012. lmax.x = point.x;
  82013. }
  82014. // y
  82015. if (point.y < lmin.y) {
  82016. lmin.y = point.y;
  82017. }
  82018. else if (point.y > lmax.y) {
  82019. lmax.y = point.y;
  82020. }
  82021. });
  82022. return {
  82023. min: lmin,
  82024. max: lmax,
  82025. width: lmax.x - lmin.x,
  82026. height: lmax.y - lmin.y
  82027. };
  82028. };
  82029. return PolygonPoints;
  82030. }());
  82031. var Polygon = /** @class */ (function () {
  82032. function Polygon() {
  82033. }
  82034. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  82035. return [
  82036. new BABYLON.Vector2(xmin, ymin),
  82037. new BABYLON.Vector2(xmax, ymin),
  82038. new BABYLON.Vector2(xmax, ymax),
  82039. new BABYLON.Vector2(xmin, ymax)
  82040. ];
  82041. };
  82042. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  82043. if (cx === void 0) { cx = 0; }
  82044. if (cy === void 0) { cy = 0; }
  82045. if (numberOfSides === void 0) { numberOfSides = 32; }
  82046. var result = new Array();
  82047. var angle = 0;
  82048. var increment = (Math.PI * 2) / numberOfSides;
  82049. for (var i = 0; i < numberOfSides; i++) {
  82050. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  82051. angle -= increment;
  82052. }
  82053. return result;
  82054. };
  82055. Polygon.Parse = function (input) {
  82056. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  82057. var i, result = [];
  82058. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  82059. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  82060. }
  82061. return result;
  82062. };
  82063. Polygon.StartingAt = function (x, y) {
  82064. return BABYLON.Path2.StartingAt(x, y);
  82065. };
  82066. return Polygon;
  82067. }());
  82068. BABYLON.Polygon = Polygon;
  82069. var PolygonMeshBuilder = /** @class */ (function () {
  82070. function PolygonMeshBuilder(name, contours, scene) {
  82071. this._points = new PolygonPoints();
  82072. this._outlinepoints = new PolygonPoints();
  82073. this._holes = new Array();
  82074. this._epoints = new Array();
  82075. this._eholes = new Array();
  82076. this._name = name;
  82077. this._scene = scene;
  82078. var points;
  82079. if (contours instanceof BABYLON.Path2) {
  82080. points = contours.getPoints();
  82081. }
  82082. else {
  82083. points = contours;
  82084. }
  82085. this._addToepoint(points);
  82086. this._points.add(points);
  82087. this._outlinepoints.add(points);
  82088. if (typeof earcut === 'undefined') {
  82089. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  82090. }
  82091. }
  82092. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  82093. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  82094. var p = points_1[_i];
  82095. this._epoints.push(p.x, p.y);
  82096. }
  82097. };
  82098. PolygonMeshBuilder.prototype.addHole = function (hole) {
  82099. this._points.add(hole);
  82100. var holepoints = new PolygonPoints();
  82101. holepoints.add(hole);
  82102. this._holes.push(holepoints);
  82103. this._eholes.push(this._epoints.length / 2);
  82104. this._addToepoint(hole);
  82105. return this;
  82106. };
  82107. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  82108. var _this = this;
  82109. if (updatable === void 0) { updatable = false; }
  82110. if (depth === void 0) { depth = 0; }
  82111. var result = new BABYLON.Mesh(this._name, this._scene);
  82112. var normals = new Array();
  82113. var positions = new Array();
  82114. var uvs = new Array();
  82115. var bounds = this._points.computeBounds();
  82116. this._points.elements.forEach(function (p) {
  82117. normals.push(0, 1.0, 0);
  82118. positions.push(p.x, 0, p.y);
  82119. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  82120. });
  82121. var indices = new Array();
  82122. var res = earcut(this._epoints, this._eholes, 2);
  82123. for (var i = 0; i < res.length; i++) {
  82124. indices.push(res[i]);
  82125. }
  82126. if (depth > 0) {
  82127. var positionscount = (positions.length / 3); //get the current pointcount
  82128. this._points.elements.forEach(function (p) {
  82129. normals.push(0, -1.0, 0);
  82130. positions.push(p.x, -depth, p.y);
  82131. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  82132. });
  82133. var totalCount = indices.length;
  82134. for (var i = 0; i < totalCount; i += 3) {
  82135. var i0 = indices[i + 0];
  82136. var i1 = indices[i + 1];
  82137. var i2 = indices[i + 2];
  82138. indices.push(i2 + positionscount);
  82139. indices.push(i1 + positionscount);
  82140. indices.push(i0 + positionscount);
  82141. }
  82142. //Add the sides
  82143. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  82144. this._holes.forEach(function (hole) {
  82145. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  82146. });
  82147. }
  82148. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  82149. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  82150. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  82151. result.setIndices(indices);
  82152. return result;
  82153. };
  82154. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  82155. var StartIndex = positions.length / 3;
  82156. var ulength = 0;
  82157. for (var i = 0; i < points.elements.length; i++) {
  82158. var p = points.elements[i];
  82159. var p1;
  82160. if ((i + 1) > points.elements.length - 1) {
  82161. p1 = points.elements[0];
  82162. }
  82163. else {
  82164. p1 = points.elements[i + 1];
  82165. }
  82166. positions.push(p.x, 0, p.y);
  82167. positions.push(p.x, -depth, p.y);
  82168. positions.push(p1.x, 0, p1.y);
  82169. positions.push(p1.x, -depth, p1.y);
  82170. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  82171. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  82172. var v3 = v2.subtract(v1);
  82173. var v4 = new BABYLON.Vector3(0, 1, 0);
  82174. var vn = BABYLON.Vector3.Cross(v3, v4);
  82175. vn = vn.normalize();
  82176. uvs.push(ulength / bounds.width, 0);
  82177. uvs.push(ulength / bounds.width, 1);
  82178. ulength += v3.length();
  82179. uvs.push((ulength / bounds.width), 0);
  82180. uvs.push((ulength / bounds.width), 1);
  82181. if (!flip) {
  82182. normals.push(-vn.x, -vn.y, -vn.z);
  82183. normals.push(-vn.x, -vn.y, -vn.z);
  82184. normals.push(-vn.x, -vn.y, -vn.z);
  82185. normals.push(-vn.x, -vn.y, -vn.z);
  82186. indices.push(StartIndex);
  82187. indices.push(StartIndex + 1);
  82188. indices.push(StartIndex + 2);
  82189. indices.push(StartIndex + 1);
  82190. indices.push(StartIndex + 3);
  82191. indices.push(StartIndex + 2);
  82192. }
  82193. else {
  82194. normals.push(vn.x, vn.y, vn.z);
  82195. normals.push(vn.x, vn.y, vn.z);
  82196. normals.push(vn.x, vn.y, vn.z);
  82197. normals.push(vn.x, vn.y, vn.z);
  82198. indices.push(StartIndex);
  82199. indices.push(StartIndex + 2);
  82200. indices.push(StartIndex + 1);
  82201. indices.push(StartIndex + 1);
  82202. indices.push(StartIndex + 2);
  82203. indices.push(StartIndex + 3);
  82204. }
  82205. StartIndex += 4;
  82206. }
  82207. ;
  82208. };
  82209. return PolygonMeshBuilder;
  82210. }());
  82211. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  82212. })(BABYLON || (BABYLON = {}));
  82213. //# sourceMappingURL=babylon.polygonMesh.js.map
  82214. var BABYLON;
  82215. (function (BABYLON) {
  82216. // Unique ID when we import meshes from Babylon to CSG
  82217. var currentCSGMeshId = 0;
  82218. // # class Vertex
  82219. // Represents a vertex of a polygon. Use your own vertex class instead of this
  82220. // one to provide additional features like texture coordinates and vertex
  82221. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  82222. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  82223. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  82224. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  82225. // is not used anywhere else.
  82226. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  82227. var Vertex = /** @class */ (function () {
  82228. function Vertex(pos, normal, uv) {
  82229. this.pos = pos;
  82230. this.normal = normal;
  82231. this.uv = uv;
  82232. }
  82233. Vertex.prototype.clone = function () {
  82234. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  82235. };
  82236. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  82237. // orientation of a polygon is flipped.
  82238. Vertex.prototype.flip = function () {
  82239. this.normal = this.normal.scale(-1);
  82240. };
  82241. // Create a new vertex between this vertex and `other` by linearly
  82242. // interpolating all properties using a parameter of `t`. Subclasses should
  82243. // override this to interpolate additional properties.
  82244. Vertex.prototype.interpolate = function (other, t) {
  82245. 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));
  82246. };
  82247. return Vertex;
  82248. }());
  82249. // # class Plane
  82250. // Represents a plane in 3D space.
  82251. var Plane = /** @class */ (function () {
  82252. function Plane(normal, w) {
  82253. this.normal = normal;
  82254. this.w = w;
  82255. }
  82256. Plane.FromPoints = function (a, b, c) {
  82257. var v0 = c.subtract(a);
  82258. var v1 = b.subtract(a);
  82259. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  82260. return null;
  82261. }
  82262. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  82263. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  82264. };
  82265. Plane.prototype.clone = function () {
  82266. return new Plane(this.normal.clone(), this.w);
  82267. };
  82268. Plane.prototype.flip = function () {
  82269. this.normal.scaleInPlace(-1);
  82270. this.w = -this.w;
  82271. };
  82272. // Split `polygon` by this plane if needed, then put the polygon or polygon
  82273. // fragments in the appropriate lists. Coplanar polygons go into either
  82274. // `coplanarFront` or `coplanarBack` depending on their orientation with
  82275. // respect to this plane. Polygons in front or in back of this plane go into
  82276. // either `front` or `back`.
  82277. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  82278. var COPLANAR = 0;
  82279. var FRONT = 1;
  82280. var BACK = 2;
  82281. var SPANNING = 3;
  82282. // Classify each point as well as the entire polygon into one of the above
  82283. // four classes.
  82284. var polygonType = 0;
  82285. var types = [];
  82286. var i;
  82287. var t;
  82288. for (i = 0; i < polygon.vertices.length; i++) {
  82289. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  82290. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  82291. polygonType |= type;
  82292. types.push(type);
  82293. }
  82294. // Put the polygon in the correct list, splitting it when necessary.
  82295. switch (polygonType) {
  82296. case COPLANAR:
  82297. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  82298. break;
  82299. case FRONT:
  82300. front.push(polygon);
  82301. break;
  82302. case BACK:
  82303. back.push(polygon);
  82304. break;
  82305. case SPANNING:
  82306. var f = [], b = [];
  82307. for (i = 0; i < polygon.vertices.length; i++) {
  82308. var j = (i + 1) % polygon.vertices.length;
  82309. var ti = types[i], tj = types[j];
  82310. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  82311. if (ti !== BACK)
  82312. f.push(vi);
  82313. if (ti !== FRONT)
  82314. b.push(ti !== BACK ? vi.clone() : vi);
  82315. if ((ti | tj) === SPANNING) {
  82316. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  82317. var v = vi.interpolate(vj, t);
  82318. f.push(v);
  82319. b.push(v.clone());
  82320. }
  82321. }
  82322. var poly;
  82323. if (f.length >= 3) {
  82324. poly = new Polygon(f, polygon.shared);
  82325. if (poly.plane)
  82326. front.push(poly);
  82327. }
  82328. if (b.length >= 3) {
  82329. poly = new Polygon(b, polygon.shared);
  82330. if (poly.plane)
  82331. back.push(poly);
  82332. }
  82333. break;
  82334. }
  82335. };
  82336. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  82337. // point is on the plane.
  82338. Plane.EPSILON = 1e-5;
  82339. return Plane;
  82340. }());
  82341. // # class Polygon
  82342. // Represents a convex polygon. The vertices used to initialize a polygon must
  82343. // be coplanar and form a convex loop.
  82344. //
  82345. // Each convex polygon has a `shared` property, which is shared between all
  82346. // polygons that are clones of each other or were split from the same polygon.
  82347. // This can be used to define per-polygon properties (such as surface color).
  82348. var Polygon = /** @class */ (function () {
  82349. function Polygon(vertices, shared) {
  82350. this.vertices = vertices;
  82351. this.shared = shared;
  82352. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  82353. }
  82354. Polygon.prototype.clone = function () {
  82355. var vertices = this.vertices.map(function (v) { return v.clone(); });
  82356. return new Polygon(vertices, this.shared);
  82357. };
  82358. Polygon.prototype.flip = function () {
  82359. this.vertices.reverse().map(function (v) { v.flip(); });
  82360. this.plane.flip();
  82361. };
  82362. return Polygon;
  82363. }());
  82364. // # class Node
  82365. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  82366. // by picking a polygon to split along. That polygon (and all other coplanar
  82367. // polygons) are added directly to that node and the other polygons are added to
  82368. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  82369. // no distinction between internal and leaf nodes.
  82370. var Node = /** @class */ (function () {
  82371. function Node(polygons) {
  82372. this.plane = null;
  82373. this.front = null;
  82374. this.back = null;
  82375. this.polygons = new Array();
  82376. if (polygons) {
  82377. this.build(polygons);
  82378. }
  82379. }
  82380. Node.prototype.clone = function () {
  82381. var node = new Node();
  82382. node.plane = this.plane && this.plane.clone();
  82383. node.front = this.front && this.front.clone();
  82384. node.back = this.back && this.back.clone();
  82385. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  82386. return node;
  82387. };
  82388. // Convert solid space to empty space and empty space to solid space.
  82389. Node.prototype.invert = function () {
  82390. for (var i = 0; i < this.polygons.length; i++) {
  82391. this.polygons[i].flip();
  82392. }
  82393. if (this.plane) {
  82394. this.plane.flip();
  82395. }
  82396. if (this.front) {
  82397. this.front.invert();
  82398. }
  82399. if (this.back) {
  82400. this.back.invert();
  82401. }
  82402. var temp = this.front;
  82403. this.front = this.back;
  82404. this.back = temp;
  82405. };
  82406. // Recursively remove all polygons in `polygons` that are inside this BSP
  82407. // tree.
  82408. Node.prototype.clipPolygons = function (polygons) {
  82409. if (!this.plane)
  82410. return polygons.slice();
  82411. var front = new Array(), back = new Array();
  82412. for (var i = 0; i < polygons.length; i++) {
  82413. this.plane.splitPolygon(polygons[i], front, back, front, back);
  82414. }
  82415. if (this.front) {
  82416. front = this.front.clipPolygons(front);
  82417. }
  82418. if (this.back) {
  82419. back = this.back.clipPolygons(back);
  82420. }
  82421. else {
  82422. back = [];
  82423. }
  82424. return front.concat(back);
  82425. };
  82426. // Remove all polygons in this BSP tree that are inside the other BSP tree
  82427. // `bsp`.
  82428. Node.prototype.clipTo = function (bsp) {
  82429. this.polygons = bsp.clipPolygons(this.polygons);
  82430. if (this.front)
  82431. this.front.clipTo(bsp);
  82432. if (this.back)
  82433. this.back.clipTo(bsp);
  82434. };
  82435. // Return a list of all polygons in this BSP tree.
  82436. Node.prototype.allPolygons = function () {
  82437. var polygons = this.polygons.slice();
  82438. if (this.front)
  82439. polygons = polygons.concat(this.front.allPolygons());
  82440. if (this.back)
  82441. polygons = polygons.concat(this.back.allPolygons());
  82442. return polygons;
  82443. };
  82444. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  82445. // new polygons are filtered down to the bottom of the tree and become new
  82446. // nodes there. Each set of polygons is partitioned using the first polygon
  82447. // (no heuristic is used to pick a good split).
  82448. Node.prototype.build = function (polygons) {
  82449. if (!polygons.length)
  82450. return;
  82451. if (!this.plane)
  82452. this.plane = polygons[0].plane.clone();
  82453. var front = new Array(), back = new Array();
  82454. for (var i = 0; i < polygons.length; i++) {
  82455. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  82456. }
  82457. if (front.length) {
  82458. if (!this.front)
  82459. this.front = new Node();
  82460. this.front.build(front);
  82461. }
  82462. if (back.length) {
  82463. if (!this.back)
  82464. this.back = new Node();
  82465. this.back.build(back);
  82466. }
  82467. };
  82468. return Node;
  82469. }());
  82470. var CSG = /** @class */ (function () {
  82471. function CSG() {
  82472. this.polygons = new Array();
  82473. }
  82474. // Convert BABYLON.Mesh to BABYLON.CSG
  82475. CSG.FromMesh = function (mesh) {
  82476. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  82477. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  82478. if (mesh instanceof BABYLON.Mesh) {
  82479. mesh.computeWorldMatrix(true);
  82480. matrix = mesh.getWorldMatrix();
  82481. meshPosition = mesh.position.clone();
  82482. meshRotation = mesh.rotation.clone();
  82483. if (mesh.rotationQuaternion) {
  82484. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  82485. }
  82486. meshScaling = mesh.scaling.clone();
  82487. }
  82488. else {
  82489. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  82490. }
  82491. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82492. var subMeshes = mesh.subMeshes;
  82493. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  82494. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  82495. vertices = [];
  82496. for (var j = 0; j < 3; j++) {
  82497. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  82498. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  82499. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  82500. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  82501. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  82502. vertex = new Vertex(position, normal, uv);
  82503. vertices.push(vertex);
  82504. }
  82505. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  82506. // To handle the case of degenerated triangle
  82507. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  82508. if (polygon.plane)
  82509. polygons.push(polygon);
  82510. }
  82511. }
  82512. var csg = CSG.FromPolygons(polygons);
  82513. csg.matrix = matrix;
  82514. csg.position = meshPosition;
  82515. csg.rotation = meshRotation;
  82516. csg.scaling = meshScaling;
  82517. csg.rotationQuaternion = meshRotationQuaternion;
  82518. currentCSGMeshId++;
  82519. return csg;
  82520. };
  82521. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  82522. CSG.FromPolygons = function (polygons) {
  82523. var csg = new CSG();
  82524. csg.polygons = polygons;
  82525. return csg;
  82526. };
  82527. CSG.prototype.clone = function () {
  82528. var csg = new CSG();
  82529. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  82530. csg.copyTransformAttributes(this);
  82531. return csg;
  82532. };
  82533. CSG.prototype.union = function (csg) {
  82534. var a = new Node(this.clone().polygons);
  82535. var b = new Node(csg.clone().polygons);
  82536. a.clipTo(b);
  82537. b.clipTo(a);
  82538. b.invert();
  82539. b.clipTo(a);
  82540. b.invert();
  82541. a.build(b.allPolygons());
  82542. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82543. };
  82544. CSG.prototype.unionInPlace = function (csg) {
  82545. var a = new Node(this.polygons);
  82546. var b = new Node(csg.polygons);
  82547. a.clipTo(b);
  82548. b.clipTo(a);
  82549. b.invert();
  82550. b.clipTo(a);
  82551. b.invert();
  82552. a.build(b.allPolygons());
  82553. this.polygons = a.allPolygons();
  82554. };
  82555. CSG.prototype.subtract = function (csg) {
  82556. var a = new Node(this.clone().polygons);
  82557. var b = new Node(csg.clone().polygons);
  82558. a.invert();
  82559. a.clipTo(b);
  82560. b.clipTo(a);
  82561. b.invert();
  82562. b.clipTo(a);
  82563. b.invert();
  82564. a.build(b.allPolygons());
  82565. a.invert();
  82566. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82567. };
  82568. CSG.prototype.subtractInPlace = function (csg) {
  82569. var a = new Node(this.polygons);
  82570. var b = new Node(csg.polygons);
  82571. a.invert();
  82572. a.clipTo(b);
  82573. b.clipTo(a);
  82574. b.invert();
  82575. b.clipTo(a);
  82576. b.invert();
  82577. a.build(b.allPolygons());
  82578. a.invert();
  82579. this.polygons = a.allPolygons();
  82580. };
  82581. CSG.prototype.intersect = function (csg) {
  82582. var a = new Node(this.clone().polygons);
  82583. var b = new Node(csg.clone().polygons);
  82584. a.invert();
  82585. b.clipTo(a);
  82586. b.invert();
  82587. a.clipTo(b);
  82588. b.clipTo(a);
  82589. a.build(b.allPolygons());
  82590. a.invert();
  82591. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82592. };
  82593. CSG.prototype.intersectInPlace = function (csg) {
  82594. var a = new Node(this.polygons);
  82595. var b = new Node(csg.polygons);
  82596. a.invert();
  82597. b.clipTo(a);
  82598. b.invert();
  82599. a.clipTo(b);
  82600. b.clipTo(a);
  82601. a.build(b.allPolygons());
  82602. a.invert();
  82603. this.polygons = a.allPolygons();
  82604. };
  82605. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  82606. // not modified.
  82607. CSG.prototype.inverse = function () {
  82608. var csg = this.clone();
  82609. csg.inverseInPlace();
  82610. return csg;
  82611. };
  82612. CSG.prototype.inverseInPlace = function () {
  82613. this.polygons.map(function (p) { p.flip(); });
  82614. };
  82615. // This is used to keep meshes transformations so they can be restored
  82616. // when we build back a Babylon Mesh
  82617. // NB : All CSG operations are performed in world coordinates
  82618. CSG.prototype.copyTransformAttributes = function (csg) {
  82619. this.matrix = csg.matrix;
  82620. this.position = csg.position;
  82621. this.rotation = csg.rotation;
  82622. this.scaling = csg.scaling;
  82623. this.rotationQuaternion = csg.rotationQuaternion;
  82624. return this;
  82625. };
  82626. // Build Raw mesh from CSG
  82627. // Coordinates here are in world space
  82628. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  82629. var matrix = this.matrix.clone();
  82630. matrix.invert();
  82631. 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;
  82632. if (keepSubMeshes) {
  82633. // Sort Polygons, since subMeshes are indices range
  82634. polygons.sort(function (a, b) {
  82635. if (a.shared.meshId === b.shared.meshId) {
  82636. return a.shared.subMeshId - b.shared.subMeshId;
  82637. }
  82638. else {
  82639. return a.shared.meshId - b.shared.meshId;
  82640. }
  82641. });
  82642. }
  82643. for (var i = 0, il = polygons.length; i < il; i++) {
  82644. polygon = polygons[i];
  82645. // Building SubMeshes
  82646. if (!subMesh_dict[polygon.shared.meshId]) {
  82647. subMesh_dict[polygon.shared.meshId] = {};
  82648. }
  82649. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  82650. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  82651. indexStart: +Infinity,
  82652. indexEnd: -Infinity,
  82653. materialIndex: polygon.shared.materialIndex
  82654. };
  82655. }
  82656. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  82657. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  82658. polygonIndices[0] = 0;
  82659. polygonIndices[1] = j - 1;
  82660. polygonIndices[2] = j;
  82661. for (var k = 0; k < 3; k++) {
  82662. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  82663. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  82664. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  82665. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  82666. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  82667. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  82668. // Check if 2 points can be merged
  82669. if (!(typeof vertex_idx !== 'undefined' &&
  82670. normals[vertex_idx * 3] === localNormal.x &&
  82671. normals[vertex_idx * 3 + 1] === localNormal.y &&
  82672. normals[vertex_idx * 3 + 2] === localNormal.z &&
  82673. uvs[vertex_idx * 2] === uv.x &&
  82674. uvs[vertex_idx * 2 + 1] === uv.y)) {
  82675. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  82676. uvs.push(uv.x, uv.y);
  82677. normals.push(normal.x, normal.y, normal.z);
  82678. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  82679. }
  82680. indices.push(vertex_idx);
  82681. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  82682. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  82683. currentIndex++;
  82684. }
  82685. }
  82686. }
  82687. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  82688. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  82689. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  82690. mesh.setIndices(indices, null);
  82691. if (keepSubMeshes) {
  82692. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  82693. var materialIndexOffset = 0, materialMaxIndex;
  82694. mesh.subMeshes = new Array();
  82695. for (var m in subMesh_dict) {
  82696. materialMaxIndex = -1;
  82697. for (var sm in subMesh_dict[m]) {
  82698. subMesh_obj = subMesh_dict[m][sm];
  82699. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  82700. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  82701. }
  82702. materialIndexOffset += ++materialMaxIndex;
  82703. }
  82704. }
  82705. return mesh;
  82706. };
  82707. // Build Mesh from CSG taking material and transforms into account
  82708. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  82709. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  82710. mesh.material = material;
  82711. mesh.position.copyFrom(this.position);
  82712. mesh.rotation.copyFrom(this.rotation);
  82713. if (this.rotationQuaternion) {
  82714. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  82715. }
  82716. mesh.scaling.copyFrom(this.scaling);
  82717. mesh.computeWorldMatrix(true);
  82718. return mesh;
  82719. };
  82720. return CSG;
  82721. }());
  82722. BABYLON.CSG = CSG;
  82723. })(BABYLON || (BABYLON = {}));
  82724. //# sourceMappingURL=babylon.csg.js.map
  82725. var BABYLON;
  82726. (function (BABYLON) {
  82727. var LensFlare = /** @class */ (function () {
  82728. function LensFlare(size, position, color, imgUrl, system) {
  82729. this.size = size;
  82730. this.position = position;
  82731. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  82732. this.color = color || new BABYLON.Color3(1, 1, 1);
  82733. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  82734. this._system = system;
  82735. system.lensFlares.push(this);
  82736. }
  82737. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  82738. return new LensFlare(size, position, color, imgUrl, system);
  82739. };
  82740. LensFlare.prototype.dispose = function () {
  82741. if (this.texture) {
  82742. this.texture.dispose();
  82743. }
  82744. // Remove from scene
  82745. var index = this._system.lensFlares.indexOf(this);
  82746. this._system.lensFlares.splice(index, 1);
  82747. };
  82748. ;
  82749. return LensFlare;
  82750. }());
  82751. BABYLON.LensFlare = LensFlare;
  82752. })(BABYLON || (BABYLON = {}));
  82753. //# sourceMappingURL=babylon.lensFlare.js.map
  82754. var BABYLON;
  82755. (function (BABYLON) {
  82756. var LensFlareSystem = /** @class */ (function () {
  82757. function LensFlareSystem(name, emitter, scene) {
  82758. this.name = name;
  82759. this.lensFlares = new Array();
  82760. this.borderLimit = 300;
  82761. this.viewportBorder = 0;
  82762. this.layerMask = 0x0FFFFFFF;
  82763. this._vertexBuffers = {};
  82764. this._isEnabled = true;
  82765. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82766. this._emitter = emitter;
  82767. this.id = name;
  82768. scene.lensFlareSystems.push(this);
  82769. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  82770. var engine = scene.getEngine();
  82771. // VBO
  82772. var vertices = [];
  82773. vertices.push(1, 1);
  82774. vertices.push(-1, 1);
  82775. vertices.push(-1, -1);
  82776. vertices.push(1, -1);
  82777. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82778. // Indices
  82779. var indices = [];
  82780. indices.push(0);
  82781. indices.push(1);
  82782. indices.push(2);
  82783. indices.push(0);
  82784. indices.push(2);
  82785. indices.push(3);
  82786. this._indexBuffer = engine.createIndexBuffer(indices);
  82787. // Effects
  82788. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  82789. }
  82790. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  82791. get: function () {
  82792. return this._isEnabled;
  82793. },
  82794. set: function (value) {
  82795. this._isEnabled = value;
  82796. },
  82797. enumerable: true,
  82798. configurable: true
  82799. });
  82800. LensFlareSystem.prototype.getScene = function () {
  82801. return this._scene;
  82802. };
  82803. LensFlareSystem.prototype.getEmitter = function () {
  82804. return this._emitter;
  82805. };
  82806. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  82807. this._emitter = newEmitter;
  82808. };
  82809. LensFlareSystem.prototype.getEmitterPosition = function () {
  82810. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  82811. };
  82812. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  82813. var position = this.getEmitterPosition();
  82814. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  82815. this._positionX = position.x;
  82816. this._positionY = position.y;
  82817. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  82818. if (this.viewportBorder > 0) {
  82819. globalViewport.x -= this.viewportBorder;
  82820. globalViewport.y -= this.viewportBorder;
  82821. globalViewport.width += this.viewportBorder * 2;
  82822. globalViewport.height += this.viewportBorder * 2;
  82823. position.x += this.viewportBorder;
  82824. position.y += this.viewportBorder;
  82825. this._positionX += this.viewportBorder;
  82826. this._positionY += this.viewportBorder;
  82827. }
  82828. if (position.z > 0) {
  82829. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  82830. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  82831. return true;
  82832. }
  82833. return true;
  82834. }
  82835. return false;
  82836. };
  82837. LensFlareSystem.prototype._isVisible = function () {
  82838. if (!this._isEnabled || !this._scene.activeCamera) {
  82839. return false;
  82840. }
  82841. var emitterPosition = this.getEmitterPosition();
  82842. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  82843. var distance = direction.length();
  82844. direction.normalize();
  82845. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  82846. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  82847. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  82848. };
  82849. LensFlareSystem.prototype.render = function () {
  82850. if (!this._effect.isReady() || !this._scene.activeCamera)
  82851. return false;
  82852. var engine = this._scene.getEngine();
  82853. var viewport = this._scene.activeCamera.viewport;
  82854. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  82855. // Position
  82856. if (!this.computeEffectivePosition(globalViewport)) {
  82857. return false;
  82858. }
  82859. // Visibility
  82860. if (!this._isVisible()) {
  82861. return false;
  82862. }
  82863. // Intensity
  82864. var awayX;
  82865. var awayY;
  82866. if (this._positionX < this.borderLimit + globalViewport.x) {
  82867. awayX = this.borderLimit + globalViewport.x - this._positionX;
  82868. }
  82869. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  82870. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  82871. }
  82872. else {
  82873. awayX = 0;
  82874. }
  82875. if (this._positionY < this.borderLimit + globalViewport.y) {
  82876. awayY = this.borderLimit + globalViewport.y - this._positionY;
  82877. }
  82878. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  82879. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  82880. }
  82881. else {
  82882. awayY = 0;
  82883. }
  82884. var away = (awayX > awayY) ? awayX : awayY;
  82885. away -= this.viewportBorder;
  82886. if (away > this.borderLimit) {
  82887. away = this.borderLimit;
  82888. }
  82889. var intensity = 1.0 - (away / this.borderLimit);
  82890. if (intensity < 0) {
  82891. return false;
  82892. }
  82893. if (intensity > 1.0) {
  82894. intensity = 1.0;
  82895. }
  82896. if (this.viewportBorder > 0) {
  82897. globalViewport.x += this.viewportBorder;
  82898. globalViewport.y += this.viewportBorder;
  82899. globalViewport.width -= this.viewportBorder * 2;
  82900. globalViewport.height -= this.viewportBorder * 2;
  82901. this._positionX -= this.viewportBorder;
  82902. this._positionY -= this.viewportBorder;
  82903. }
  82904. // Position
  82905. var centerX = globalViewport.x + globalViewport.width / 2;
  82906. var centerY = globalViewport.y + globalViewport.height / 2;
  82907. var distX = centerX - this._positionX;
  82908. var distY = centerY - this._positionY;
  82909. // Effects
  82910. engine.enableEffect(this._effect);
  82911. engine.setState(false);
  82912. engine.setDepthBuffer(false);
  82913. // VBOs
  82914. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  82915. // Flares
  82916. for (var index = 0; index < this.lensFlares.length; index++) {
  82917. var flare = this.lensFlares[index];
  82918. engine.setAlphaMode(flare.alphaMode);
  82919. var x = centerX - (distX * flare.position);
  82920. var y = centerY - (distY * flare.position);
  82921. var cw = flare.size;
  82922. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  82923. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  82924. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  82925. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  82926. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  82927. // Texture
  82928. this._effect.setTexture("textureSampler", flare.texture);
  82929. // Color
  82930. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  82931. // Draw order
  82932. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82933. }
  82934. engine.setDepthBuffer(true);
  82935. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82936. return true;
  82937. };
  82938. LensFlareSystem.prototype.dispose = function () {
  82939. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82940. if (vertexBuffer) {
  82941. vertexBuffer.dispose();
  82942. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82943. }
  82944. if (this._indexBuffer) {
  82945. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82946. this._indexBuffer = null;
  82947. }
  82948. while (this.lensFlares.length) {
  82949. this.lensFlares[0].dispose();
  82950. }
  82951. // Remove from scene
  82952. var index = this._scene.lensFlareSystems.indexOf(this);
  82953. this._scene.lensFlareSystems.splice(index, 1);
  82954. };
  82955. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  82956. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  82957. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  82958. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  82959. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  82960. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  82961. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  82962. var parsedFlare = parsedLensFlareSystem.flares[index];
  82963. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  82964. }
  82965. return lensFlareSystem;
  82966. };
  82967. LensFlareSystem.prototype.serialize = function () {
  82968. var serializationObject = {};
  82969. serializationObject.id = this.id;
  82970. serializationObject.name = this.name;
  82971. serializationObject.emitterId = this.getEmitter().id;
  82972. serializationObject.borderLimit = this.borderLimit;
  82973. serializationObject.flares = [];
  82974. for (var index = 0; index < this.lensFlares.length; index++) {
  82975. var flare = this.lensFlares[index];
  82976. serializationObject.flares.push({
  82977. size: flare.size,
  82978. position: flare.position,
  82979. color: flare.color.asArray(),
  82980. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  82981. });
  82982. }
  82983. return serializationObject;
  82984. };
  82985. return LensFlareSystem;
  82986. }());
  82987. BABYLON.LensFlareSystem = LensFlareSystem;
  82988. })(BABYLON || (BABYLON = {}));
  82989. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  82990. var BABYLON;
  82991. (function (BABYLON) {
  82992. /**
  82993. * This is a holder class for the physics joint created by the physics plugin.
  82994. * It holds a set of functions to control the underlying joint.
  82995. */
  82996. var PhysicsJoint = /** @class */ (function () {
  82997. function PhysicsJoint(type, jointData) {
  82998. this.type = type;
  82999. this.jointData = jointData;
  83000. jointData.nativeParams = jointData.nativeParams || {};
  83001. }
  83002. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  83003. get: function () {
  83004. return this._physicsJoint;
  83005. },
  83006. set: function (newJoint) {
  83007. if (this._physicsJoint) {
  83008. //remove from the wolrd
  83009. }
  83010. this._physicsJoint = newJoint;
  83011. },
  83012. enumerable: true,
  83013. configurable: true
  83014. });
  83015. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  83016. set: function (physicsPlugin) {
  83017. this._physicsPlugin = physicsPlugin;
  83018. },
  83019. enumerable: true,
  83020. configurable: true
  83021. });
  83022. /**
  83023. * Execute a function that is physics-plugin specific.
  83024. * @param {Function} func the function that will be executed.
  83025. * It accepts two parameters: the physics world and the physics joint.
  83026. */
  83027. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  83028. func(this._physicsPlugin.world, this._physicsJoint);
  83029. };
  83030. //TODO check if the native joints are the same
  83031. //Joint Types
  83032. PhysicsJoint.DistanceJoint = 0;
  83033. PhysicsJoint.HingeJoint = 1;
  83034. PhysicsJoint.BallAndSocketJoint = 2;
  83035. PhysicsJoint.WheelJoint = 3;
  83036. PhysicsJoint.SliderJoint = 4;
  83037. //OIMO
  83038. PhysicsJoint.PrismaticJoint = 5;
  83039. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  83040. PhysicsJoint.UniversalJoint = 6;
  83041. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  83042. //Cannon
  83043. //Similar to a Ball-Joint. Different in params
  83044. PhysicsJoint.PointToPointJoint = 8;
  83045. //Cannon only at the moment
  83046. PhysicsJoint.SpringJoint = 9;
  83047. PhysicsJoint.LockJoint = 10;
  83048. return PhysicsJoint;
  83049. }());
  83050. BABYLON.PhysicsJoint = PhysicsJoint;
  83051. /**
  83052. * A class representing a physics distance joint.
  83053. */
  83054. var DistanceJoint = /** @class */ (function (_super) {
  83055. __extends(DistanceJoint, _super);
  83056. function DistanceJoint(jointData) {
  83057. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  83058. }
  83059. /**
  83060. * Update the predefined distance.
  83061. */
  83062. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  83063. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  83064. };
  83065. return DistanceJoint;
  83066. }(PhysicsJoint));
  83067. BABYLON.DistanceJoint = DistanceJoint;
  83068. var MotorEnabledJoint = /** @class */ (function (_super) {
  83069. __extends(MotorEnabledJoint, _super);
  83070. function MotorEnabledJoint(type, jointData) {
  83071. return _super.call(this, type, jointData) || this;
  83072. }
  83073. /**
  83074. * Set the motor values.
  83075. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83076. * @param {number} force the force to apply
  83077. * @param {number} maxForce max force for this motor.
  83078. */
  83079. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  83080. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83081. };
  83082. /**
  83083. * Set the motor's limits.
  83084. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83085. */
  83086. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83087. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83088. };
  83089. return MotorEnabledJoint;
  83090. }(PhysicsJoint));
  83091. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  83092. /**
  83093. * This class represents a single hinge physics joint
  83094. */
  83095. var HingeJoint = /** @class */ (function (_super) {
  83096. __extends(HingeJoint, _super);
  83097. function HingeJoint(jointData) {
  83098. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  83099. }
  83100. /**
  83101. * Set the motor values.
  83102. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83103. * @param {number} force the force to apply
  83104. * @param {number} maxForce max force for this motor.
  83105. */
  83106. HingeJoint.prototype.setMotor = function (force, maxForce) {
  83107. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83108. };
  83109. /**
  83110. * Set the motor's limits.
  83111. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83112. */
  83113. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83114. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83115. };
  83116. return HingeJoint;
  83117. }(MotorEnabledJoint));
  83118. BABYLON.HingeJoint = HingeJoint;
  83119. /**
  83120. * This class represents a dual hinge physics joint (same as wheel joint)
  83121. */
  83122. var Hinge2Joint = /** @class */ (function (_super) {
  83123. __extends(Hinge2Joint, _super);
  83124. function Hinge2Joint(jointData) {
  83125. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  83126. }
  83127. /**
  83128. * Set the motor values.
  83129. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83130. * @param {number} force the force to apply
  83131. * @param {number} maxForce max force for this motor.
  83132. * @param {motorIndex} the motor's index, 0 or 1.
  83133. */
  83134. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  83135. if (motorIndex === void 0) { motorIndex = 0; }
  83136. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  83137. };
  83138. /**
  83139. * Set the motor limits.
  83140. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83141. * @param {number} upperLimit the upper limit
  83142. * @param {number} lowerLimit lower limit
  83143. * @param {motorIndex} the motor's index, 0 or 1.
  83144. */
  83145. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  83146. if (motorIndex === void 0) { motorIndex = 0; }
  83147. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  83148. };
  83149. return Hinge2Joint;
  83150. }(MotorEnabledJoint));
  83151. BABYLON.Hinge2Joint = Hinge2Joint;
  83152. })(BABYLON || (BABYLON = {}));
  83153. //# sourceMappingURL=babylon.physicsJoint.js.map
  83154. var BABYLON;
  83155. (function (BABYLON) {
  83156. var PhysicsImpostor = /** @class */ (function () {
  83157. function PhysicsImpostor(object, type, _options, _scene) {
  83158. if (_options === void 0) { _options = { mass: 0 }; }
  83159. var _this = this;
  83160. this.object = object;
  83161. this.type = type;
  83162. this._options = _options;
  83163. this._scene = _scene;
  83164. this._bodyUpdateRequired = false;
  83165. this._onBeforePhysicsStepCallbacks = new Array();
  83166. this._onAfterPhysicsStepCallbacks = new Array();
  83167. this._onPhysicsCollideCallbacks = [];
  83168. this._deltaPosition = BABYLON.Vector3.Zero();
  83169. this._isDisposed = false;
  83170. //temp variables for parent rotation calculations
  83171. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  83172. this._tmpQuat = new BABYLON.Quaternion();
  83173. this._tmpQuat2 = new BABYLON.Quaternion();
  83174. /**
  83175. * this function is executed by the physics engine.
  83176. */
  83177. this.beforeStep = function () {
  83178. if (!_this._physicsEngine) {
  83179. return;
  83180. }
  83181. _this.object.translate(_this._deltaPosition, -1);
  83182. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  83183. _this.object.computeWorldMatrix(false);
  83184. if (_this.object.parent && _this.object.rotationQuaternion) {
  83185. _this.getParentsRotation();
  83186. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  83187. }
  83188. else {
  83189. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  83190. }
  83191. if (!_this._options.disableBidirectionalTransformation) {
  83192. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  83193. }
  83194. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  83195. func(_this);
  83196. });
  83197. };
  83198. /**
  83199. * this function is executed by the physics engine.
  83200. */
  83201. this.afterStep = function () {
  83202. if (!_this._physicsEngine) {
  83203. return;
  83204. }
  83205. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  83206. func(_this);
  83207. });
  83208. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  83209. // object has now its world rotation. needs to be converted to local.
  83210. if (_this.object.parent && _this.object.rotationQuaternion) {
  83211. _this.getParentsRotation();
  83212. _this._tmpQuat.conjugateInPlace();
  83213. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  83214. }
  83215. // take the position set and make it the absolute position of this object.
  83216. _this.object.setAbsolutePosition(_this.object.position);
  83217. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  83218. _this.object.translate(_this._deltaPosition, 1);
  83219. };
  83220. /**
  83221. * Legacy collision detection event support
  83222. */
  83223. this.onCollideEvent = null;
  83224. //event and body object due to cannon's event-based architecture.
  83225. this.onCollide = function (e) {
  83226. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  83227. return;
  83228. }
  83229. if (!_this._physicsEngine) {
  83230. return;
  83231. }
  83232. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  83233. if (otherImpostor) {
  83234. // Legacy collision detection event support
  83235. if (_this.onCollideEvent) {
  83236. _this.onCollideEvent(_this, otherImpostor);
  83237. }
  83238. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  83239. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  83240. }).forEach(function (obj) {
  83241. obj.callback(_this, otherImpostor);
  83242. });
  83243. }
  83244. };
  83245. //sanity check!
  83246. if (!this.object) {
  83247. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  83248. return;
  83249. }
  83250. //legacy support for old syntax.
  83251. if (!this._scene && object.getScene) {
  83252. this._scene = object.getScene();
  83253. }
  83254. if (!this._scene) {
  83255. return;
  83256. }
  83257. this._physicsEngine = this._scene.getPhysicsEngine();
  83258. if (!this._physicsEngine) {
  83259. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  83260. }
  83261. else {
  83262. //set the object's quaternion, if not set
  83263. if (!this.object.rotationQuaternion) {
  83264. if (this.object.rotation) {
  83265. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  83266. }
  83267. else {
  83268. this.object.rotationQuaternion = new BABYLON.Quaternion();
  83269. }
  83270. }
  83271. //default options params
  83272. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  83273. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  83274. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  83275. this._joints = [];
  83276. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  83277. if (!this.object.parent || this._options.ignoreParent) {
  83278. this._init();
  83279. }
  83280. else if (this.object.parent.physicsImpostor) {
  83281. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  83282. }
  83283. }
  83284. }
  83285. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  83286. get: function () {
  83287. return this._isDisposed;
  83288. },
  83289. enumerable: true,
  83290. configurable: true
  83291. });
  83292. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  83293. get: function () {
  83294. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  83295. },
  83296. set: function (value) {
  83297. this.setMass(value);
  83298. },
  83299. enumerable: true,
  83300. configurable: true
  83301. });
  83302. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  83303. get: function () {
  83304. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  83305. },
  83306. set: function (value) {
  83307. if (!this._physicsEngine) {
  83308. return;
  83309. }
  83310. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  83311. },
  83312. enumerable: true,
  83313. configurable: true
  83314. });
  83315. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  83316. get: function () {
  83317. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  83318. },
  83319. set: function (value) {
  83320. if (!this._physicsEngine) {
  83321. return;
  83322. }
  83323. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  83324. },
  83325. enumerable: true,
  83326. configurable: true
  83327. });
  83328. /**
  83329. * This function will completly initialize this impostor.
  83330. * It will create a new body - but only if this mesh has no parent.
  83331. * If it has, this impostor will not be used other than to define the impostor
  83332. * of the child mesh.
  83333. */
  83334. PhysicsImpostor.prototype._init = function () {
  83335. if (!this._physicsEngine) {
  83336. return;
  83337. }
  83338. this._physicsEngine.removeImpostor(this);
  83339. this.physicsBody = null;
  83340. this._parent = this._parent || this._getPhysicsParent();
  83341. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  83342. this._physicsEngine.addImpostor(this);
  83343. }
  83344. };
  83345. PhysicsImpostor.prototype._getPhysicsParent = function () {
  83346. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  83347. var parentMesh = this.object.parent;
  83348. return parentMesh.physicsImpostor;
  83349. }
  83350. return null;
  83351. };
  83352. /**
  83353. * Should a new body be generated.
  83354. */
  83355. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  83356. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  83357. };
  83358. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  83359. this.forceUpdate();
  83360. };
  83361. /**
  83362. * Force a regeneration of this or the parent's impostor's body.
  83363. * Use under cautious - This will remove all joints already implemented.
  83364. */
  83365. PhysicsImpostor.prototype.forceUpdate = function () {
  83366. this._init();
  83367. if (this.parent && !this._options.ignoreParent) {
  83368. this.parent.forceUpdate();
  83369. }
  83370. };
  83371. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  83372. /*public get mesh(): AbstractMesh {
  83373. return this._mesh;
  83374. }*/
  83375. /**
  83376. * Gets the body that holds this impostor. Either its own, or its parent.
  83377. */
  83378. get: function () {
  83379. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  83380. },
  83381. /**
  83382. * Set the physics body. Used mainly by the physics engine/plugin
  83383. */
  83384. set: function (physicsBody) {
  83385. if (this._physicsBody && this._physicsEngine) {
  83386. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  83387. }
  83388. this._physicsBody = physicsBody;
  83389. this.resetUpdateFlags();
  83390. },
  83391. enumerable: true,
  83392. configurable: true
  83393. });
  83394. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  83395. get: function () {
  83396. return !this._options.ignoreParent && this._parent ? this._parent : null;
  83397. },
  83398. set: function (value) {
  83399. this._parent = value;
  83400. },
  83401. enumerable: true,
  83402. configurable: true
  83403. });
  83404. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  83405. this._bodyUpdateRequired = false;
  83406. };
  83407. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  83408. if (this.object.getBoundingInfo) {
  83409. var q = this.object.rotationQuaternion;
  83410. //reset rotation
  83411. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  83412. //calculate the world matrix with no rotation
  83413. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  83414. var boundingInfo = this.object.getBoundingInfo();
  83415. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  83416. //bring back the rotation
  83417. this.object.rotationQuaternion = q;
  83418. //calculate the world matrix with the new rotation
  83419. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  83420. return size;
  83421. }
  83422. else {
  83423. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  83424. }
  83425. };
  83426. PhysicsImpostor.prototype.getObjectCenter = function () {
  83427. if (this.object.getBoundingInfo) {
  83428. var boundingInfo = this.object.getBoundingInfo();
  83429. return boundingInfo.boundingBox.centerWorld;
  83430. }
  83431. else {
  83432. return this.object.position;
  83433. }
  83434. };
  83435. /**
  83436. * Get a specific parametes from the options parameter.
  83437. */
  83438. PhysicsImpostor.prototype.getParam = function (paramName) {
  83439. return this._options[paramName];
  83440. };
  83441. /**
  83442. * Sets a specific parameter in the options given to the physics plugin
  83443. */
  83444. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  83445. this._options[paramName] = value;
  83446. this._bodyUpdateRequired = true;
  83447. };
  83448. /**
  83449. * Specifically change the body's mass option. Won't recreate the physics body object
  83450. */
  83451. PhysicsImpostor.prototype.setMass = function (mass) {
  83452. if (this.getParam("mass") !== mass) {
  83453. this.setParam("mass", mass);
  83454. }
  83455. if (this._physicsEngine) {
  83456. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  83457. }
  83458. };
  83459. PhysicsImpostor.prototype.getLinearVelocity = function () {
  83460. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  83461. };
  83462. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  83463. if (this._physicsEngine) {
  83464. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  83465. }
  83466. };
  83467. PhysicsImpostor.prototype.getAngularVelocity = function () {
  83468. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  83469. };
  83470. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  83471. if (this._physicsEngine) {
  83472. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  83473. }
  83474. };
  83475. /**
  83476. * Execute a function with the physics plugin native code.
  83477. * Provide a function the will have two variables - the world object and the physics body object.
  83478. */
  83479. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  83480. if (this._physicsEngine) {
  83481. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  83482. }
  83483. };
  83484. /**
  83485. * Register a function that will be executed before the physics world is stepping forward.
  83486. */
  83487. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  83488. this._onBeforePhysicsStepCallbacks.push(func);
  83489. };
  83490. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  83491. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  83492. if (index > -1) {
  83493. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  83494. }
  83495. else {
  83496. BABYLON.Tools.Warn("Function to remove was not found");
  83497. }
  83498. };
  83499. /**
  83500. * Register a function that will be executed after the physics step
  83501. */
  83502. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  83503. this._onAfterPhysicsStepCallbacks.push(func);
  83504. };
  83505. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  83506. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  83507. if (index > -1) {
  83508. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  83509. }
  83510. else {
  83511. BABYLON.Tools.Warn("Function to remove was not found");
  83512. }
  83513. };
  83514. /**
  83515. * register a function that will be executed when this impostor collides against a different body.
  83516. */
  83517. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  83518. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  83519. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  83520. };
  83521. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  83522. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  83523. var index = -1;
  83524. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  83525. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  83526. // chcek the arrays match
  83527. var sameList = cbDef.otherImpostors.every(function (impostor) {
  83528. return collidedAgainstList.indexOf(impostor) > -1;
  83529. });
  83530. if (sameList) {
  83531. index = idx;
  83532. }
  83533. return sameList;
  83534. }
  83535. return false;
  83536. });
  83537. if (found) {
  83538. this._onPhysicsCollideCallbacks.splice(index, 1);
  83539. }
  83540. else {
  83541. BABYLON.Tools.Warn("Function to remove was not found");
  83542. }
  83543. };
  83544. PhysicsImpostor.prototype.getParentsRotation = function () {
  83545. var parent = this.object.parent;
  83546. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  83547. while (parent) {
  83548. if (parent.rotationQuaternion) {
  83549. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  83550. }
  83551. else {
  83552. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  83553. }
  83554. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  83555. parent = parent.parent;
  83556. }
  83557. return this._tmpQuat;
  83558. };
  83559. /**
  83560. * Apply a force
  83561. */
  83562. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  83563. if (this._physicsEngine) {
  83564. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  83565. }
  83566. return this;
  83567. };
  83568. /**
  83569. * Apply an impulse
  83570. */
  83571. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  83572. if (this._physicsEngine) {
  83573. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  83574. }
  83575. return this;
  83576. };
  83577. /**
  83578. * A help function to create a joint.
  83579. */
  83580. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  83581. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  83582. this.addJoint(otherImpostor, joint);
  83583. return this;
  83584. };
  83585. /**
  83586. * Add a joint to this impostor with a different impostor.
  83587. */
  83588. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  83589. this._joints.push({
  83590. otherImpostor: otherImpostor,
  83591. joint: joint
  83592. });
  83593. if (this._physicsEngine) {
  83594. this._physicsEngine.addJoint(this, otherImpostor, joint);
  83595. }
  83596. return this;
  83597. };
  83598. /**
  83599. * Will keep this body still, in a sleep mode.
  83600. */
  83601. PhysicsImpostor.prototype.sleep = function () {
  83602. if (this._physicsEngine) {
  83603. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  83604. }
  83605. return this;
  83606. };
  83607. /**
  83608. * Wake the body up.
  83609. */
  83610. PhysicsImpostor.prototype.wakeUp = function () {
  83611. if (this._physicsEngine) {
  83612. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  83613. }
  83614. return this;
  83615. };
  83616. PhysicsImpostor.prototype.clone = function (newObject) {
  83617. if (!newObject)
  83618. return null;
  83619. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  83620. };
  83621. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  83622. var _this = this;
  83623. //no dispose if no physics engine is available.
  83624. if (!this._physicsEngine) {
  83625. return;
  83626. }
  83627. this._joints.forEach(function (j) {
  83628. if (_this._physicsEngine) {
  83629. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  83630. }
  83631. });
  83632. //dispose the physics body
  83633. this._physicsEngine.removeImpostor(this);
  83634. if (this.parent) {
  83635. this.parent.forceUpdate();
  83636. }
  83637. else {
  83638. /*this._object.getChildMeshes().forEach(function(mesh) {
  83639. if (mesh.physicsImpostor) {
  83640. if (disposeChildren) {
  83641. mesh.physicsImpostor.dispose();
  83642. mesh.physicsImpostor = null;
  83643. }
  83644. }
  83645. })*/
  83646. }
  83647. this._isDisposed = true;
  83648. };
  83649. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  83650. this._deltaPosition.copyFrom(position);
  83651. };
  83652. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  83653. if (!this._deltaRotation) {
  83654. this._deltaRotation = new BABYLON.Quaternion();
  83655. }
  83656. this._deltaRotation.copyFrom(rotation);
  83657. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  83658. };
  83659. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  83660. if (this._physicsEngine) {
  83661. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  83662. }
  83663. return this;
  83664. };
  83665. PhysicsImpostor.prototype.getRadius = function () {
  83666. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  83667. };
  83668. /**
  83669. * Sync a bone with this impostor
  83670. * @param bone The bone to sync to the impostor.
  83671. * @param boneMesh The mesh that the bone is influencing.
  83672. * @param jointPivot The pivot of the joint / bone in local space.
  83673. * @param distToJoint Optional distance from the impostor to the joint.
  83674. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  83675. */
  83676. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  83677. var tempVec = PhysicsImpostor._tmpVecs[0];
  83678. var mesh = this.object;
  83679. if (mesh.rotationQuaternion) {
  83680. if (adjustRotation) {
  83681. var tempQuat = PhysicsImpostor._tmpQuat;
  83682. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  83683. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  83684. }
  83685. else {
  83686. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  83687. }
  83688. }
  83689. tempVec.x = 0;
  83690. tempVec.y = 0;
  83691. tempVec.z = 0;
  83692. if (jointPivot) {
  83693. tempVec.x = jointPivot.x;
  83694. tempVec.y = jointPivot.y;
  83695. tempVec.z = jointPivot.z;
  83696. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  83697. if (distToJoint === undefined || distToJoint === null) {
  83698. distToJoint = jointPivot.length();
  83699. }
  83700. tempVec.x *= distToJoint;
  83701. tempVec.y *= distToJoint;
  83702. tempVec.z *= distToJoint;
  83703. }
  83704. if (bone.getParent()) {
  83705. tempVec.addInPlace(mesh.getAbsolutePosition());
  83706. bone.setAbsolutePosition(tempVec, boneMesh);
  83707. }
  83708. else {
  83709. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  83710. boneMesh.position.x -= tempVec.x;
  83711. boneMesh.position.y -= tempVec.y;
  83712. boneMesh.position.z -= tempVec.z;
  83713. }
  83714. };
  83715. /**
  83716. * Sync impostor to a bone
  83717. * @param bone The bone that the impostor will be synced to.
  83718. * @param boneMesh The mesh that the bone is influencing.
  83719. * @param jointPivot The pivot of the joint / bone in local space.
  83720. * @param distToJoint Optional distance from the impostor to the joint.
  83721. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  83722. * @param boneAxis Optional vector3 axis the bone is aligned with
  83723. */
  83724. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  83725. var mesh = this.object;
  83726. if (mesh.rotationQuaternion) {
  83727. if (adjustRotation) {
  83728. var tempQuat = PhysicsImpostor._tmpQuat;
  83729. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  83730. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  83731. }
  83732. else {
  83733. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  83734. }
  83735. }
  83736. var pos = PhysicsImpostor._tmpVecs[0];
  83737. var boneDir = PhysicsImpostor._tmpVecs[1];
  83738. if (!boneAxis) {
  83739. boneAxis = PhysicsImpostor._tmpVecs[2];
  83740. boneAxis.x = 0;
  83741. boneAxis.y = 1;
  83742. boneAxis.z = 0;
  83743. }
  83744. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  83745. bone.getAbsolutePositionToRef(boneMesh, pos);
  83746. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  83747. distToJoint = jointPivot.length();
  83748. }
  83749. if (distToJoint !== undefined && distToJoint !== null) {
  83750. pos.x += boneDir.x * distToJoint;
  83751. pos.y += boneDir.y * distToJoint;
  83752. pos.z += boneDir.z * distToJoint;
  83753. }
  83754. mesh.setAbsolutePosition(pos);
  83755. };
  83756. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  83757. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  83758. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83759. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  83760. //Impostor types
  83761. PhysicsImpostor.NoImpostor = 0;
  83762. PhysicsImpostor.SphereImpostor = 1;
  83763. PhysicsImpostor.BoxImpostor = 2;
  83764. PhysicsImpostor.PlaneImpostor = 3;
  83765. PhysicsImpostor.MeshImpostor = 4;
  83766. PhysicsImpostor.CylinderImpostor = 7;
  83767. PhysicsImpostor.ParticleImpostor = 8;
  83768. PhysicsImpostor.HeightmapImpostor = 9;
  83769. return PhysicsImpostor;
  83770. }());
  83771. BABYLON.PhysicsImpostor = PhysicsImpostor;
  83772. })(BABYLON || (BABYLON = {}));
  83773. //# sourceMappingURL=babylon.physicsImpostor.js.map
  83774. var BABYLON;
  83775. (function (BABYLON) {
  83776. var PhysicsEngine = /** @class */ (function () {
  83777. function PhysicsEngine(gravity, _physicsPlugin) {
  83778. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  83779. this._physicsPlugin = _physicsPlugin;
  83780. //new methods and parameters
  83781. this._impostors = [];
  83782. this._joints = [];
  83783. if (!this._physicsPlugin.isSupported()) {
  83784. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  83785. + "Please make sure it is included.");
  83786. }
  83787. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  83788. this.setGravity(gravity);
  83789. this.setTimeStep();
  83790. }
  83791. PhysicsEngine.prototype.setGravity = function (gravity) {
  83792. this.gravity = gravity;
  83793. this._physicsPlugin.setGravity(this.gravity);
  83794. };
  83795. /**
  83796. * Set the time step of the physics engine.
  83797. * default is 1/60.
  83798. * To slow it down, enter 1/600 for example.
  83799. * To speed it up, 1/30
  83800. * @param {number} newTimeStep the new timestep to apply to this world.
  83801. */
  83802. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  83803. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  83804. this._physicsPlugin.setTimeStep(newTimeStep);
  83805. };
  83806. /**
  83807. * Get the time step of the physics engine.
  83808. */
  83809. PhysicsEngine.prototype.getTimeStep = function () {
  83810. return this._physicsPlugin.getTimeStep();
  83811. };
  83812. PhysicsEngine.prototype.dispose = function () {
  83813. this._impostors.forEach(function (impostor) {
  83814. impostor.dispose();
  83815. });
  83816. this._physicsPlugin.dispose();
  83817. };
  83818. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  83819. return this._physicsPlugin.name;
  83820. };
  83821. /**
  83822. * Adding a new impostor for the impostor tracking.
  83823. * This will be done by the impostor itself.
  83824. * @param {PhysicsImpostor} impostor the impostor to add
  83825. */
  83826. PhysicsEngine.prototype.addImpostor = function (impostor) {
  83827. impostor.uniqueId = this._impostors.push(impostor);
  83828. //if no parent, generate the body
  83829. if (!impostor.parent) {
  83830. this._physicsPlugin.generatePhysicsBody(impostor);
  83831. }
  83832. };
  83833. /**
  83834. * Remove an impostor from the engine.
  83835. * This impostor and its mesh will not longer be updated by the physics engine.
  83836. * @param {PhysicsImpostor} impostor the impostor to remove
  83837. */
  83838. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  83839. var index = this._impostors.indexOf(impostor);
  83840. if (index > -1) {
  83841. var removed = this._impostors.splice(index, 1);
  83842. //Is it needed?
  83843. if (removed.length) {
  83844. //this will also remove it from the world.
  83845. removed[0].physicsBody = null;
  83846. }
  83847. }
  83848. };
  83849. /**
  83850. * Add a joint to the physics engine
  83851. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  83852. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  83853. * @param {PhysicsJoint} the joint that will connect both impostors.
  83854. */
  83855. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  83856. var impostorJoint = {
  83857. mainImpostor: mainImpostor,
  83858. connectedImpostor: connectedImpostor,
  83859. joint: joint
  83860. };
  83861. joint.physicsPlugin = this._physicsPlugin;
  83862. this._joints.push(impostorJoint);
  83863. this._physicsPlugin.generateJoint(impostorJoint);
  83864. };
  83865. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  83866. var matchingJoints = this._joints.filter(function (impostorJoint) {
  83867. return (impostorJoint.connectedImpostor === connectedImpostor
  83868. && impostorJoint.joint === joint
  83869. && impostorJoint.mainImpostor === mainImpostor);
  83870. });
  83871. if (matchingJoints.length) {
  83872. this._physicsPlugin.removeJoint(matchingJoints[0]);
  83873. //TODO remove it from the list as well
  83874. }
  83875. };
  83876. /**
  83877. * Called by the scene. no need to call it.
  83878. */
  83879. PhysicsEngine.prototype._step = function (delta) {
  83880. var _this = this;
  83881. //check if any mesh has no body / requires an update
  83882. this._impostors.forEach(function (impostor) {
  83883. if (impostor.isBodyInitRequired()) {
  83884. _this._physicsPlugin.generatePhysicsBody(impostor);
  83885. }
  83886. });
  83887. if (delta > 0.1) {
  83888. delta = 0.1;
  83889. }
  83890. else if (delta <= 0) {
  83891. delta = 1.0 / 60.0;
  83892. }
  83893. this._physicsPlugin.executeStep(delta, this._impostors);
  83894. };
  83895. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  83896. return this._physicsPlugin;
  83897. };
  83898. PhysicsEngine.prototype.getImpostors = function () {
  83899. return this._impostors;
  83900. };
  83901. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  83902. for (var i = 0; i < this._impostors.length; ++i) {
  83903. if (this._impostors[i].object === object) {
  83904. return this._impostors[i];
  83905. }
  83906. }
  83907. return null;
  83908. };
  83909. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  83910. for (var i = 0; i < this._impostors.length; ++i) {
  83911. if (this._impostors[i].physicsBody === body) {
  83912. return this._impostors[i];
  83913. }
  83914. }
  83915. return null;
  83916. };
  83917. // Statics
  83918. PhysicsEngine.Epsilon = 0.001;
  83919. return PhysicsEngine;
  83920. }());
  83921. BABYLON.PhysicsEngine = PhysicsEngine;
  83922. })(BABYLON || (BABYLON = {}));
  83923. //# sourceMappingURL=babylon.physicsEngine.js.map
  83924. var BABYLON;
  83925. (function (BABYLON) {
  83926. var PhysicsHelper = /** @class */ (function () {
  83927. function PhysicsHelper(scene) {
  83928. this._scene = scene;
  83929. this._physicsEngine = this._scene.getPhysicsEngine();
  83930. if (!this._physicsEngine) {
  83931. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  83932. }
  83933. }
  83934. /**
  83935. * @param {Vector3} origin the origin of the explosion
  83936. * @param {number} radius the explosion radius
  83937. * @param {number} strength the explosion strength
  83938. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83939. */
  83940. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  83941. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83942. if (!this._physicsEngine) {
  83943. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  83944. return null;
  83945. }
  83946. var impostors = this._physicsEngine.getImpostors();
  83947. if (impostors.length === 0) {
  83948. return null;
  83949. }
  83950. var event = new PhysicsRadialExplosionEvent(this._scene);
  83951. impostors.forEach(function (impostor) {
  83952. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83953. if (!impostorForceAndContactPoint) {
  83954. return;
  83955. }
  83956. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83957. });
  83958. event.dispose(false);
  83959. return event;
  83960. };
  83961. /**
  83962. * @param {Vector3} origin the origin of the explosion
  83963. * @param {number} radius the explosion radius
  83964. * @param {number} strength the explosion strength
  83965. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83966. */
  83967. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  83968. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83969. if (!this._physicsEngine) {
  83970. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83971. return null;
  83972. }
  83973. var impostors = this._physicsEngine.getImpostors();
  83974. if (impostors.length === 0) {
  83975. return null;
  83976. }
  83977. var event = new PhysicsRadialExplosionEvent(this._scene);
  83978. impostors.forEach(function (impostor) {
  83979. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83980. if (!impostorForceAndContactPoint) {
  83981. return;
  83982. }
  83983. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83984. });
  83985. event.dispose(false);
  83986. return event;
  83987. };
  83988. /**
  83989. * @param {Vector3} origin the origin of the explosion
  83990. * @param {number} radius the explosion radius
  83991. * @param {number} strength the explosion strength
  83992. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83993. */
  83994. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  83995. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83996. if (!this._physicsEngine) {
  83997. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83998. return null;
  83999. }
  84000. var impostors = this._physicsEngine.getImpostors();
  84001. if (impostors.length === 0) {
  84002. return null;
  84003. }
  84004. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  84005. event.dispose(false);
  84006. return event;
  84007. };
  84008. /**
  84009. * @param {Vector3} origin the origin of the updraft
  84010. * @param {number} radius the radius of the updraft
  84011. * @param {number} strength the strength of the updraft
  84012. * @param {number} height the height of the updraft
  84013. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  84014. */
  84015. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  84016. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  84017. if (!this._physicsEngine) {
  84018. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84019. return null;
  84020. }
  84021. if (this._physicsEngine.getImpostors().length === 0) {
  84022. return null;
  84023. }
  84024. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  84025. event.dispose(false);
  84026. return event;
  84027. };
  84028. /**
  84029. * @param {Vector3} origin the of the vortex
  84030. * @param {number} radius the radius of the vortex
  84031. * @param {number} strength the strength of the vortex
  84032. * @param {number} height the height of the vortex
  84033. */
  84034. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  84035. if (!this._physicsEngine) {
  84036. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84037. return null;
  84038. }
  84039. if (this._physicsEngine.getImpostors().length === 0) {
  84040. return null;
  84041. }
  84042. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  84043. event.dispose(false);
  84044. return event;
  84045. };
  84046. return PhysicsHelper;
  84047. }());
  84048. BABYLON.PhysicsHelper = PhysicsHelper;
  84049. /***** Radial explosion *****/
  84050. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  84051. function PhysicsRadialExplosionEvent(scene) {
  84052. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  84053. this._rays = [];
  84054. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  84055. this._scene = scene;
  84056. }
  84057. /**
  84058. * Returns the data related to the radial explosion event (sphere & rays).
  84059. * @returns {PhysicsRadialExplosionEventData}
  84060. */
  84061. PhysicsRadialExplosionEvent.prototype.getData = function () {
  84062. this._dataFetched = true;
  84063. return {
  84064. sphere: this._sphere,
  84065. rays: this._rays,
  84066. };
  84067. };
  84068. /**
  84069. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  84070. * @param impostor
  84071. * @param {Vector3} origin the origin of the explosion
  84072. * @param {number} radius the explosion radius
  84073. * @param {number} strength the explosion strength
  84074. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  84075. * @returns {Nullable<PhysicsForceAndContactPoint>}
  84076. */
  84077. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  84078. if (impostor.mass === 0) {
  84079. return null;
  84080. }
  84081. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  84082. return null;
  84083. }
  84084. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84085. return null;
  84086. }
  84087. var impostorObjectCenter = impostor.getObjectCenter();
  84088. var direction = impostorObjectCenter.subtract(origin);
  84089. var ray = new BABYLON.Ray(origin, direction, radius);
  84090. this._rays.push(ray);
  84091. var hit = ray.intersectsMesh(impostor.object);
  84092. var contactPoint = hit.pickedPoint;
  84093. if (!contactPoint) {
  84094. return null;
  84095. }
  84096. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  84097. if (distanceFromOrigin > radius) {
  84098. return null;
  84099. }
  84100. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  84101. ? strength
  84102. : strength * (1 - (distanceFromOrigin / radius));
  84103. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84104. return { force: force, contactPoint: contactPoint };
  84105. };
  84106. /**
  84107. * Disposes the sphere.
  84108. * @param {bolean} force
  84109. */
  84110. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  84111. var _this = this;
  84112. if (force === void 0) { force = true; }
  84113. if (force) {
  84114. this._sphere.dispose();
  84115. }
  84116. else {
  84117. setTimeout(function () {
  84118. if (!_this._dataFetched) {
  84119. _this._sphere.dispose();
  84120. }
  84121. }, 0);
  84122. }
  84123. };
  84124. /*** Helpers ***/
  84125. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  84126. if (!this._sphere) {
  84127. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  84128. this._sphere.isVisible = false;
  84129. }
  84130. };
  84131. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  84132. var impostorObject = impostor.object;
  84133. this._prepareSphere();
  84134. this._sphere.position = origin;
  84135. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  84136. this._sphere._updateBoundingInfo();
  84137. this._sphere.computeWorldMatrix(true);
  84138. return this._sphere.intersectsMesh(impostorObject, true);
  84139. };
  84140. return PhysicsRadialExplosionEvent;
  84141. }());
  84142. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  84143. /***** Gravitational Field *****/
  84144. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  84145. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  84146. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84147. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84148. this._physicsHelper = physicsHelper;
  84149. this._scene = scene;
  84150. this._origin = origin;
  84151. this._radius = radius;
  84152. this._strength = strength;
  84153. this._falloff = falloff;
  84154. this._tickCallback = this._tick.bind(this);
  84155. }
  84156. /**
  84157. * Returns the data related to the gravitational field event (sphere).
  84158. * @returns {PhysicsGravitationalFieldEventData}
  84159. */
  84160. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  84161. this._dataFetched = true;
  84162. return {
  84163. sphere: this._sphere,
  84164. };
  84165. };
  84166. /**
  84167. * Enables the gravitational field.
  84168. */
  84169. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  84170. this._tickCallback.call(this);
  84171. this._scene.registerBeforeRender(this._tickCallback);
  84172. };
  84173. /**
  84174. * Disables the gravitational field.
  84175. */
  84176. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  84177. this._scene.unregisterBeforeRender(this._tickCallback);
  84178. };
  84179. /**
  84180. * Disposes the sphere.
  84181. * @param {bolean} force
  84182. */
  84183. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  84184. var _this = this;
  84185. if (force === void 0) { force = true; }
  84186. if (force) {
  84187. this._sphere.dispose();
  84188. }
  84189. else {
  84190. setTimeout(function () {
  84191. if (!_this._dataFetched) {
  84192. _this._sphere.dispose();
  84193. }
  84194. }, 0);
  84195. }
  84196. };
  84197. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  84198. // Since the params won't change, we fetch the event only once
  84199. if (this._sphere) {
  84200. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84201. }
  84202. else {
  84203. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84204. if (radialExplosionEvent) {
  84205. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  84206. }
  84207. }
  84208. };
  84209. return PhysicsGravitationalFieldEvent;
  84210. }());
  84211. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  84212. /***** Updraft *****/
  84213. var PhysicsUpdraftEvent = /** @class */ (function () {
  84214. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  84215. this._scene = _scene;
  84216. this._origin = _origin;
  84217. this._radius = _radius;
  84218. this._strength = _strength;
  84219. this._height = _height;
  84220. this._updraftMode = _updraftMode;
  84221. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84222. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  84223. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84224. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84225. this._physicsEngine = this._scene.getPhysicsEngine();
  84226. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84227. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84228. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84229. this._originDirection = this._origin.subtract(this._originTop).normalize();
  84230. }
  84231. this._tickCallback = this._tick.bind(this);
  84232. }
  84233. /**
  84234. * Returns the data related to the updraft event (cylinder).
  84235. * @returns {PhysicsUpdraftEventData}
  84236. */
  84237. PhysicsUpdraftEvent.prototype.getData = function () {
  84238. this._dataFetched = true;
  84239. return {
  84240. cylinder: this._cylinder,
  84241. };
  84242. };
  84243. /**
  84244. * Enables the updraft.
  84245. */
  84246. PhysicsUpdraftEvent.prototype.enable = function () {
  84247. this._tickCallback.call(this);
  84248. this._scene.registerBeforeRender(this._tickCallback);
  84249. };
  84250. /**
  84251. * Disables the cortex.
  84252. */
  84253. PhysicsUpdraftEvent.prototype.disable = function () {
  84254. this._scene.unregisterBeforeRender(this._tickCallback);
  84255. };
  84256. /**
  84257. * Disposes the sphere.
  84258. * @param {bolean} force
  84259. */
  84260. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  84261. var _this = this;
  84262. if (force === void 0) { force = true; }
  84263. if (force) {
  84264. this._cylinder.dispose();
  84265. }
  84266. else {
  84267. setTimeout(function () {
  84268. if (!_this._dataFetched) {
  84269. _this._cylinder.dispose();
  84270. }
  84271. }, 0);
  84272. }
  84273. };
  84274. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84275. if (impostor.mass === 0) {
  84276. return null;
  84277. }
  84278. if (!this._intersectsWithCylinder(impostor)) {
  84279. return null;
  84280. }
  84281. var impostorObjectCenter = impostor.getObjectCenter();
  84282. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84283. var direction = this._originDirection;
  84284. }
  84285. else {
  84286. var direction = impostorObjectCenter.subtract(this._originTop);
  84287. }
  84288. var multiplier = this._strength * -1;
  84289. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84290. return { force: force, contactPoint: impostorObjectCenter };
  84291. };
  84292. PhysicsUpdraftEvent.prototype._tick = function () {
  84293. var _this = this;
  84294. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84295. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84296. if (!impostorForceAndContactPoint) {
  84297. return;
  84298. }
  84299. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84300. });
  84301. };
  84302. /*** Helpers ***/
  84303. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  84304. if (!this._cylinder) {
  84305. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  84306. height: this._height,
  84307. diameter: this._radius * 2,
  84308. }, this._scene);
  84309. this._cylinder.isVisible = false;
  84310. }
  84311. };
  84312. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  84313. var impostorObject = impostor.object;
  84314. this._prepareCylinder();
  84315. this._cylinder.position = this._cylinderPosition;
  84316. return this._cylinder.intersectsMesh(impostorObject, true);
  84317. };
  84318. return PhysicsUpdraftEvent;
  84319. }());
  84320. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  84321. /***** Vortex *****/
  84322. var PhysicsVortexEvent = /** @class */ (function () {
  84323. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  84324. this._scene = _scene;
  84325. this._origin = _origin;
  84326. this._radius = _radius;
  84327. this._strength = _strength;
  84328. this._height = _height;
  84329. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84330. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  84331. this._updraftMultiplier = 0.02;
  84332. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84333. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84334. this._physicsEngine = this._scene.getPhysicsEngine();
  84335. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84336. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84337. this._tickCallback = this._tick.bind(this);
  84338. }
  84339. /**
  84340. * Returns the data related to the vortex event (cylinder).
  84341. * @returns {PhysicsVortexEventData}
  84342. */
  84343. PhysicsVortexEvent.prototype.getData = function () {
  84344. this._dataFetched = true;
  84345. return {
  84346. cylinder: this._cylinder,
  84347. };
  84348. };
  84349. /**
  84350. * Enables the vortex.
  84351. */
  84352. PhysicsVortexEvent.prototype.enable = function () {
  84353. this._tickCallback.call(this);
  84354. this._scene.registerBeforeRender(this._tickCallback);
  84355. };
  84356. /**
  84357. * Disables the cortex.
  84358. */
  84359. PhysicsVortexEvent.prototype.disable = function () {
  84360. this._scene.unregisterBeforeRender(this._tickCallback);
  84361. };
  84362. /**
  84363. * Disposes the sphere.
  84364. * @param {bolean} force
  84365. */
  84366. PhysicsVortexEvent.prototype.dispose = function (force) {
  84367. var _this = this;
  84368. if (force === void 0) { force = true; }
  84369. if (force) {
  84370. this._cylinder.dispose();
  84371. }
  84372. else {
  84373. setTimeout(function () {
  84374. if (!_this._dataFetched) {
  84375. _this._cylinder.dispose();
  84376. }
  84377. }, 0);
  84378. }
  84379. };
  84380. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84381. if (impostor.mass === 0) {
  84382. return null;
  84383. }
  84384. if (!this._intersectsWithCylinder(impostor)) {
  84385. return null;
  84386. }
  84387. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84388. return null;
  84389. }
  84390. var impostorObjectCenter = impostor.getObjectCenter();
  84391. 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)
  84392. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  84393. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  84394. var hit = ray.intersectsMesh(impostor.object);
  84395. var contactPoint = hit.pickedPoint;
  84396. if (!contactPoint) {
  84397. return null;
  84398. }
  84399. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  84400. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  84401. var directionToOrigin = contactPoint.normalize();
  84402. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  84403. directionToOrigin = directionToOrigin.negate();
  84404. }
  84405. // TODO: find a more physically based solution
  84406. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  84407. var forceX = directionToOrigin.x * this._strength / 8;
  84408. var forceY = directionToOrigin.y * this._updraftMultiplier;
  84409. var forceZ = directionToOrigin.z * this._strength / 8;
  84410. }
  84411. else {
  84412. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  84413. var forceY = this._originTop.y * this._updraftMultiplier;
  84414. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  84415. }
  84416. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  84417. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  84418. return { force: force, contactPoint: impostorObjectCenter };
  84419. };
  84420. PhysicsVortexEvent.prototype._tick = function () {
  84421. var _this = this;
  84422. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84423. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84424. if (!impostorForceAndContactPoint) {
  84425. return;
  84426. }
  84427. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84428. });
  84429. };
  84430. /*** Helpers ***/
  84431. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  84432. if (!this._cylinder) {
  84433. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  84434. height: this._height,
  84435. diameter: this._radius * 2,
  84436. }, this._scene);
  84437. this._cylinder.isVisible = false;
  84438. }
  84439. };
  84440. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  84441. var impostorObject = impostor.object;
  84442. this._prepareCylinder();
  84443. this._cylinder.position = this._cylinderPosition;
  84444. return this._cylinder.intersectsMesh(impostorObject, true);
  84445. };
  84446. return PhysicsVortexEvent;
  84447. }());
  84448. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  84449. /***** Enums *****/
  84450. /**
  84451. * The strenght of the force in correspondence to the distance of the affected object
  84452. */
  84453. var PhysicsRadialImpulseFalloff;
  84454. (function (PhysicsRadialImpulseFalloff) {
  84455. /** Defines that impulse is constant in strength across it's whole radius */
  84456. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  84457. /** DEfines that impulse gets weaker if it's further from the origin */
  84458. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  84459. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  84460. /**
  84461. * The strenght of the force in correspondence to the distance of the affected object
  84462. */
  84463. var PhysicsUpdraftMode;
  84464. (function (PhysicsUpdraftMode) {
  84465. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  84466. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  84467. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  84468. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  84469. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  84470. })(BABYLON || (BABYLON = {}));
  84471. //# sourceMappingURL=babylon.physicsHelper.js.map
  84472. var BABYLON;
  84473. (function (BABYLON) {
  84474. var CannonJSPlugin = /** @class */ (function () {
  84475. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  84476. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  84477. if (iterations === void 0) { iterations = 10; }
  84478. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  84479. this.name = "CannonJSPlugin";
  84480. this._physicsMaterials = new Array();
  84481. this._fixedTimeStep = 1 / 60;
  84482. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  84483. this.BJSCANNON = CANNON;
  84484. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  84485. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  84486. this._tmpPosition = BABYLON.Vector3.Zero();
  84487. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  84488. this._tmpUnityRotation = new BABYLON.Quaternion();
  84489. if (!this.isSupported()) {
  84490. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  84491. return;
  84492. }
  84493. this._extendNamespace();
  84494. this.world = new this.BJSCANNON.World();
  84495. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  84496. this.world.solver.iterations = iterations;
  84497. }
  84498. CannonJSPlugin.prototype.setGravity = function (gravity) {
  84499. this.world.gravity.copy(gravity);
  84500. };
  84501. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  84502. this._fixedTimeStep = timeStep;
  84503. };
  84504. CannonJSPlugin.prototype.getTimeStep = function () {
  84505. return this._fixedTimeStep;
  84506. };
  84507. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  84508. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  84509. };
  84510. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84511. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  84512. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  84513. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  84514. };
  84515. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  84516. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  84517. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  84518. impostor.physicsBody.applyForce(impulse, worldPoint);
  84519. };
  84520. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  84521. //parent-child relationship. Does this impostor has a parent impostor?
  84522. if (impostor.parent) {
  84523. if (impostor.physicsBody) {
  84524. this.removePhysicsBody(impostor);
  84525. //TODO is that needed?
  84526. impostor.forceUpdate();
  84527. }
  84528. return;
  84529. }
  84530. //should a new body be created for this impostor?
  84531. if (impostor.isBodyInitRequired()) {
  84532. var shape = this._createShape(impostor);
  84533. //unregister events, if body is being changed
  84534. var oldBody = impostor.physicsBody;
  84535. if (oldBody) {
  84536. this.removePhysicsBody(impostor);
  84537. }
  84538. //create the body and material
  84539. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  84540. var bodyCreationObject = {
  84541. mass: impostor.getParam("mass"),
  84542. material: material
  84543. };
  84544. // A simple extend, in case native options were used.
  84545. var nativeOptions = impostor.getParam("nativeOptions");
  84546. for (var key in nativeOptions) {
  84547. if (nativeOptions.hasOwnProperty(key)) {
  84548. bodyCreationObject[key] = nativeOptions[key];
  84549. }
  84550. }
  84551. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  84552. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  84553. this.world.addEventListener("preStep", impostor.beforeStep);
  84554. this.world.addEventListener("postStep", impostor.afterStep);
  84555. impostor.physicsBody.addShape(shape);
  84556. this.world.add(impostor.physicsBody);
  84557. //try to keep the body moving in the right direction by taking old properties.
  84558. //Should be tested!
  84559. if (oldBody) {
  84560. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  84561. impostor.physicsBody[param].copy(oldBody[param]);
  84562. });
  84563. }
  84564. this._processChildMeshes(impostor);
  84565. }
  84566. //now update the body's transformation
  84567. this._updatePhysicsBodyTransformation(impostor);
  84568. };
  84569. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  84570. var _this = this;
  84571. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  84572. var currentRotation = mainImpostor.object.rotationQuaternion;
  84573. if (meshChildren.length) {
  84574. var processMesh = function (localPosition, mesh) {
  84575. if (!currentRotation || !mesh.rotationQuaternion) {
  84576. return;
  84577. }
  84578. var childImpostor = mesh.getPhysicsImpostor();
  84579. if (childImpostor) {
  84580. var parent = childImpostor.parent;
  84581. if (parent !== mainImpostor) {
  84582. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  84583. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  84584. if (childImpostor.physicsBody) {
  84585. _this.removePhysicsBody(childImpostor);
  84586. childImpostor.physicsBody = null;
  84587. }
  84588. childImpostor.parent = mainImpostor;
  84589. childImpostor.resetUpdateFlags();
  84590. 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));
  84591. //Add the mass of the children.
  84592. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  84593. }
  84594. }
  84595. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  84596. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  84597. };
  84598. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  84599. }
  84600. };
  84601. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  84602. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  84603. this.world.removeEventListener("preStep", impostor.beforeStep);
  84604. this.world.removeEventListener("postStep", impostor.afterStep);
  84605. this.world.remove(impostor.physicsBody);
  84606. };
  84607. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  84608. var mainBody = impostorJoint.mainImpostor.physicsBody;
  84609. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  84610. if (!mainBody || !connectedBody) {
  84611. return;
  84612. }
  84613. var constraint;
  84614. var jointData = impostorJoint.joint.jointData;
  84615. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  84616. var constraintData = {
  84617. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  84618. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  84619. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  84620. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  84621. maxForce: jointData.nativeParams.maxForce,
  84622. collideConnected: !!jointData.collision
  84623. };
  84624. switch (impostorJoint.joint.type) {
  84625. case BABYLON.PhysicsJoint.HingeJoint:
  84626. case BABYLON.PhysicsJoint.Hinge2Joint:
  84627. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  84628. break;
  84629. case BABYLON.PhysicsJoint.DistanceJoint:
  84630. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  84631. break;
  84632. case BABYLON.PhysicsJoint.SpringJoint:
  84633. var springData = jointData;
  84634. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  84635. restLength: springData.length,
  84636. stiffness: springData.stiffness,
  84637. damping: springData.damping,
  84638. localAnchorA: constraintData.pivotA,
  84639. localAnchorB: constraintData.pivotB
  84640. });
  84641. break;
  84642. case BABYLON.PhysicsJoint.LockJoint:
  84643. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  84644. break;
  84645. case BABYLON.PhysicsJoint.PointToPointJoint:
  84646. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  84647. default:
  84648. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  84649. break;
  84650. }
  84651. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  84652. constraint.collideConnected = !!jointData.collision;
  84653. impostorJoint.joint.physicsJoint = constraint;
  84654. //don't add spring as constraint, as it is not one.
  84655. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  84656. this.world.addConstraint(constraint);
  84657. }
  84658. else {
  84659. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  84660. constraint.applyForce();
  84661. });
  84662. }
  84663. };
  84664. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  84665. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  84666. };
  84667. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  84668. var index;
  84669. var mat;
  84670. for (index = 0; index < this._physicsMaterials.length; index++) {
  84671. mat = this._physicsMaterials[index];
  84672. if (mat.friction === friction && mat.restitution === restitution) {
  84673. return mat;
  84674. }
  84675. }
  84676. var currentMat = new this.BJSCANNON.Material(name);
  84677. currentMat.friction = friction;
  84678. currentMat.restitution = restitution;
  84679. this._physicsMaterials.push(currentMat);
  84680. return currentMat;
  84681. };
  84682. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  84683. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  84684. };
  84685. CannonJSPlugin.prototype._createShape = function (impostor) {
  84686. var object = impostor.object;
  84687. var returnValue;
  84688. var extendSize = impostor.getObjectExtendSize();
  84689. switch (impostor.type) {
  84690. case BABYLON.PhysicsImpostor.SphereImpostor:
  84691. var radiusX = extendSize.x;
  84692. var radiusY = extendSize.y;
  84693. var radiusZ = extendSize.z;
  84694. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  84695. break;
  84696. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  84697. case BABYLON.PhysicsImpostor.CylinderImpostor:
  84698. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  84699. break;
  84700. case BABYLON.PhysicsImpostor.BoxImpostor:
  84701. var box = extendSize.scale(0.5);
  84702. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  84703. break;
  84704. case BABYLON.PhysicsImpostor.PlaneImpostor:
  84705. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  84706. returnValue = new this.BJSCANNON.Plane();
  84707. break;
  84708. case BABYLON.PhysicsImpostor.MeshImpostor:
  84709. // should transform the vertex data to world coordinates!!
  84710. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  84711. var rawFaces = object.getIndices ? object.getIndices() : [];
  84712. if (!rawVerts)
  84713. return;
  84714. // get only scale! so the object could transform correctly.
  84715. var oldPosition = object.position.clone();
  84716. var oldRotation = object.rotation && object.rotation.clone();
  84717. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  84718. object.position.copyFromFloats(0, 0, 0);
  84719. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  84720. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  84721. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  84722. var transform = object.computeWorldMatrix(true);
  84723. // convert rawVerts to object space
  84724. var temp = new Array();
  84725. var index;
  84726. for (index = 0; index < rawVerts.length; index += 3) {
  84727. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  84728. }
  84729. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  84730. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  84731. //now set back the transformation!
  84732. object.position.copyFrom(oldPosition);
  84733. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  84734. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  84735. break;
  84736. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  84737. var oldPosition2 = object.position.clone();
  84738. var oldRotation2 = object.rotation && object.rotation.clone();
  84739. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  84740. object.position.copyFromFloats(0, 0, 0);
  84741. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  84742. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  84743. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  84744. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  84745. returnValue = this._createHeightmap(object);
  84746. object.position.copyFrom(oldPosition2);
  84747. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  84748. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  84749. object.computeWorldMatrix(true);
  84750. break;
  84751. case BABYLON.PhysicsImpostor.ParticleImpostor:
  84752. returnValue = new this.BJSCANNON.Particle();
  84753. break;
  84754. }
  84755. return returnValue;
  84756. };
  84757. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  84758. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  84759. var transform = object.computeWorldMatrix(true);
  84760. // convert rawVerts to object space
  84761. var temp = new Array();
  84762. var index;
  84763. for (index = 0; index < pos.length; index += 3) {
  84764. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  84765. }
  84766. pos = temp;
  84767. var matrix = new Array();
  84768. //For now pointDepth will not be used and will be automatically calculated.
  84769. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  84770. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  84771. var boundingInfo = object.getBoundingInfo();
  84772. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  84773. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  84774. var elementSize = dim * 2 / arraySize;
  84775. for (var i = 0; i < pos.length; i = i + 3) {
  84776. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  84777. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  84778. var y = -pos[i + 2] + minY;
  84779. if (!matrix[x]) {
  84780. matrix[x] = [];
  84781. }
  84782. if (!matrix[x][z]) {
  84783. matrix[x][z] = y;
  84784. }
  84785. matrix[x][z] = Math.max(y, matrix[x][z]);
  84786. }
  84787. for (var x = 0; x <= arraySize; ++x) {
  84788. if (!matrix[x]) {
  84789. var loc = 1;
  84790. while (!matrix[(x + loc) % arraySize]) {
  84791. loc++;
  84792. }
  84793. matrix[x] = matrix[(x + loc) % arraySize].slice();
  84794. //console.log("missing x", x);
  84795. }
  84796. for (var z = 0; z <= arraySize; ++z) {
  84797. if (!matrix[x][z]) {
  84798. var loc = 1;
  84799. var newValue;
  84800. while (newValue === undefined) {
  84801. newValue = matrix[x][(z + loc++) % arraySize];
  84802. }
  84803. matrix[x][z] = newValue;
  84804. }
  84805. }
  84806. }
  84807. var shape = new this.BJSCANNON.Heightfield(matrix, {
  84808. elementSize: elementSize
  84809. });
  84810. //For future reference, needed for body transformation
  84811. shape.minY = minY;
  84812. return shape;
  84813. };
  84814. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  84815. var object = impostor.object;
  84816. //make sure it is updated...
  84817. object.computeWorldMatrix && object.computeWorldMatrix(true);
  84818. // The delta between the mesh position and the mesh bounding box center
  84819. var bInfo = object.getBoundingInfo();
  84820. if (!bInfo)
  84821. return;
  84822. var center = impostor.getObjectCenter();
  84823. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  84824. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  84825. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  84826. this._tmpPosition.copyFrom(center);
  84827. var quaternion = object.rotationQuaternion;
  84828. if (!quaternion) {
  84829. return;
  84830. }
  84831. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  84832. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  84833. //-90 DEG in X, precalculated
  84834. quaternion = quaternion.multiply(this._minus90X);
  84835. //Invert! (Precalculated, 90 deg in X)
  84836. //No need to clone. this will never change.
  84837. impostor.setDeltaRotation(this._plus90X);
  84838. }
  84839. //If it is a heightfield, if should be centered.
  84840. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  84841. var mesh = object;
  84842. var boundingInfo = mesh.getBoundingInfo();
  84843. //calculate the correct body position:
  84844. var rotationQuaternion = mesh.rotationQuaternion;
  84845. mesh.rotationQuaternion = this._tmpUnityRotation;
  84846. mesh.computeWorldMatrix(true);
  84847. //get original center with no rotation
  84848. var c = center.clone();
  84849. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  84850. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  84851. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  84852. mesh.setPreTransformMatrix(p);
  84853. mesh.computeWorldMatrix(true);
  84854. //calculate the translation
  84855. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  84856. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  84857. //add it inverted to the delta
  84858. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  84859. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  84860. //rotation is back
  84861. mesh.rotationQuaternion = rotationQuaternion;
  84862. mesh.setPreTransformMatrix(oldPivot);
  84863. mesh.computeWorldMatrix(true);
  84864. }
  84865. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  84866. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  84867. //this._tmpPosition.copyFrom(object.position);
  84868. }
  84869. impostor.setDeltaPosition(this._tmpDeltaPosition);
  84870. //Now update the impostor object
  84871. impostor.physicsBody.position.copy(this._tmpPosition);
  84872. impostor.physicsBody.quaternion.copy(quaternion);
  84873. };
  84874. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84875. impostor.object.position.copyFrom(impostor.physicsBody.position);
  84876. if (impostor.object.rotationQuaternion) {
  84877. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  84878. }
  84879. };
  84880. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84881. impostor.physicsBody.position.copy(newPosition);
  84882. impostor.physicsBody.quaternion.copy(newRotation);
  84883. };
  84884. CannonJSPlugin.prototype.isSupported = function () {
  84885. return this.BJSCANNON !== undefined;
  84886. };
  84887. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84888. impostor.physicsBody.velocity.copy(velocity);
  84889. };
  84890. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84891. impostor.physicsBody.angularVelocity.copy(velocity);
  84892. };
  84893. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84894. var v = impostor.physicsBody.velocity;
  84895. if (!v) {
  84896. return null;
  84897. }
  84898. return new BABYLON.Vector3(v.x, v.y, v.z);
  84899. };
  84900. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84901. var v = impostor.physicsBody.angularVelocity;
  84902. if (!v) {
  84903. return null;
  84904. }
  84905. return new BABYLON.Vector3(v.x, v.y, v.z);
  84906. };
  84907. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84908. impostor.physicsBody.mass = mass;
  84909. impostor.physicsBody.updateMassProperties();
  84910. };
  84911. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  84912. return impostor.physicsBody.mass;
  84913. };
  84914. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  84915. return impostor.physicsBody.material.friction;
  84916. };
  84917. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84918. impostor.physicsBody.material.friction = friction;
  84919. };
  84920. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84921. return impostor.physicsBody.material.restitution;
  84922. };
  84923. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84924. impostor.physicsBody.material.restitution = restitution;
  84925. };
  84926. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  84927. impostor.physicsBody.sleep();
  84928. };
  84929. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  84930. impostor.physicsBody.wakeUp();
  84931. };
  84932. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84933. joint.physicsJoint.distance = maxDistance;
  84934. };
  84935. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84936. // if (!motorIndex) {
  84937. // joint.physicsJoint.enableMotor();
  84938. // }
  84939. // }
  84940. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84941. // if (!motorIndex) {
  84942. // joint.physicsJoint.disableMotor();
  84943. // }
  84944. // }
  84945. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84946. if (!motorIndex) {
  84947. joint.physicsJoint.enableMotor();
  84948. joint.physicsJoint.setMotorSpeed(speed);
  84949. if (maxForce) {
  84950. this.setLimit(joint, maxForce);
  84951. }
  84952. }
  84953. };
  84954. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  84955. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  84956. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  84957. };
  84958. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84959. var body = impostor.physicsBody;
  84960. mesh.position.x = body.position.x;
  84961. mesh.position.y = body.position.y;
  84962. mesh.position.z = body.position.z;
  84963. if (mesh.rotationQuaternion) {
  84964. mesh.rotationQuaternion.x = body.quaternion.x;
  84965. mesh.rotationQuaternion.y = body.quaternion.y;
  84966. mesh.rotationQuaternion.z = body.quaternion.z;
  84967. mesh.rotationQuaternion.w = body.quaternion.w;
  84968. }
  84969. };
  84970. CannonJSPlugin.prototype.getRadius = function (impostor) {
  84971. var shape = impostor.physicsBody.shapes[0];
  84972. return shape.boundingSphereRadius;
  84973. };
  84974. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84975. var shape = impostor.physicsBody.shapes[0];
  84976. result.x = shape.halfExtents.x * 2;
  84977. result.y = shape.halfExtents.y * 2;
  84978. result.z = shape.halfExtents.z * 2;
  84979. };
  84980. CannonJSPlugin.prototype.dispose = function () {
  84981. };
  84982. CannonJSPlugin.prototype._extendNamespace = function () {
  84983. //this will force cannon to execute at least one step when using interpolation
  84984. var step_tmp1 = new this.BJSCANNON.Vec3();
  84985. var Engine = this.BJSCANNON;
  84986. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  84987. maxSubSteps = maxSubSteps || 10;
  84988. timeSinceLastCalled = timeSinceLastCalled || 0;
  84989. if (timeSinceLastCalled === 0) {
  84990. this.internalStep(dt);
  84991. this.time += dt;
  84992. }
  84993. else {
  84994. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  84995. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  84996. var t0 = performance.now();
  84997. for (var i = 0; i !== internalSteps; i++) {
  84998. this.internalStep(dt);
  84999. if (performance.now() - t0 > dt * 1000) {
  85000. break;
  85001. }
  85002. }
  85003. this.time += timeSinceLastCalled;
  85004. var h = this.time % dt;
  85005. var h_div_dt = h / dt;
  85006. var interpvelo = step_tmp1;
  85007. var bodies = this.bodies;
  85008. for (var j = 0; j !== bodies.length; j++) {
  85009. var b = bodies[j];
  85010. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  85011. b.position.vsub(b.previousPosition, interpvelo);
  85012. interpvelo.scale(h_div_dt, interpvelo);
  85013. b.position.vadd(interpvelo, b.interpolatedPosition);
  85014. }
  85015. else {
  85016. b.interpolatedPosition.copy(b.position);
  85017. b.interpolatedQuaternion.copy(b.quaternion);
  85018. }
  85019. }
  85020. }
  85021. };
  85022. };
  85023. return CannonJSPlugin;
  85024. }());
  85025. BABYLON.CannonJSPlugin = CannonJSPlugin;
  85026. })(BABYLON || (BABYLON = {}));
  85027. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  85028. var BABYLON;
  85029. (function (BABYLON) {
  85030. var OimoJSPlugin = /** @class */ (function () {
  85031. function OimoJSPlugin(iterations) {
  85032. this.name = "OimoJSPlugin";
  85033. this._tmpImpostorsArray = [];
  85034. this._tmpPositionVector = BABYLON.Vector3.Zero();
  85035. this.BJSOIMO = OIMO;
  85036. this.world = new this.BJSOIMO.World({
  85037. iterations: iterations
  85038. });
  85039. this.world.clear();
  85040. }
  85041. OimoJSPlugin.prototype.setGravity = function (gravity) {
  85042. this.world.gravity.copy(gravity);
  85043. };
  85044. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  85045. this.world.timeStep = timeStep;
  85046. };
  85047. OimoJSPlugin.prototype.getTimeStep = function () {
  85048. return this.world.timeStep;
  85049. };
  85050. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  85051. var _this = this;
  85052. impostors.forEach(function (impostor) {
  85053. impostor.beforeStep();
  85054. });
  85055. this.world.step();
  85056. impostors.forEach(function (impostor) {
  85057. impostor.afterStep();
  85058. //update the ordered impostors array
  85059. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  85060. });
  85061. //check for collisions
  85062. var contact = this.world.contacts;
  85063. while (contact !== null) {
  85064. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  85065. contact = contact.next;
  85066. continue;
  85067. }
  85068. //is this body colliding with any other? get the impostor
  85069. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  85070. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  85071. if (!mainImpostor || !collidingImpostor) {
  85072. contact = contact.next;
  85073. continue;
  85074. }
  85075. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  85076. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  85077. contact = contact.next;
  85078. }
  85079. };
  85080. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85081. var mass = impostor.physicsBody.mass;
  85082. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  85083. };
  85084. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85085. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  85086. this.applyImpulse(impostor, force, contactPoint);
  85087. };
  85088. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85089. var _this = this;
  85090. //parent-child relationship. Does this impostor has a parent impostor?
  85091. if (impostor.parent) {
  85092. if (impostor.physicsBody) {
  85093. this.removePhysicsBody(impostor);
  85094. //TODO is that needed?
  85095. impostor.forceUpdate();
  85096. }
  85097. return;
  85098. }
  85099. if (impostor.isBodyInitRequired()) {
  85100. var bodyConfig = {
  85101. name: impostor.uniqueId,
  85102. //Oimo must have mass, also for static objects.
  85103. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  85104. size: [],
  85105. type: [],
  85106. pos: [],
  85107. posShape: [],
  85108. rot: [],
  85109. rotShape: [],
  85110. move: impostor.getParam("mass") !== 0,
  85111. density: impostor.getParam("mass"),
  85112. friction: impostor.getParam("friction"),
  85113. restitution: impostor.getParam("restitution"),
  85114. //Supporting older versions of Oimo
  85115. world: this.world
  85116. };
  85117. var impostors = [impostor];
  85118. var addToArray = function (parent) {
  85119. if (!parent.getChildMeshes)
  85120. return;
  85121. parent.getChildMeshes().forEach(function (m) {
  85122. if (m.physicsImpostor) {
  85123. impostors.push(m.physicsImpostor);
  85124. //m.physicsImpostor._init();
  85125. }
  85126. });
  85127. };
  85128. addToArray(impostor.object);
  85129. var checkWithEpsilon_1 = function (value) {
  85130. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  85131. };
  85132. impostors.forEach(function (i) {
  85133. if (!i.object.rotationQuaternion) {
  85134. return;
  85135. }
  85136. //get the correct bounding box
  85137. var oldQuaternion = i.object.rotationQuaternion;
  85138. var rot = oldQuaternion.toEulerAngles();
  85139. var extendSize = i.getObjectExtendSize();
  85140. var radToDeg = 57.295779513082320876;
  85141. if (i === impostor) {
  85142. var center = impostor.getObjectCenter();
  85143. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  85144. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  85145. //Can also use Array.prototype.push.apply
  85146. bodyConfig.pos.push(center.x);
  85147. bodyConfig.pos.push(center.y);
  85148. bodyConfig.pos.push(center.z);
  85149. bodyConfig.posShape.push(0, 0, 0);
  85150. //tmp solution
  85151. bodyConfig.rot.push(rot.x * radToDeg);
  85152. bodyConfig.rot.push(rot.y * radToDeg);
  85153. bodyConfig.rot.push(rot.z * radToDeg);
  85154. bodyConfig.rotShape.push(0, 0, 0);
  85155. }
  85156. else {
  85157. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  85158. bodyConfig.posShape.push(localPosition.x);
  85159. bodyConfig.posShape.push(localPosition.y);
  85160. bodyConfig.posShape.push(localPosition.z);
  85161. bodyConfig.pos.push(0, 0, 0);
  85162. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  85163. bodyConfig.rot.push(0);
  85164. bodyConfig.rot.push(0);
  85165. bodyConfig.rot.push(0);
  85166. bodyConfig.rotShape.push(rot.x * radToDeg);
  85167. bodyConfig.rotShape.push(rot.y * radToDeg);
  85168. bodyConfig.rotShape.push(rot.z * radToDeg);
  85169. }
  85170. // register mesh
  85171. switch (i.type) {
  85172. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85173. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  85174. case BABYLON.PhysicsImpostor.SphereImpostor:
  85175. var radiusX = extendSize.x;
  85176. var radiusY = extendSize.y;
  85177. var radiusZ = extendSize.z;
  85178. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  85179. bodyConfig.type.push('sphere');
  85180. //due to the way oimo works with compounds, add 3 times
  85181. bodyConfig.size.push(size);
  85182. bodyConfig.size.push(size);
  85183. bodyConfig.size.push(size);
  85184. break;
  85185. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85186. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  85187. var sizeY = checkWithEpsilon_1(extendSize.y);
  85188. bodyConfig.type.push('cylinder');
  85189. bodyConfig.size.push(sizeX);
  85190. bodyConfig.size.push(sizeY);
  85191. //due to the way oimo works with compounds, add one more value.
  85192. bodyConfig.size.push(sizeY);
  85193. break;
  85194. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85195. case BABYLON.PhysicsImpostor.BoxImpostor:
  85196. default:
  85197. var sizeX = checkWithEpsilon_1(extendSize.x);
  85198. var sizeY = checkWithEpsilon_1(extendSize.y);
  85199. var sizeZ = checkWithEpsilon_1(extendSize.z);
  85200. bodyConfig.type.push('box');
  85201. //if (i === impostor) {
  85202. bodyConfig.size.push(sizeX);
  85203. bodyConfig.size.push(sizeY);
  85204. bodyConfig.size.push(sizeZ);
  85205. //} else {
  85206. // bodyConfig.size.push(0,0,0);
  85207. //}
  85208. break;
  85209. }
  85210. //actually not needed, but hey...
  85211. i.object.rotationQuaternion = oldQuaternion;
  85212. });
  85213. impostor.physicsBody = this.world.add(bodyConfig);
  85214. }
  85215. else {
  85216. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  85217. }
  85218. impostor.setDeltaPosition(this._tmpPositionVector);
  85219. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  85220. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  85221. };
  85222. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85223. //impostor.physicsBody.dispose();
  85224. //Same as : (older oimo versions)
  85225. this.world.removeRigidBody(impostor.physicsBody);
  85226. };
  85227. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85228. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85229. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85230. if (!mainBody || !connectedBody) {
  85231. return;
  85232. }
  85233. var jointData = impostorJoint.joint.jointData;
  85234. var options = jointData.nativeParams || {};
  85235. var type;
  85236. var nativeJointData = {
  85237. body1: mainBody,
  85238. body2: connectedBody,
  85239. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  85240. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  85241. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  85242. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  85243. min: options.min,
  85244. max: options.max,
  85245. collision: options.collision || jointData.collision,
  85246. spring: options.spring,
  85247. //supporting older version of Oimo
  85248. world: this.world
  85249. };
  85250. switch (impostorJoint.joint.type) {
  85251. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85252. type = "jointBall";
  85253. break;
  85254. case BABYLON.PhysicsJoint.SpringJoint:
  85255. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  85256. var springData = jointData;
  85257. nativeJointData.min = springData.length || nativeJointData.min;
  85258. //Max should also be set, just make sure it is at least min
  85259. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  85260. case BABYLON.PhysicsJoint.DistanceJoint:
  85261. type = "jointDistance";
  85262. nativeJointData.max = jointData.maxDistance;
  85263. break;
  85264. case BABYLON.PhysicsJoint.PrismaticJoint:
  85265. type = "jointPrisme";
  85266. break;
  85267. case BABYLON.PhysicsJoint.SliderJoint:
  85268. type = "jointSlide";
  85269. break;
  85270. case BABYLON.PhysicsJoint.WheelJoint:
  85271. type = "jointWheel";
  85272. break;
  85273. case BABYLON.PhysicsJoint.HingeJoint:
  85274. default:
  85275. type = "jointHinge";
  85276. break;
  85277. }
  85278. nativeJointData.type = type;
  85279. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  85280. };
  85281. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85282. //Bug in Oimo prevents us from disposing a joint in the playground
  85283. //joint.joint.physicsJoint.dispose();
  85284. //So we will bruteforce it!
  85285. try {
  85286. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  85287. }
  85288. catch (e) {
  85289. BABYLON.Tools.Warn(e);
  85290. }
  85291. };
  85292. OimoJSPlugin.prototype.isSupported = function () {
  85293. return this.BJSOIMO !== undefined;
  85294. };
  85295. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  85296. if (!impostor.physicsBody.sleeping) {
  85297. //TODO check that
  85298. /*if (impostor.physicsBody.shapes.next) {
  85299. var parentShape = this._getLastShape(impostor.physicsBody);
  85300. impostor.object.position.copyFrom(parentShape.position);
  85301. console.log(parentShape.position);
  85302. } else {*/
  85303. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  85304. //}
  85305. if (impostor.object.rotationQuaternion) {
  85306. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  85307. }
  85308. }
  85309. };
  85310. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  85311. var body = impostor.physicsBody;
  85312. body.position.copy(newPosition);
  85313. body.orientation.copy(newRotation);
  85314. body.syncShapes();
  85315. body.awake();
  85316. };
  85317. /*private _getLastShape(body: any): any {
  85318. var lastShape = body.shapes;
  85319. while (lastShape.next) {
  85320. lastShape = lastShape.next;
  85321. }
  85322. return lastShape;
  85323. }*/
  85324. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  85325. impostor.physicsBody.linearVelocity.copy(velocity);
  85326. };
  85327. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  85328. impostor.physicsBody.angularVelocity.copy(velocity);
  85329. };
  85330. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  85331. var v = impostor.physicsBody.linearVelocity;
  85332. if (!v) {
  85333. return null;
  85334. }
  85335. return new BABYLON.Vector3(v.x, v.y, v.z);
  85336. };
  85337. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  85338. var v = impostor.physicsBody.angularVelocity;
  85339. if (!v) {
  85340. return null;
  85341. }
  85342. return new BABYLON.Vector3(v.x, v.y, v.z);
  85343. };
  85344. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  85345. var staticBody = mass === 0;
  85346. //this will actually set the body's density and not its mass.
  85347. //But this is how oimo treats the mass variable.
  85348. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  85349. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  85350. };
  85351. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  85352. return impostor.physicsBody.shapes.density;
  85353. };
  85354. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  85355. return impostor.physicsBody.shapes.friction;
  85356. };
  85357. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  85358. impostor.physicsBody.shapes.friction = friction;
  85359. };
  85360. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  85361. return impostor.physicsBody.shapes.restitution;
  85362. };
  85363. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  85364. impostor.physicsBody.shapes.restitution = restitution;
  85365. };
  85366. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  85367. impostor.physicsBody.sleep();
  85368. };
  85369. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  85370. impostor.physicsBody.awake();
  85371. };
  85372. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  85373. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  85374. if (minDistance !== void 0) {
  85375. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  85376. }
  85377. };
  85378. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  85379. //TODO separate rotational and transational motors.
  85380. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  85381. if (motor) {
  85382. motor.setMotor(speed, maxForce);
  85383. }
  85384. };
  85385. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  85386. //TODO separate rotational and transational motors.
  85387. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  85388. if (motor) {
  85389. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  85390. }
  85391. };
  85392. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  85393. var body = impostor.physicsBody;
  85394. mesh.position.x = body.position.x;
  85395. mesh.position.y = body.position.y;
  85396. mesh.position.z = body.position.z;
  85397. if (mesh.rotationQuaternion) {
  85398. mesh.rotationQuaternion.x = body.orientation.x;
  85399. mesh.rotationQuaternion.y = body.orientation.y;
  85400. mesh.rotationQuaternion.z = body.orientation.z;
  85401. mesh.rotationQuaternion.w = body.orientation.s;
  85402. }
  85403. };
  85404. OimoJSPlugin.prototype.getRadius = function (impostor) {
  85405. return impostor.physicsBody.shapes.radius;
  85406. };
  85407. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  85408. var shape = impostor.physicsBody.shapes;
  85409. result.x = shape.halfWidth * 2;
  85410. result.y = shape.halfHeight * 2;
  85411. result.z = shape.halfDepth * 2;
  85412. };
  85413. OimoJSPlugin.prototype.dispose = function () {
  85414. this.world.clear();
  85415. };
  85416. return OimoJSPlugin;
  85417. }());
  85418. BABYLON.OimoJSPlugin = OimoJSPlugin;
  85419. })(BABYLON || (BABYLON = {}));
  85420. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  85421. var BABYLON;
  85422. (function (BABYLON) {
  85423. /*
  85424. * Based on jsTGALoader - Javascript loader for TGA file
  85425. * By Vincent Thibault
  85426. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  85427. */
  85428. var TGATools = /** @class */ (function () {
  85429. function TGATools() {
  85430. }
  85431. TGATools.GetTGAHeader = function (data) {
  85432. var offset = 0;
  85433. var header = {
  85434. id_length: data[offset++],
  85435. colormap_type: data[offset++],
  85436. image_type: data[offset++],
  85437. colormap_index: data[offset++] | data[offset++] << 8,
  85438. colormap_length: data[offset++] | data[offset++] << 8,
  85439. colormap_size: data[offset++],
  85440. origin: [
  85441. data[offset++] | data[offset++] << 8,
  85442. data[offset++] | data[offset++] << 8
  85443. ],
  85444. width: data[offset++] | data[offset++] << 8,
  85445. height: data[offset++] | data[offset++] << 8,
  85446. pixel_size: data[offset++],
  85447. flags: data[offset++]
  85448. };
  85449. return header;
  85450. };
  85451. TGATools.UploadContent = function (gl, data) {
  85452. // Not enough data to contain header ?
  85453. if (data.length < 19) {
  85454. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  85455. return;
  85456. }
  85457. // Read Header
  85458. var offset = 18;
  85459. var header = TGATools.GetTGAHeader(data);
  85460. // Assume it's a valid Targa file.
  85461. if (header.id_length + offset > data.length) {
  85462. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  85463. return;
  85464. }
  85465. // Skip not needed data
  85466. offset += header.id_length;
  85467. var use_rle = false;
  85468. var use_pal = false;
  85469. var use_grey = false;
  85470. // Get some informations.
  85471. switch (header.image_type) {
  85472. case TGATools._TYPE_RLE_INDEXED:
  85473. use_rle = true;
  85474. case TGATools._TYPE_INDEXED:
  85475. use_pal = true;
  85476. break;
  85477. case TGATools._TYPE_RLE_RGB:
  85478. use_rle = true;
  85479. case TGATools._TYPE_RGB:
  85480. // use_rgb = true;
  85481. break;
  85482. case TGATools._TYPE_RLE_GREY:
  85483. use_rle = true;
  85484. case TGATools._TYPE_GREY:
  85485. use_grey = true;
  85486. break;
  85487. }
  85488. var pixel_data;
  85489. // var numAlphaBits = header.flags & 0xf;
  85490. var pixel_size = header.pixel_size >> 3;
  85491. var pixel_total = header.width * header.height * pixel_size;
  85492. // Read palettes
  85493. var palettes;
  85494. if (use_pal) {
  85495. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  85496. }
  85497. // Read LRE
  85498. if (use_rle) {
  85499. pixel_data = new Uint8Array(pixel_total);
  85500. var c, count, i;
  85501. var localOffset = 0;
  85502. var pixels = new Uint8Array(pixel_size);
  85503. while (offset < pixel_total && localOffset < pixel_total) {
  85504. c = data[offset++];
  85505. count = (c & 0x7f) + 1;
  85506. // RLE pixels
  85507. if (c & 0x80) {
  85508. // Bind pixel tmp array
  85509. for (i = 0; i < pixel_size; ++i) {
  85510. pixels[i] = data[offset++];
  85511. }
  85512. // Copy pixel array
  85513. for (i = 0; i < count; ++i) {
  85514. pixel_data.set(pixels, localOffset + i * pixel_size);
  85515. }
  85516. localOffset += pixel_size * count;
  85517. }
  85518. // Raw pixels
  85519. else {
  85520. count *= pixel_size;
  85521. for (i = 0; i < count; ++i) {
  85522. pixel_data[localOffset + i] = data[offset++];
  85523. }
  85524. localOffset += count;
  85525. }
  85526. }
  85527. }
  85528. // RAW Pixels
  85529. else {
  85530. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  85531. }
  85532. // Load to texture
  85533. var x_start, y_start, x_step, y_step, y_end, x_end;
  85534. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  85535. default:
  85536. case TGATools._ORIGIN_UL:
  85537. x_start = 0;
  85538. x_step = 1;
  85539. x_end = header.width;
  85540. y_start = 0;
  85541. y_step = 1;
  85542. y_end = header.height;
  85543. break;
  85544. case TGATools._ORIGIN_BL:
  85545. x_start = 0;
  85546. x_step = 1;
  85547. x_end = header.width;
  85548. y_start = header.height - 1;
  85549. y_step = -1;
  85550. y_end = -1;
  85551. break;
  85552. case TGATools._ORIGIN_UR:
  85553. x_start = header.width - 1;
  85554. x_step = -1;
  85555. x_end = -1;
  85556. y_start = 0;
  85557. y_step = 1;
  85558. y_end = header.height;
  85559. break;
  85560. case TGATools._ORIGIN_BR:
  85561. x_start = header.width - 1;
  85562. x_step = -1;
  85563. x_end = -1;
  85564. y_start = header.height - 1;
  85565. y_step = -1;
  85566. y_end = -1;
  85567. break;
  85568. }
  85569. // Load the specify method
  85570. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  85571. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  85572. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  85573. };
  85574. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85575. var image = pixel_data, colormap = palettes;
  85576. var width = header.width, height = header.height;
  85577. var color, i = 0, x, y;
  85578. var imageData = new Uint8Array(width * height * 4);
  85579. for (y = y_start; y !== y_end; y += y_step) {
  85580. for (x = x_start; x !== x_end; x += x_step, i++) {
  85581. color = image[i];
  85582. imageData[(x + width * y) * 4 + 3] = 255;
  85583. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  85584. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  85585. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  85586. }
  85587. }
  85588. return imageData;
  85589. };
  85590. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85591. var image = pixel_data;
  85592. var width = header.width, height = header.height;
  85593. var color, i = 0, x, y;
  85594. var imageData = new Uint8Array(width * height * 4);
  85595. for (y = y_start; y !== y_end; y += y_step) {
  85596. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  85597. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  85598. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  85599. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  85600. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  85601. imageData[(x + width * y) * 4 + 0] = r;
  85602. imageData[(x + width * y) * 4 + 1] = g;
  85603. imageData[(x + width * y) * 4 + 2] = b;
  85604. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  85605. }
  85606. }
  85607. return imageData;
  85608. };
  85609. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85610. var image = pixel_data;
  85611. var width = header.width, height = header.height;
  85612. var i = 0, x, y;
  85613. var imageData = new Uint8Array(width * height * 4);
  85614. for (y = y_start; y !== y_end; y += y_step) {
  85615. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  85616. imageData[(x + width * y) * 4 + 3] = 255;
  85617. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85618. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  85619. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  85620. }
  85621. }
  85622. return imageData;
  85623. };
  85624. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85625. var image = pixel_data;
  85626. var width = header.width, height = header.height;
  85627. var i = 0, x, y;
  85628. var imageData = new Uint8Array(width * height * 4);
  85629. for (y = y_start; y !== y_end; y += y_step) {
  85630. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  85631. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85632. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  85633. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  85634. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  85635. }
  85636. }
  85637. return imageData;
  85638. };
  85639. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85640. var image = pixel_data;
  85641. var width = header.width, height = header.height;
  85642. var color, i = 0, x, y;
  85643. var imageData = new Uint8Array(width * height * 4);
  85644. for (y = y_start; y !== y_end; y += y_step) {
  85645. for (x = x_start; x !== x_end; x += x_step, i++) {
  85646. color = image[i];
  85647. imageData[(x + width * y) * 4 + 0] = color;
  85648. imageData[(x + width * y) * 4 + 1] = color;
  85649. imageData[(x + width * y) * 4 + 2] = color;
  85650. imageData[(x + width * y) * 4 + 3] = 255;
  85651. }
  85652. }
  85653. return imageData;
  85654. };
  85655. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85656. var image = pixel_data;
  85657. var width = header.width, height = header.height;
  85658. var i = 0, x, y;
  85659. var imageData = new Uint8Array(width * height * 4);
  85660. for (y = y_start; y !== y_end; y += y_step) {
  85661. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  85662. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  85663. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  85664. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85665. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  85666. }
  85667. }
  85668. return imageData;
  85669. };
  85670. //private static _TYPE_NO_DATA = 0;
  85671. TGATools._TYPE_INDEXED = 1;
  85672. TGATools._TYPE_RGB = 2;
  85673. TGATools._TYPE_GREY = 3;
  85674. TGATools._TYPE_RLE_INDEXED = 9;
  85675. TGATools._TYPE_RLE_RGB = 10;
  85676. TGATools._TYPE_RLE_GREY = 11;
  85677. TGATools._ORIGIN_MASK = 0x30;
  85678. TGATools._ORIGIN_SHIFT = 0x04;
  85679. TGATools._ORIGIN_BL = 0x00;
  85680. TGATools._ORIGIN_BR = 0x01;
  85681. TGATools._ORIGIN_UL = 0x02;
  85682. TGATools._ORIGIN_UR = 0x03;
  85683. return TGATools;
  85684. }());
  85685. BABYLON.TGATools = TGATools;
  85686. })(BABYLON || (BABYLON = {}));
  85687. //# sourceMappingURL=babylon.tga.js.map
  85688. var BABYLON;
  85689. (function (BABYLON) {
  85690. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  85691. // All values and structures referenced from:
  85692. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  85693. var DDS_MAGIC = 0x20534444;
  85694. var
  85695. //DDSD_CAPS = 0x1,
  85696. //DDSD_HEIGHT = 0x2,
  85697. //DDSD_WIDTH = 0x4,
  85698. //DDSD_PITCH = 0x8,
  85699. //DDSD_PIXELFORMAT = 0x1000,
  85700. DDSD_MIPMAPCOUNT = 0x20000;
  85701. //DDSD_LINEARSIZE = 0x80000,
  85702. //DDSD_DEPTH = 0x800000;
  85703. // var DDSCAPS_COMPLEX = 0x8,
  85704. // DDSCAPS_MIPMAP = 0x400000,
  85705. // DDSCAPS_TEXTURE = 0x1000;
  85706. var DDSCAPS2_CUBEMAP = 0x200;
  85707. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  85708. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  85709. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  85710. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  85711. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  85712. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  85713. // DDSCAPS2_VOLUME = 0x200000;
  85714. var
  85715. //DDPF_ALPHAPIXELS = 0x1,
  85716. //DDPF_ALPHA = 0x2,
  85717. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  85718. //DDPF_YUV = 0x200,
  85719. DDPF_LUMINANCE = 0x20000;
  85720. function FourCCToInt32(value) {
  85721. return value.charCodeAt(0) +
  85722. (value.charCodeAt(1) << 8) +
  85723. (value.charCodeAt(2) << 16) +
  85724. (value.charCodeAt(3) << 24);
  85725. }
  85726. function Int32ToFourCC(value) {
  85727. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  85728. }
  85729. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  85730. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  85731. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  85732. var FOURCC_DX10 = FourCCToInt32("DX10");
  85733. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  85734. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  85735. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  85736. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  85737. var headerLengthInt = 31; // The header length in 32 bit ints
  85738. // Offsets into the header array
  85739. var off_magic = 0;
  85740. var off_size = 1;
  85741. var off_flags = 2;
  85742. var off_height = 3;
  85743. var off_width = 4;
  85744. var off_mipmapCount = 7;
  85745. var off_pfFlags = 20;
  85746. var off_pfFourCC = 21;
  85747. var off_RGBbpp = 22;
  85748. var off_RMask = 23;
  85749. var off_GMask = 24;
  85750. var off_BMask = 25;
  85751. var off_AMask = 26;
  85752. // var off_caps1 = 27;
  85753. var off_caps2 = 28;
  85754. // var off_caps3 = 29;
  85755. // var off_caps4 = 30;
  85756. var off_dxgiFormat = 32;
  85757. ;
  85758. var DDSTools = /** @class */ (function () {
  85759. function DDSTools() {
  85760. }
  85761. DDSTools.GetDDSInfo = function (arrayBuffer) {
  85762. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  85763. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  85764. var mipmapCount = 1;
  85765. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  85766. mipmapCount = Math.max(1, header[off_mipmapCount]);
  85767. }
  85768. var fourCC = header[off_pfFourCC];
  85769. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  85770. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85771. switch (fourCC) {
  85772. case FOURCC_D3DFMT_R16G16B16A16F:
  85773. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85774. break;
  85775. case FOURCC_D3DFMT_R32G32B32A32F:
  85776. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85777. break;
  85778. case FOURCC_DX10:
  85779. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  85780. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85781. break;
  85782. }
  85783. }
  85784. return {
  85785. width: header[off_width],
  85786. height: header[off_height],
  85787. mipmapCount: mipmapCount,
  85788. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  85789. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  85790. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  85791. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  85792. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  85793. dxgiFormat: dxgiFormat,
  85794. textureType: textureType
  85795. };
  85796. };
  85797. DDSTools._ToHalfFloat = function (value) {
  85798. if (!DDSTools._FloatView) {
  85799. DDSTools._FloatView = new Float32Array(1);
  85800. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  85801. }
  85802. DDSTools._FloatView[0] = value;
  85803. var x = DDSTools._Int32View[0];
  85804. var bits = (x >> 16) & 0x8000; /* Get the sign */
  85805. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  85806. var e = (x >> 23) & 0xff; /* Using int is faster here */
  85807. /* If zero, or denormal, or exponent underflows too much for a denormal
  85808. * half, return signed zero. */
  85809. if (e < 103) {
  85810. return bits;
  85811. }
  85812. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  85813. if (e > 142) {
  85814. bits |= 0x7c00;
  85815. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  85816. * not Inf, so make sure we set one mantissa bit too. */
  85817. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  85818. return bits;
  85819. }
  85820. /* If exponent underflows but not too much, return a denormal */
  85821. if (e < 113) {
  85822. m |= 0x0800;
  85823. /* Extra rounding may overflow and set mantissa to 0 and exponent
  85824. * to 1, which is OK. */
  85825. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  85826. return bits;
  85827. }
  85828. bits |= ((e - 112) << 10) | (m >> 1);
  85829. bits += m & 1;
  85830. return bits;
  85831. };
  85832. DDSTools._FromHalfFloat = function (value) {
  85833. var s = (value & 0x8000) >> 15;
  85834. var e = (value & 0x7C00) >> 10;
  85835. var f = value & 0x03FF;
  85836. if (e === 0) {
  85837. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  85838. }
  85839. else if (e == 0x1F) {
  85840. return f ? NaN : ((s ? -1 : 1) * Infinity);
  85841. }
  85842. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  85843. };
  85844. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85845. var destArray = new Float32Array(dataLength);
  85846. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85847. var index = 0;
  85848. for (var y = 0; y < height; y++) {
  85849. for (var x = 0; x < width; x++) {
  85850. var srcPos = (x + y * width) * 4;
  85851. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  85852. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  85853. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  85854. if (DDSTools.StoreLODInAlphaChannel) {
  85855. destArray[index + 3] = lod;
  85856. }
  85857. else {
  85858. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  85859. }
  85860. index += 4;
  85861. }
  85862. }
  85863. return destArray;
  85864. };
  85865. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85866. if (DDSTools.StoreLODInAlphaChannel) {
  85867. var destArray = new Uint16Array(dataLength);
  85868. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85869. var index = 0;
  85870. for (var y = 0; y < height; y++) {
  85871. for (var x = 0; x < width; x++) {
  85872. var srcPos = (x + y * width) * 4;
  85873. destArray[index] = srcData[srcPos];
  85874. destArray[index + 1] = srcData[srcPos + 1];
  85875. destArray[index + 2] = srcData[srcPos + 2];
  85876. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  85877. index += 4;
  85878. }
  85879. }
  85880. return destArray;
  85881. }
  85882. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  85883. };
  85884. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85885. if (DDSTools.StoreLODInAlphaChannel) {
  85886. var destArray = new Float32Array(dataLength);
  85887. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85888. var index = 0;
  85889. for (var y = 0; y < height; y++) {
  85890. for (var x = 0; x < width; x++) {
  85891. var srcPos = (x + y * width) * 4;
  85892. destArray[index] = srcData[srcPos];
  85893. destArray[index + 1] = srcData[srcPos + 1];
  85894. destArray[index + 2] = srcData[srcPos + 2];
  85895. destArray[index + 3] = lod;
  85896. index += 4;
  85897. }
  85898. }
  85899. return destArray;
  85900. }
  85901. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  85902. };
  85903. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85904. var destArray = new Uint8Array(dataLength);
  85905. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85906. var index = 0;
  85907. for (var y = 0; y < height; y++) {
  85908. for (var x = 0; x < width; x++) {
  85909. var srcPos = (x + y * width) * 4;
  85910. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  85911. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  85912. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  85913. if (DDSTools.StoreLODInAlphaChannel) {
  85914. destArray[index + 3] = lod;
  85915. }
  85916. else {
  85917. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  85918. }
  85919. index += 4;
  85920. }
  85921. }
  85922. return destArray;
  85923. };
  85924. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85925. var destArray = new Uint8Array(dataLength);
  85926. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85927. var index = 0;
  85928. for (var y = 0; y < height; y++) {
  85929. for (var x = 0; x < width; x++) {
  85930. var srcPos = (x + y * width) * 4;
  85931. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  85932. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  85933. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  85934. if (DDSTools.StoreLODInAlphaChannel) {
  85935. destArray[index + 3] = lod;
  85936. }
  85937. else {
  85938. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  85939. }
  85940. index += 4;
  85941. }
  85942. }
  85943. return destArray;
  85944. };
  85945. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  85946. var byteArray = new Uint8Array(dataLength);
  85947. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85948. var index = 0;
  85949. for (var y = 0; y < height; y++) {
  85950. for (var x = 0; x < width; x++) {
  85951. var srcPos = (x + y * width) * 4;
  85952. byteArray[index] = srcData[srcPos + rOffset];
  85953. byteArray[index + 1] = srcData[srcPos + gOffset];
  85954. byteArray[index + 2] = srcData[srcPos + bOffset];
  85955. byteArray[index + 3] = srcData[srcPos + aOffset];
  85956. index += 4;
  85957. }
  85958. }
  85959. return byteArray;
  85960. };
  85961. DDSTools._ExtractLongWordOrder = function (value) {
  85962. if (value === 0 || value === 255 || value === -16777216) {
  85963. return 0;
  85964. }
  85965. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  85966. };
  85967. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  85968. var byteArray = new Uint8Array(dataLength);
  85969. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85970. var index = 0;
  85971. for (var y = 0; y < height; y++) {
  85972. for (var x = 0; x < width; x++) {
  85973. var srcPos = (x + y * width) * 3;
  85974. byteArray[index] = srcData[srcPos + rOffset];
  85975. byteArray[index + 1] = srcData[srcPos + gOffset];
  85976. byteArray[index + 2] = srcData[srcPos + bOffset];
  85977. index += 3;
  85978. }
  85979. }
  85980. return byteArray;
  85981. };
  85982. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  85983. var byteArray = new Uint8Array(dataLength);
  85984. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85985. var index = 0;
  85986. for (var y = 0; y < height; y++) {
  85987. for (var x = 0; x < width; x++) {
  85988. var srcPos = (x + y * width);
  85989. byteArray[index] = srcData[srcPos];
  85990. index++;
  85991. }
  85992. }
  85993. return byteArray;
  85994. };
  85995. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  85996. if (lodIndex === void 0) { lodIndex = -1; }
  85997. var sphericalPolynomialFaces = null;
  85998. if (info.sphericalPolynomial) {
  85999. sphericalPolynomialFaces = new Array();
  86000. }
  86001. var ext = engine.getCaps().s3tc;
  86002. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  86003. var fourCC, width, height, dataLength = 0, dataOffset;
  86004. var byteArray, mipmapCount, mip;
  86005. var internalFormat = 0;
  86006. var format = 0;
  86007. var blockBytes = 1;
  86008. if (header[off_magic] !== DDS_MAGIC) {
  86009. BABYLON.Tools.Error("Invalid magic number in DDS header");
  86010. return;
  86011. }
  86012. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  86013. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  86014. return;
  86015. }
  86016. if (info.isCompressed && !ext) {
  86017. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  86018. return;
  86019. }
  86020. var bpp = header[off_RGBbpp];
  86021. dataOffset = header[off_size] + 4;
  86022. var computeFormats = false;
  86023. if (info.isFourCC) {
  86024. fourCC = header[off_pfFourCC];
  86025. switch (fourCC) {
  86026. case FOURCC_DXT1:
  86027. blockBytes = 8;
  86028. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  86029. break;
  86030. case FOURCC_DXT3:
  86031. blockBytes = 16;
  86032. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  86033. break;
  86034. case FOURCC_DXT5:
  86035. blockBytes = 16;
  86036. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  86037. break;
  86038. case FOURCC_D3DFMT_R16G16B16A16F:
  86039. computeFormats = true;
  86040. break;
  86041. case FOURCC_D3DFMT_R32G32B32A32F:
  86042. computeFormats = true;
  86043. break;
  86044. case FOURCC_DX10:
  86045. // There is an additionnal header so dataOffset need to be changed
  86046. dataOffset += 5 * 4; // 5 uints
  86047. var supported = false;
  86048. switch (info.dxgiFormat) {
  86049. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  86050. computeFormats = true;
  86051. supported = true;
  86052. break;
  86053. case DXGI_FORMAT_B8G8R8X8_UNORM:
  86054. info.isRGB = true;
  86055. info.isFourCC = false;
  86056. bpp = 32;
  86057. supported = true;
  86058. break;
  86059. }
  86060. if (supported) {
  86061. break;
  86062. }
  86063. default:
  86064. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  86065. return;
  86066. }
  86067. }
  86068. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  86069. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  86070. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  86071. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  86072. if (computeFormats) {
  86073. format = engine._getWebGLTextureType(info.textureType);
  86074. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86075. }
  86076. mipmapCount = 1;
  86077. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  86078. mipmapCount = Math.max(1, header[off_mipmapCount]);
  86079. }
  86080. for (var face = 0; face < faces; face++) {
  86081. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  86082. width = header[off_width];
  86083. height = header[off_height];
  86084. for (mip = 0; mip < mipmapCount; ++mip) {
  86085. if (lodIndex === -1 || lodIndex === mip) {
  86086. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  86087. var i = (lodIndex === -1) ? mip : 0;
  86088. if (!info.isCompressed && info.isFourCC) {
  86089. dataLength = width * height * 4;
  86090. var floatArray = null;
  86091. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  86092. if (bpp === 128) {
  86093. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86094. if (sphericalPolynomialFaces && i == 0) {
  86095. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86096. }
  86097. }
  86098. else if (bpp === 64) {
  86099. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86100. if (sphericalPolynomialFaces && i == 0) {
  86101. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86102. }
  86103. }
  86104. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86105. format = engine._getWebGLTextureType(info.textureType);
  86106. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86107. }
  86108. else {
  86109. if (bpp === 128) {
  86110. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86111. if (sphericalPolynomialFaces && i == 0) {
  86112. sphericalPolynomialFaces.push(floatArray);
  86113. }
  86114. }
  86115. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  86116. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86117. if (sphericalPolynomialFaces && i == 0) {
  86118. sphericalPolynomialFaces.push(floatArray);
  86119. }
  86120. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86121. format = engine._getWebGLTextureType(info.textureType);
  86122. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86123. }
  86124. else { // 64
  86125. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86126. if (sphericalPolynomialFaces && i == 0) {
  86127. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86128. }
  86129. }
  86130. }
  86131. if (floatArray) {
  86132. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  86133. }
  86134. }
  86135. else if (info.isRGB) {
  86136. if (bpp === 24) {
  86137. dataLength = width * height * 3;
  86138. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  86139. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  86140. }
  86141. else { // 32
  86142. dataLength = width * height * 4;
  86143. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  86144. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  86145. }
  86146. }
  86147. else if (info.isLuminance) {
  86148. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  86149. var unpaddedRowSize = width;
  86150. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  86151. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  86152. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  86153. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  86154. }
  86155. else {
  86156. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  86157. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  86158. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  86159. }
  86160. }
  86161. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  86162. width *= 0.5;
  86163. height *= 0.5;
  86164. width = Math.max(1.0, width);
  86165. height = Math.max(1.0, height);
  86166. }
  86167. if (currentFace !== undefined) {
  86168. // Loading a single face
  86169. break;
  86170. }
  86171. }
  86172. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  86173. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  86174. size: header[off_width],
  86175. right: sphericalPolynomialFaces[0],
  86176. left: sphericalPolynomialFaces[1],
  86177. up: sphericalPolynomialFaces[2],
  86178. down: sphericalPolynomialFaces[3],
  86179. front: sphericalPolynomialFaces[4],
  86180. back: sphericalPolynomialFaces[5],
  86181. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  86182. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  86183. gammaSpace: false,
  86184. });
  86185. }
  86186. else {
  86187. info.sphericalPolynomial = undefined;
  86188. }
  86189. };
  86190. DDSTools.StoreLODInAlphaChannel = false;
  86191. return DDSTools;
  86192. }());
  86193. BABYLON.DDSTools = DDSTools;
  86194. })(BABYLON || (BABYLON = {}));
  86195. //# sourceMappingURL=babylon.dds.js.map
  86196. var BABYLON;
  86197. (function (BABYLON) {
  86198. /**
  86199. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  86200. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  86201. */
  86202. var KhronosTextureContainer = /** @class */ (function () {
  86203. /**
  86204. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  86205. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  86206. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  86207. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  86208. */
  86209. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  86210. this.arrayBuffer = arrayBuffer;
  86211. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  86212. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  86213. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  86214. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  86215. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  86216. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  86217. BABYLON.Tools.Error("texture missing KTX identifier");
  86218. return;
  86219. }
  86220. // load the reset of the header in native 32 bit int
  86221. var header = new Int32Array(this.arrayBuffer, 12, 13);
  86222. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  86223. var oppositeEndianess = header[0] === 0x01020304;
  86224. // read all the header elements in order they exist in the file, without modification (sans endainness)
  86225. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  86226. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  86227. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  86228. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  86229. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  86230. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  86231. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  86232. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  86233. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  86234. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  86235. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  86236. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  86237. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  86238. if (this.glType !== 0) {
  86239. BABYLON.Tools.Error("only compressed formats currently supported");
  86240. return;
  86241. }
  86242. else {
  86243. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  86244. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  86245. }
  86246. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  86247. BABYLON.Tools.Error("only 2D textures currently supported");
  86248. return;
  86249. }
  86250. if (this.numberOfArrayElements !== 0) {
  86251. BABYLON.Tools.Error("texture arrays not currently supported");
  86252. return;
  86253. }
  86254. if (this.numberOfFaces !== facesExpected) {
  86255. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  86256. return;
  86257. }
  86258. // we now have a completely validated file, so could use existence of loadType as success
  86259. // would need to make this more elaborate & adjust checks above to support more than one load type
  86260. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  86261. }
  86262. // not as fast hardware based, but will probably never need to use
  86263. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  86264. return ((val & 0xFF) << 24)
  86265. | ((val & 0xFF00) << 8)
  86266. | ((val >> 8) & 0xFF00)
  86267. | ((val >> 24) & 0xFF);
  86268. };
  86269. /**
  86270. * It is assumed that the texture has already been created & is currently bound
  86271. */
  86272. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  86273. switch (this.loadType) {
  86274. case KhronosTextureContainer.COMPRESSED_2D:
  86275. this._upload2DCompressedLevels(gl, loadMipmaps);
  86276. break;
  86277. case KhronosTextureContainer.TEX_2D:
  86278. case KhronosTextureContainer.COMPRESSED_3D:
  86279. case KhronosTextureContainer.TEX_3D:
  86280. }
  86281. };
  86282. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  86283. // initialize width & height for level 1
  86284. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  86285. var width = this.pixelWidth;
  86286. var height = this.pixelHeight;
  86287. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  86288. for (var level = 0; level < mipmapCount; level++) {
  86289. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  86290. for (var face = 0; face < this.numberOfFaces; face++) {
  86291. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  86292. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  86293. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  86294. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  86295. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  86296. }
  86297. width = Math.max(1.0, width * 0.5);
  86298. height = Math.max(1.0, height * 0.5);
  86299. }
  86300. };
  86301. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  86302. // load types
  86303. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  86304. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  86305. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  86306. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  86307. return KhronosTextureContainer;
  86308. }());
  86309. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  86310. })(BABYLON || (BABYLON = {}));
  86311. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  86312. var BABYLON;
  86313. (function (BABYLON) {
  86314. var Debug;
  86315. (function (Debug) {
  86316. /**
  86317. * Class used to render a debug view of a given skeleton
  86318. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  86319. */
  86320. var SkeletonViewer = /** @class */ (function () {
  86321. /**
  86322. * Creates a new SkeletonViewer
  86323. * @param skeleton defines the skeleton to render
  86324. * @param mesh defines the mesh attached to the skeleton
  86325. * @param scene defines the hosting scene
  86326. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  86327. * @param renderingGroupId defines the rendering group id to use with the viewer
  86328. */
  86329. function SkeletonViewer(
  86330. /** defines the skeleton to render */
  86331. skeleton,
  86332. /** defines the mesh attached to the skeleton */
  86333. mesh, scene,
  86334. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  86335. autoUpdateBonesMatrices,
  86336. /** defines the rendering group id to use with the viewer */
  86337. renderingGroupId) {
  86338. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  86339. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  86340. this.skeleton = skeleton;
  86341. this.mesh = mesh;
  86342. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  86343. this.renderingGroupId = renderingGroupId;
  86344. /** Gets or sets the color used to render the skeleton */
  86345. this.color = BABYLON.Color3.White();
  86346. this._debugLines = new Array();
  86347. this._isEnabled = false;
  86348. this._scene = scene;
  86349. this.update();
  86350. this._renderFunction = this.update.bind(this);
  86351. }
  86352. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  86353. get: function () {
  86354. return this._isEnabled;
  86355. },
  86356. /** Gets or sets a boolean indicating if the viewer is enabled */
  86357. set: function (value) {
  86358. if (this._isEnabled === value) {
  86359. return;
  86360. }
  86361. this._isEnabled = value;
  86362. if (value) {
  86363. this._scene.registerBeforeRender(this._renderFunction);
  86364. }
  86365. else {
  86366. this._scene.unregisterBeforeRender(this._renderFunction);
  86367. }
  86368. },
  86369. enumerable: true,
  86370. configurable: true
  86371. });
  86372. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  86373. if (x === void 0) { x = 0; }
  86374. if (y === void 0) { y = 0; }
  86375. if (z === void 0) { z = 0; }
  86376. var tmat = BABYLON.Tmp.Matrix[0];
  86377. var parentBone = bone.getParent();
  86378. tmat.copyFrom(bone.getLocalMatrix());
  86379. if (x !== 0 || y !== 0 || z !== 0) {
  86380. var tmat2 = BABYLON.Tmp.Matrix[1];
  86381. BABYLON.Matrix.IdentityToRef(tmat2);
  86382. tmat2.m[12] = x;
  86383. tmat2.m[13] = y;
  86384. tmat2.m[14] = z;
  86385. tmat2.multiplyToRef(tmat, tmat);
  86386. }
  86387. if (parentBone) {
  86388. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  86389. }
  86390. tmat.multiplyToRef(meshMat, tmat);
  86391. position.x = tmat.m[12];
  86392. position.y = tmat.m[13];
  86393. position.z = tmat.m[14];
  86394. };
  86395. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  86396. var len = bones.length;
  86397. var meshPos = this.mesh.position;
  86398. for (var i = 0; i < len; i++) {
  86399. var bone = bones[i];
  86400. var points = this._debugLines[i];
  86401. if (!points) {
  86402. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86403. this._debugLines[i] = points;
  86404. }
  86405. this._getBonePosition(points[0], bone, meshMat);
  86406. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  86407. points[0].subtractInPlace(meshPos);
  86408. points[1].subtractInPlace(meshPos);
  86409. }
  86410. };
  86411. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  86412. var len = bones.length;
  86413. var boneNum = 0;
  86414. var meshPos = this.mesh.position;
  86415. for (var i = len - 1; i >= 0; i--) {
  86416. var childBone = bones[i];
  86417. var parentBone = childBone.getParent();
  86418. if (!parentBone) {
  86419. continue;
  86420. }
  86421. var points = this._debugLines[boneNum];
  86422. if (!points) {
  86423. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86424. this._debugLines[boneNum] = points;
  86425. }
  86426. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  86427. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  86428. points[0].subtractInPlace(meshPos);
  86429. points[1].subtractInPlace(meshPos);
  86430. boneNum++;
  86431. }
  86432. };
  86433. /** Update the viewer to sync with current skeleton state */
  86434. SkeletonViewer.prototype.update = function () {
  86435. if (this.autoUpdateBonesMatrices) {
  86436. this.skeleton.computeAbsoluteTransforms();
  86437. }
  86438. if (this.skeleton.bones[0].length === undefined) {
  86439. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  86440. }
  86441. else {
  86442. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  86443. }
  86444. if (!this._debugMesh) {
  86445. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  86446. this._debugMesh.renderingGroupId = this.renderingGroupId;
  86447. }
  86448. else {
  86449. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  86450. }
  86451. this._debugMesh.position.copyFrom(this.mesh.position);
  86452. this._debugMesh.color = this.color;
  86453. };
  86454. /** Release associated resources */
  86455. SkeletonViewer.prototype.dispose = function () {
  86456. if (this._debugMesh) {
  86457. this.isEnabled = false;
  86458. this._debugMesh.dispose();
  86459. this._debugMesh = null;
  86460. }
  86461. };
  86462. return SkeletonViewer;
  86463. }());
  86464. Debug.SkeletonViewer = SkeletonViewer;
  86465. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86466. })(BABYLON || (BABYLON = {}));
  86467. //# sourceMappingURL=babylon.skeletonViewer.js.map
  86468. /**
  86469. * Module Debug contains the (visual) components to debug a scene correctly
  86470. */
  86471. var BABYLON;
  86472. (function (BABYLON) {
  86473. var Debug;
  86474. (function (Debug) {
  86475. /**
  86476. * The Axes viewer will show 3 axes in a specific point in space
  86477. */
  86478. var AxesViewer = /** @class */ (function () {
  86479. /**
  86480. * Creates a new AxesViewer
  86481. * @param scene defines the hosting scene
  86482. * @param scaleLines defines a number used to scale line length (1 by default)
  86483. */
  86484. function AxesViewer(scene, scaleLines) {
  86485. if (scaleLines === void 0) { scaleLines = 1; }
  86486. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86487. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86488. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86489. /**
  86490. * Gets or sets a number used to scale line length
  86491. */
  86492. this.scaleLines = 1;
  86493. this.scaleLines = scaleLines;
  86494. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  86495. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  86496. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  86497. this._xmesh.renderingGroupId = 2;
  86498. this._ymesh.renderingGroupId = 2;
  86499. this._zmesh.renderingGroupId = 2;
  86500. this._xmesh.material.checkReadyOnlyOnce = true;
  86501. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  86502. this._ymesh.material.checkReadyOnlyOnce = true;
  86503. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  86504. this._zmesh.material.checkReadyOnlyOnce = true;
  86505. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  86506. this.scene = scene;
  86507. }
  86508. /**
  86509. * Force the viewer to update
  86510. * @param position defines the position of the viewer
  86511. * @param xaxis defines the x axis of the viewer
  86512. * @param yaxis defines the y axis of the viewer
  86513. * @param zaxis defines the z axis of the viewer
  86514. */
  86515. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  86516. var scaleLines = this.scaleLines;
  86517. if (this._xmesh) {
  86518. this._xmesh.position.copyFrom(position);
  86519. }
  86520. if (this._ymesh) {
  86521. this._ymesh.position.copyFrom(position);
  86522. }
  86523. if (this._zmesh) {
  86524. this._zmesh.position.copyFrom(position);
  86525. }
  86526. var point2 = this._xline[1];
  86527. point2.x = xaxis.x * scaleLines;
  86528. point2.y = xaxis.y * scaleLines;
  86529. point2.z = xaxis.z * scaleLines;
  86530. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  86531. point2 = this._yline[1];
  86532. point2.x = yaxis.x * scaleLines;
  86533. point2.y = yaxis.y * scaleLines;
  86534. point2.z = yaxis.z * scaleLines;
  86535. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  86536. point2 = this._zline[1];
  86537. point2.x = zaxis.x * scaleLines;
  86538. point2.y = zaxis.y * scaleLines;
  86539. point2.z = zaxis.z * scaleLines;
  86540. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  86541. };
  86542. /** Releases resources */
  86543. AxesViewer.prototype.dispose = function () {
  86544. if (this._xmesh) {
  86545. this._xmesh.dispose();
  86546. }
  86547. if (this._ymesh) {
  86548. this._ymesh.dispose();
  86549. }
  86550. if (this._zmesh) {
  86551. this._zmesh.dispose();
  86552. }
  86553. this._xmesh = null;
  86554. this._ymesh = null;
  86555. this._zmesh = null;
  86556. this.scene = null;
  86557. };
  86558. return AxesViewer;
  86559. }());
  86560. Debug.AxesViewer = AxesViewer;
  86561. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86562. })(BABYLON || (BABYLON = {}));
  86563. //# sourceMappingURL=babylon.axesViewer.js.map
  86564. var BABYLON;
  86565. (function (BABYLON) {
  86566. var Debug;
  86567. (function (Debug) {
  86568. /**
  86569. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  86570. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  86571. */
  86572. var BoneAxesViewer = /** @class */ (function (_super) {
  86573. __extends(BoneAxesViewer, _super);
  86574. /**
  86575. * Creates a new BoneAxesViewer
  86576. * @param scene defines the hosting scene
  86577. * @param bone defines the target bone
  86578. * @param mesh defines the target mesh
  86579. * @param scaleLines defines a scaling factor for line length (1 by default)
  86580. */
  86581. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  86582. if (scaleLines === void 0) { scaleLines = 1; }
  86583. var _this = _super.call(this, scene, scaleLines) || this;
  86584. /** Gets current position */
  86585. _this.pos = BABYLON.Vector3.Zero();
  86586. /** Gets direction of X axis */
  86587. _this.xaxis = BABYLON.Vector3.Zero();
  86588. /** Gets direction of Y axis */
  86589. _this.yaxis = BABYLON.Vector3.Zero();
  86590. /** Gets direction of Z axis */
  86591. _this.zaxis = BABYLON.Vector3.Zero();
  86592. _this.mesh = mesh;
  86593. _this.bone = bone;
  86594. return _this;
  86595. }
  86596. /**
  86597. * Force the viewer to update
  86598. */
  86599. BoneAxesViewer.prototype.update = function () {
  86600. if (!this.mesh || !this.bone) {
  86601. return;
  86602. }
  86603. var bone = this.bone;
  86604. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  86605. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  86606. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  86607. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  86608. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  86609. };
  86610. /** Releases resources */
  86611. BoneAxesViewer.prototype.dispose = function () {
  86612. if (this.mesh) {
  86613. this.mesh = null;
  86614. this.bone = null;
  86615. _super.prototype.dispose.call(this);
  86616. }
  86617. };
  86618. return BoneAxesViewer;
  86619. }(Debug.AxesViewer));
  86620. Debug.BoneAxesViewer = BoneAxesViewer;
  86621. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86622. })(BABYLON || (BABYLON = {}));
  86623. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  86624. var BABYLON;
  86625. (function (BABYLON) {
  86626. var RayHelper = /** @class */ (function () {
  86627. function RayHelper(ray) {
  86628. this.ray = ray;
  86629. }
  86630. RayHelper.CreateAndShow = function (ray, scene, color) {
  86631. var helper = new RayHelper(ray);
  86632. helper.show(scene, color);
  86633. return helper;
  86634. };
  86635. RayHelper.prototype.show = function (scene, color) {
  86636. if (!this._renderFunction && this.ray) {
  86637. var ray = this.ray;
  86638. this._renderFunction = this._render.bind(this);
  86639. this._scene = scene;
  86640. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  86641. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  86642. if (this._renderFunction) {
  86643. this._scene.registerBeforeRender(this._renderFunction);
  86644. }
  86645. }
  86646. if (color && this._renderLine) {
  86647. this._renderLine.color.copyFrom(color);
  86648. }
  86649. };
  86650. RayHelper.prototype.hide = function () {
  86651. if (this._renderFunction && this._scene) {
  86652. this._scene.unregisterBeforeRender(this._renderFunction);
  86653. this._scene = null;
  86654. this._renderFunction = null;
  86655. if (this._renderLine) {
  86656. this._renderLine.dispose();
  86657. this._renderLine = null;
  86658. }
  86659. this._renderPoints = [];
  86660. }
  86661. };
  86662. RayHelper.prototype._render = function () {
  86663. var ray = this.ray;
  86664. if (!ray) {
  86665. return;
  86666. }
  86667. var point = this._renderPoints[1];
  86668. var len = Math.min(ray.length, 1000000);
  86669. point.copyFrom(ray.direction);
  86670. point.scaleInPlace(len);
  86671. point.addInPlace(ray.origin);
  86672. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  86673. };
  86674. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  86675. this._attachedToMesh = mesh;
  86676. var ray = this.ray;
  86677. if (!ray) {
  86678. return;
  86679. }
  86680. if (!ray.direction) {
  86681. ray.direction = BABYLON.Vector3.Zero();
  86682. }
  86683. if (!ray.origin) {
  86684. ray.origin = BABYLON.Vector3.Zero();
  86685. }
  86686. if (length) {
  86687. ray.length = length;
  86688. }
  86689. if (!meshSpaceOrigin) {
  86690. meshSpaceOrigin = BABYLON.Vector3.Zero();
  86691. }
  86692. if (!meshSpaceDirection) {
  86693. // -1 so that this will work with Mesh.lookAt
  86694. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  86695. }
  86696. if (!this._meshSpaceDirection) {
  86697. this._meshSpaceDirection = meshSpaceDirection.clone();
  86698. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  86699. }
  86700. else {
  86701. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  86702. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  86703. }
  86704. if (!this._updateToMeshFunction) {
  86705. this._updateToMeshFunction = this._updateToMesh.bind(this);
  86706. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  86707. }
  86708. this._updateToMesh();
  86709. };
  86710. RayHelper.prototype.detachFromMesh = function () {
  86711. if (this._attachedToMesh) {
  86712. if (this._updateToMeshFunction) {
  86713. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  86714. }
  86715. this._attachedToMesh = null;
  86716. this._updateToMeshFunction = null;
  86717. }
  86718. };
  86719. RayHelper.prototype._updateToMesh = function () {
  86720. var ray = this.ray;
  86721. if (!this._attachedToMesh || !ray) {
  86722. return;
  86723. }
  86724. if (this._attachedToMesh._isDisposed) {
  86725. this.detachFromMesh();
  86726. return;
  86727. }
  86728. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  86729. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  86730. };
  86731. RayHelper.prototype.dispose = function () {
  86732. this.hide();
  86733. this.detachFromMesh();
  86734. this.ray = null;
  86735. };
  86736. return RayHelper;
  86737. }());
  86738. BABYLON.RayHelper = RayHelper;
  86739. })(BABYLON || (BABYLON = {}));
  86740. //# sourceMappingURL=babylon.rayHelper.js.map
  86741. var BABYLON;
  86742. (function (BABYLON) {
  86743. // load the inspector using require, if not present in the global namespace.
  86744. var DebugLayer = /** @class */ (function () {
  86745. function DebugLayer(scene) {
  86746. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  86747. this._scene = scene;
  86748. // load inspector using require, if it doesn't exist on the global namespace.
  86749. }
  86750. /** Creates the inspector window. */
  86751. DebugLayer.prototype._createInspector = function (config) {
  86752. if (config === void 0) { config = {}; }
  86753. var popup = config.popup || false;
  86754. var initialTab = config.initialTab || 0;
  86755. var parentElement = config.parentElement || null;
  86756. if (!this._inspector) {
  86757. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  86758. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  86759. } // else nothing to do,; instance is already existing
  86760. };
  86761. DebugLayer.prototype.isVisible = function () {
  86762. if (!this._inspector) {
  86763. return false;
  86764. }
  86765. return true;
  86766. };
  86767. DebugLayer.prototype.hide = function () {
  86768. if (this._inspector) {
  86769. try {
  86770. this._inspector.dispose();
  86771. }
  86772. catch (e) {
  86773. // If the inspector has been removed directly from the inspector tool
  86774. }
  86775. this._inspector = null;
  86776. }
  86777. };
  86778. /**
  86779. *
  86780. * Launch the debugLayer.
  86781. *
  86782. * initialTab:
  86783. * | Value | Tab Name |
  86784. * | --- | --- |
  86785. * | 0 | Scene |
  86786. * | 1 | Console |
  86787. * | 2 | Stats |
  86788. * | 3 | Textures |
  86789. * | 4 | Mesh |
  86790. * | 5 | Light |
  86791. * | 6 | Material |
  86792. * | 7 | GLTF |
  86793. * | 8 | GUI |
  86794. * | 9 | Physics |
  86795. * | 10 | Camera |
  86796. * | 11 | Audio |
  86797. *
  86798. */
  86799. DebugLayer.prototype.show = function (config) {
  86800. if (config === void 0) { config = {}; }
  86801. if (typeof this.BJSINSPECTOR == 'undefined') {
  86802. // Load inspector and add it to the DOM
  86803. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  86804. }
  86805. else {
  86806. // Otherwise creates the inspector
  86807. this._createInspector(config);
  86808. }
  86809. };
  86810. /**
  86811. * Gets the active tab
  86812. * @return the index of the active tab or -1 if the inspector is hidden
  86813. */
  86814. DebugLayer.prototype.getActiveTab = function () {
  86815. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  86816. };
  86817. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  86818. return DebugLayer;
  86819. }());
  86820. BABYLON.DebugLayer = DebugLayer;
  86821. })(BABYLON || (BABYLON = {}));
  86822. //# sourceMappingURL=babylon.debugLayer.js.map
  86823. var BABYLON;
  86824. (function (BABYLON) {
  86825. var Debug;
  86826. (function (Debug) {
  86827. /**
  86828. * Used to show the physics impostor around the specific mesh
  86829. */
  86830. var PhysicsViewer = /** @class */ (function () {
  86831. /**
  86832. * Creates a new PhysicsViewer
  86833. * @param scene defines the hosting scene
  86834. */
  86835. function PhysicsViewer(scene) {
  86836. /** @hidden */
  86837. this._impostors = [];
  86838. /** @hidden */
  86839. this._meshes = [];
  86840. /** @hidden */
  86841. this._numMeshes = 0;
  86842. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86843. var physicEngine = this._scene.getPhysicsEngine();
  86844. if (physicEngine) {
  86845. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  86846. }
  86847. }
  86848. /** @hidden */
  86849. PhysicsViewer.prototype._updateDebugMeshes = function () {
  86850. var plugin = this._physicsEnginePlugin;
  86851. for (var i = 0; i < this._numMeshes; i++) {
  86852. var impostor = this._impostors[i];
  86853. if (!impostor) {
  86854. continue;
  86855. }
  86856. if (impostor.isDisposed) {
  86857. this.hideImpostor(this._impostors[i--]);
  86858. }
  86859. else {
  86860. var mesh = this._meshes[i];
  86861. if (mesh && plugin) {
  86862. plugin.syncMeshWithImpostor(mesh, impostor);
  86863. }
  86864. }
  86865. }
  86866. };
  86867. /**
  86868. * Renders a specified physic impostor
  86869. * @param impostor defines the impostor to render
  86870. */
  86871. PhysicsViewer.prototype.showImpostor = function (impostor) {
  86872. if (!this._scene) {
  86873. return;
  86874. }
  86875. for (var i = 0; i < this._numMeshes; i++) {
  86876. if (this._impostors[i] == impostor) {
  86877. return;
  86878. }
  86879. }
  86880. var debugMesh = this._getDebugMesh(impostor, this._scene);
  86881. if (debugMesh) {
  86882. this._impostors[this._numMeshes] = impostor;
  86883. this._meshes[this._numMeshes] = debugMesh;
  86884. if (this._numMeshes === 0) {
  86885. this._renderFunction = this._updateDebugMeshes.bind(this);
  86886. this._scene.registerBeforeRender(this._renderFunction);
  86887. }
  86888. this._numMeshes++;
  86889. }
  86890. };
  86891. /**
  86892. * Hides a specified physic impostor
  86893. * @param impostor defines the impostor to hide
  86894. */
  86895. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  86896. if (!impostor || !this._scene) {
  86897. return;
  86898. }
  86899. var removed = false;
  86900. for (var i = 0; i < this._numMeshes; i++) {
  86901. if (this._impostors[i] == impostor) {
  86902. var mesh = this._meshes[i];
  86903. if (!mesh) {
  86904. continue;
  86905. }
  86906. this._scene.removeMesh(mesh);
  86907. mesh.dispose();
  86908. this._numMeshes--;
  86909. if (this._numMeshes > 0) {
  86910. this._meshes[i] = this._meshes[this._numMeshes];
  86911. this._impostors[i] = this._impostors[this._numMeshes];
  86912. this._meshes[this._numMeshes] = null;
  86913. this._impostors[this._numMeshes] = null;
  86914. }
  86915. else {
  86916. this._meshes[0] = null;
  86917. this._impostors[0] = null;
  86918. }
  86919. removed = true;
  86920. break;
  86921. }
  86922. }
  86923. if (removed && this._numMeshes === 0) {
  86924. this._scene.unregisterBeforeRender(this._renderFunction);
  86925. }
  86926. };
  86927. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  86928. if (!this._debugMaterial) {
  86929. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  86930. this._debugMaterial.wireframe = true;
  86931. }
  86932. return this._debugMaterial;
  86933. };
  86934. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  86935. if (!this._debugBoxMesh) {
  86936. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  86937. this._debugBoxMesh.renderingGroupId = 1;
  86938. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86939. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  86940. scene.removeMesh(this._debugBoxMesh);
  86941. }
  86942. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  86943. };
  86944. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  86945. if (!this._debugSphereMesh) {
  86946. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  86947. this._debugSphereMesh.renderingGroupId = 1;
  86948. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86949. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  86950. scene.removeMesh(this._debugSphereMesh);
  86951. }
  86952. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  86953. };
  86954. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  86955. var mesh = null;
  86956. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  86957. mesh = this._getDebugBoxMesh(scene);
  86958. impostor.getBoxSizeToRef(mesh.scaling);
  86959. }
  86960. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  86961. mesh = this._getDebugSphereMesh(scene);
  86962. var radius = impostor.getRadius();
  86963. mesh.scaling.x = radius * 2;
  86964. mesh.scaling.y = radius * 2;
  86965. mesh.scaling.z = radius * 2;
  86966. }
  86967. return mesh;
  86968. };
  86969. /** Releases all resources */
  86970. PhysicsViewer.prototype.dispose = function () {
  86971. for (var i = 0; i < this._numMeshes; i++) {
  86972. this.hideImpostor(this._impostors[i]);
  86973. }
  86974. if (this._debugBoxMesh) {
  86975. this._debugBoxMesh.dispose();
  86976. }
  86977. if (this._debugSphereMesh) {
  86978. this._debugSphereMesh.dispose();
  86979. }
  86980. if (this._debugMaterial) {
  86981. this._debugMaterial.dispose();
  86982. }
  86983. this._impostors.length = 0;
  86984. this._scene = null;
  86985. this._physicsEnginePlugin = null;
  86986. };
  86987. return PhysicsViewer;
  86988. }());
  86989. Debug.PhysicsViewer = PhysicsViewer;
  86990. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86991. })(BABYLON || (BABYLON = {}));
  86992. //# sourceMappingURL=babylon.physicsViewer.js.map
  86993. var BABYLON;
  86994. (function (BABYLON) {
  86995. var BoundingBoxRenderer = /** @class */ (function () {
  86996. function BoundingBoxRenderer(scene) {
  86997. this.frontColor = new BABYLON.Color3(1, 1, 1);
  86998. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  86999. this.showBackLines = true;
  87000. this.renderList = new BABYLON.SmartArray(32);
  87001. this._vertexBuffers = {};
  87002. this._scene = scene;
  87003. }
  87004. BoundingBoxRenderer.prototype._prepareRessources = function () {
  87005. if (this._colorShader) {
  87006. return;
  87007. }
  87008. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  87009. attributes: [BABYLON.VertexBuffer.PositionKind],
  87010. uniforms: ["world", "viewProjection", "color"]
  87011. });
  87012. var engine = this._scene.getEngine();
  87013. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  87014. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  87015. this._createIndexBuffer();
  87016. };
  87017. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  87018. var engine = this._scene.getEngine();
  87019. 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]);
  87020. };
  87021. BoundingBoxRenderer.prototype._rebuild = function () {
  87022. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87023. if (vb) {
  87024. vb._rebuild();
  87025. }
  87026. this._createIndexBuffer();
  87027. };
  87028. BoundingBoxRenderer.prototype.reset = function () {
  87029. this.renderList.reset();
  87030. };
  87031. BoundingBoxRenderer.prototype.render = function () {
  87032. if (this.renderList.length === 0) {
  87033. return;
  87034. }
  87035. this._prepareRessources();
  87036. if (!this._colorShader.isReady()) {
  87037. return;
  87038. }
  87039. var engine = this._scene.getEngine();
  87040. engine.setDepthWrite(false);
  87041. this._colorShader._preBind();
  87042. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  87043. var boundingBox = this.renderList.data[boundingBoxIndex];
  87044. var min = boundingBox.minimum;
  87045. var max = boundingBox.maximum;
  87046. var diff = max.subtract(min);
  87047. var median = min.add(diff.scale(0.5));
  87048. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87049. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87050. .multiply(boundingBox.getWorldMatrix());
  87051. // VBOs
  87052. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87053. if (this.showBackLines) {
  87054. // Back
  87055. engine.setDepthFunctionToGreaterOrEqual();
  87056. this._scene.resetCachedMaterial();
  87057. this._colorShader.setColor4("color", this.backColor.toColor4());
  87058. this._colorShader.bind(worldMatrix);
  87059. // Draw order
  87060. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87061. }
  87062. // Front
  87063. engine.setDepthFunctionToLess();
  87064. this._scene.resetCachedMaterial();
  87065. this._colorShader.setColor4("color", this.frontColor.toColor4());
  87066. this._colorShader.bind(worldMatrix);
  87067. // Draw order
  87068. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87069. }
  87070. this._colorShader.unbind();
  87071. engine.setDepthFunctionToLessOrEqual();
  87072. engine.setDepthWrite(true);
  87073. };
  87074. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  87075. this._prepareRessources();
  87076. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  87077. return;
  87078. }
  87079. var engine = this._scene.getEngine();
  87080. engine.setDepthWrite(false);
  87081. engine.setColorWrite(false);
  87082. this._colorShader._preBind();
  87083. var boundingBox = mesh._boundingInfo.boundingBox;
  87084. var min = boundingBox.minimum;
  87085. var max = boundingBox.maximum;
  87086. var diff = max.subtract(min);
  87087. var median = min.add(diff.scale(0.5));
  87088. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87089. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87090. .multiply(boundingBox.getWorldMatrix());
  87091. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87092. engine.setDepthFunctionToLess();
  87093. this._scene.resetCachedMaterial();
  87094. this._colorShader.bind(worldMatrix);
  87095. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87096. this._colorShader.unbind();
  87097. engine.setDepthFunctionToLessOrEqual();
  87098. engine.setDepthWrite(true);
  87099. engine.setColorWrite(true);
  87100. };
  87101. BoundingBoxRenderer.prototype.dispose = function () {
  87102. if (!this._colorShader) {
  87103. return;
  87104. }
  87105. this.renderList.dispose();
  87106. this._colorShader.dispose();
  87107. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87108. if (buffer) {
  87109. buffer.dispose();
  87110. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87111. }
  87112. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87113. };
  87114. return BoundingBoxRenderer;
  87115. }());
  87116. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  87117. })(BABYLON || (BABYLON = {}));
  87118. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  87119. var BABYLON;
  87120. (function (BABYLON) {
  87121. /**
  87122. * Renders a layer on top of an existing scene
  87123. */
  87124. var UtilityLayerRenderer = /** @class */ (function () {
  87125. /**
  87126. * Instantiates a UtilityLayerRenderer
  87127. * @param originalScene the original scene that will be rendered on top of
  87128. */
  87129. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  87130. var _this = this;
  87131. this.originalScene = originalScene;
  87132. this._pointerCaptures = {};
  87133. this._lastPointerEvents = {};
  87134. /**
  87135. * If the utility layer should automatically be rendered on top of existing scene
  87136. */
  87137. this.shouldRender = true;
  87138. /**
  87139. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  87140. */
  87141. this.onlyCheckPointerDownEvents = true;
  87142. /**
  87143. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  87144. */
  87145. this.processAllEvents = false;
  87146. /**
  87147. * Observable raised when the pointer move from the utility layer scene to the main scene
  87148. */
  87149. this.onPointerOutObservable = new BABYLON.Observable();
  87150. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  87151. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  87152. originalScene.getEngine().scenes.pop();
  87153. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  87154. this.utilityLayerScene.detachControl();
  87155. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  87156. if (!_this.processAllEvents) {
  87157. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  87158. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  87159. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  87160. return;
  87161. }
  87162. }
  87163. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  87164. if (!prePointerInfo.ray && utilityScenePick) {
  87165. prePointerInfo.ray = utilityScenePick.ray;
  87166. }
  87167. // always fire the prepointer oversvable
  87168. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  87169. // allow every non pointer down event to flow to the utility layer
  87170. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  87171. if (!prePointerInfo.skipOnPointerObservable) {
  87172. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87173. }
  87174. return;
  87175. }
  87176. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  87177. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  87178. if (utilityScenePick && utilityScenePick.hit) {
  87179. if (!prePointerInfo.skipOnPointerObservable) {
  87180. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87181. }
  87182. prePointerInfo.skipOnPointerObservable = true;
  87183. }
  87184. }
  87185. else {
  87186. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  87187. var pointerEvent = (prePointerInfo.event);
  87188. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  87189. if (originalScenePick && utilityScenePick) {
  87190. if (utilityScenePick.distance === 0) {
  87191. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87192. _this._pointerCaptures[pointerEvent.pointerId] = true;
  87193. }
  87194. }
  87195. if (!_this._pointerCaptures[pointerEvent.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  87196. if (!prePointerInfo.skipOnPointerObservable) {
  87197. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87198. _this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  87199. }
  87200. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  87201. }
  87202. else if (!_this._pointerCaptures[pointerEvent.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  87203. // We need to send a last pointup to the utilityLayerScene to make sure animations can complete
  87204. if (_this._lastPointerEvents[pointerEvent.pointerId]) {
  87205. _this.onPointerOutObservable.notifyObservers(pointerEvent.pointerId);
  87206. delete _this._lastPointerEvents[pointerEvent.pointerId];
  87207. }
  87208. }
  87209. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  87210. _this._pointerCaptures[pointerEvent.pointerId] = false;
  87211. }
  87212. }
  87213. }
  87214. });
  87215. // Render directly on top of existing scene without clearing
  87216. this.utilityLayerScene.autoClear = false;
  87217. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  87218. if (_this.shouldRender) {
  87219. _this.render();
  87220. }
  87221. });
  87222. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  87223. _this.dispose();
  87224. });
  87225. this._updateCamera();
  87226. }
  87227. /**
  87228. * Renders the utility layers scene on top of the original scene
  87229. */
  87230. UtilityLayerRenderer.prototype.render = function () {
  87231. this._updateCamera();
  87232. this.utilityLayerScene.render(false);
  87233. };
  87234. /**
  87235. * Disposes of the renderer
  87236. */
  87237. UtilityLayerRenderer.prototype.dispose = function () {
  87238. this.onPointerOutObservable.clear();
  87239. if (this._afterRenderObserver) {
  87240. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  87241. }
  87242. if (this._sceneDisposeObserver) {
  87243. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  87244. }
  87245. if (this._originalPointerObserver) {
  87246. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  87247. }
  87248. this.utilityLayerScene.dispose();
  87249. };
  87250. UtilityLayerRenderer.prototype._updateCamera = function () {
  87251. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  87252. };
  87253. return UtilityLayerRenderer;
  87254. }());
  87255. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  87256. })(BABYLON || (BABYLON = {}));
  87257. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  87258. var BABYLON;
  87259. (function (BABYLON) {
  87260. /**
  87261. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  87262. */
  87263. var PointerDragBehavior = /** @class */ (function () {
  87264. /**
  87265. * Creates a pointer drag behavior that can be attached to a mesh
  87266. * @param options The drag axis or normal of the plane that will be dragged across.
  87267. */
  87268. function PointerDragBehavior(options) {
  87269. this.options = options;
  87270. this._draggingID = -1;
  87271. /**
  87272. * Fires each time the attached mesh is dragged with the pointer
  87273. */
  87274. this.onDragObservable = new BABYLON.Observable();
  87275. /**
  87276. * Fires each time a drag begins (eg. mouse down on mesh)
  87277. */
  87278. this.onDragStartObservable = new BABYLON.Observable();
  87279. /**
  87280. * Fires each time a drag ends (eg. mouse release after drag)
  87281. */
  87282. this.onDragEndObservable = new BABYLON.Observable();
  87283. /**
  87284. * If the attached mesh should be moved when dragged
  87285. */
  87286. this.moveAttached = true;
  87287. /**
  87288. * Mesh with the position where the drag plane should be placed
  87289. */
  87290. this._dragPlaneParent = null;
  87291. /**
  87292. * If the drag behavior will react to drag events
  87293. */
  87294. this.enabled = true;
  87295. var optionCount = 0;
  87296. if (options.dragAxis) {
  87297. optionCount++;
  87298. }
  87299. if (options.dragPlaneNormal) {
  87300. optionCount++;
  87301. }
  87302. if (optionCount > 1) {
  87303. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  87304. }
  87305. if (optionCount < 1) {
  87306. throw "At least one drag mode option must be specified";
  87307. }
  87308. }
  87309. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  87310. /**
  87311. * The name of the behavior
  87312. */
  87313. get: function () {
  87314. return "PointerDrag";
  87315. },
  87316. enumerable: true,
  87317. configurable: true
  87318. });
  87319. /**
  87320. * Initializes the behavior
  87321. */
  87322. PointerDragBehavior.prototype.init = function () { };
  87323. /**
  87324. * Attaches the drag behavior the passed in mesh
  87325. * @param ownerNode The mesh that will be dragged around once attached
  87326. */
  87327. PointerDragBehavior.prototype.attach = function (ownerNode) {
  87328. var _this = this;
  87329. this._scene = ownerNode.getScene();
  87330. this._attachedNode = ownerNode;
  87331. // Initialize drag plane to not interfere with existing scene
  87332. if (!PointerDragBehavior._planeScene) {
  87333. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  87334. this._scene.getEngine().scenes.pop();
  87335. }
  87336. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", 1000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  87337. // State of the drag
  87338. var dragging = false;
  87339. var lastPosition = new BABYLON.Vector3(0, 0, 0);
  87340. var delta = new BABYLON.Vector3(0, 0, 0);
  87341. var pickPredicate = function (m) {
  87342. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  87343. };
  87344. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  87345. if (!_this.enabled) {
  87346. return;
  87347. }
  87348. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  87349. if (!dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  87350. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray);
  87351. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  87352. if (pickedPoint) {
  87353. dragging = true;
  87354. _this._draggingID = pointerInfo.event.pointerId;
  87355. lastPosition.copyFrom(pickedPoint);
  87356. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint });
  87357. }
  87358. }
  87359. }
  87360. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  87361. if (_this._draggingID == pointerInfo.event.pointerId) {
  87362. dragging = false;
  87363. _this._draggingID = -1;
  87364. _this.onDragEndObservable.notifyObservers({ dragPlanePoint: lastPosition });
  87365. }
  87366. }
  87367. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  87368. if (_this._draggingID == pointerInfo.event.pointerId && dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  87369. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  87370. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray);
  87371. if (pickedPoint) {
  87372. // depending on the drag mode option drag accordingly
  87373. if (_this.options.dragAxis) {
  87374. //get the closest point on the dragaxis from the selected mesh to the picked point location
  87375. // https://www.opengl.org/discussion_boards/showthread.php/159717-Closest-point-on-a-Vector-to-a-point
  87376. _this.options.dragAxis.scaleToRef(BABYLON.Vector3.Dot(pickedPoint.subtract(lastPosition), _this.options.dragAxis), delta);
  87377. }
  87378. else {
  87379. pickedPoint.subtractToRef(lastPosition, delta);
  87380. }
  87381. if (_this.moveAttached) {
  87382. _this._attachedNode.position.addInPlace(delta);
  87383. }
  87384. _this.onDragObservable.notifyObservers({ delta: delta, dragPlanePoint: pickedPoint });
  87385. lastPosition.copyFrom(pickedPoint);
  87386. }
  87387. }
  87388. }
  87389. });
  87390. };
  87391. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  87392. var _this = this;
  87393. if (!ray) {
  87394. return null;
  87395. }
  87396. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  87397. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  87398. return pickResult.pickedPoint;
  87399. }
  87400. else {
  87401. return null;
  87402. }
  87403. };
  87404. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  87405. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray) {
  87406. var pointA = this._dragPlaneParent ? this._dragPlaneParent.position : this._attachedNode.position; // center
  87407. if (this.options.dragAxis) {
  87408. var camPos = ray.origin;
  87409. // Calculate plane normal in direction of camera but perpendicular to drag axis
  87410. var pointB = pointA.add(this.options.dragAxis); // towards drag axis
  87411. var pointC = pointA.add(camPos.subtract(pointA).normalize()); // towards camera
  87412. // Get perpendicular line from direction to camera and drag axis
  87413. var lineA = pointB.subtract(pointA);
  87414. var lineB = pointC.subtract(pointA);
  87415. var perpLine = BABYLON.Vector3.Cross(lineA, lineB);
  87416. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  87417. var norm = BABYLON.Vector3.Cross(lineA, perpLine).normalize();
  87418. this._dragPlane.position.copyFrom(pointA);
  87419. this._dragPlane.lookAt(pointA.add(norm));
  87420. }
  87421. else if (this.options.dragPlaneNormal) {
  87422. this._dragPlane.position.copyFrom(pointA);
  87423. this._dragPlane.lookAt(pointA.add(this.options.dragPlaneNormal));
  87424. }
  87425. this._dragPlane.computeWorldMatrix(true);
  87426. };
  87427. /**
  87428. * Detaches the behavior from the mesh
  87429. */
  87430. PointerDragBehavior.prototype.detach = function () {
  87431. if (this._pointerObserver) {
  87432. this._scene.onPointerObservable.remove(this._pointerObserver);
  87433. }
  87434. };
  87435. return PointerDragBehavior;
  87436. }());
  87437. BABYLON.PointerDragBehavior = PointerDragBehavior;
  87438. })(BABYLON || (BABYLON = {}));
  87439. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  87440. var BABYLON;
  87441. (function (BABYLON) {
  87442. /**
  87443. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  87444. */
  87445. var Gizmo = /** @class */ (function () {
  87446. /**
  87447. * Creates a gizmo
  87448. * @param gizmoLayer The utility layer the gizmo will be added to
  87449. */
  87450. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  87451. var _this = this;
  87452. this.gizmoLayer = gizmoLayer;
  87453. this._interactionsEnabled = true;
  87454. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  87455. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  87456. if (_this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  87457. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 3;
  87458. _this._rootMesh.scaling.set(dist, dist, dist);
  87459. }
  87460. if (_this.attachedMesh) {
  87461. _this._rootMesh.position.copyFrom(_this.attachedMesh.position);
  87462. }
  87463. });
  87464. }
  87465. Gizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87466. };
  87467. Object.defineProperty(Gizmo.prototype, "interactionsEnabled", {
  87468. get: function () {
  87469. return this._interactionsEnabled;
  87470. },
  87471. /**
  87472. * If interactions are enabled with this gizmo. (eg. dragging/rotation)
  87473. */
  87474. set: function (value) {
  87475. this._interactionsEnabled = value;
  87476. this._onInteractionsEnabledChanged(value);
  87477. },
  87478. enumerable: true,
  87479. configurable: true
  87480. });
  87481. /**
  87482. * Disposes of the gizmo
  87483. */
  87484. Gizmo.prototype.dispose = function () {
  87485. this._rootMesh.dispose();
  87486. if (this._beforeRenderObserver) {
  87487. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  87488. }
  87489. };
  87490. return Gizmo;
  87491. }());
  87492. BABYLON.Gizmo = Gizmo;
  87493. })(BABYLON || (BABYLON = {}));
  87494. //# sourceMappingURL=babylon.gizmo.js.map
  87495. var BABYLON;
  87496. (function (BABYLON) {
  87497. /**
  87498. * Single axis drag gizmo
  87499. */
  87500. var AxisDragGizmo = /** @class */ (function (_super) {
  87501. __extends(AxisDragGizmo, _super);
  87502. /**
  87503. * Creates an AxisDragGizmo
  87504. * @param gizmoLayer The utility layer the gizmo will be added to
  87505. * @param dragAxis The axis which the gizmo will be able to drag on
  87506. * @param color The color of the gizmo
  87507. */
  87508. function AxisDragGizmo(gizmoLayer, dragAxis, color) {
  87509. var _this = _super.call(this, gizmoLayer) || this;
  87510. // Create Material
  87511. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87512. coloredMaterial.disableLighting = true;
  87513. coloredMaterial.emissiveColor = color;
  87514. // Build mesh on root node
  87515. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87516. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87517. _this._rootMesh.addChild(arrowMesh);
  87518. _this._rootMesh.addChild(arrowTail);
  87519. // Position arrow pointing in its drag axis
  87520. arrowMesh.scaling.scaleInPlace(0.1);
  87521. arrowMesh.material = coloredMaterial;
  87522. arrowMesh.rotation.x = Math.PI / 2;
  87523. arrowMesh.position.z += 0.3;
  87524. arrowTail.rotation.x = Math.PI / 2;
  87525. arrowTail.material = coloredMaterial;
  87526. arrowTail.position.z += 0.2;
  87527. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  87528. // Add drag behavior to handle events when the gizmo is dragged
  87529. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  87530. _this._dragBehavior.moveAttached = false;
  87531. _this._rootMesh.addBehavior(_this._dragBehavior);
  87532. _this._dragBehavior.onDragObservable.add(function (event) {
  87533. if (!_this.interactionsEnabled) {
  87534. return;
  87535. }
  87536. if (_this.attachedMesh) {
  87537. _this.attachedMesh.position.addInPlace(event.delta);
  87538. }
  87539. });
  87540. return _this;
  87541. }
  87542. AxisDragGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87543. this._dragBehavior.enabled = value;
  87544. };
  87545. /**
  87546. * Disposes of the gizmo
  87547. */
  87548. AxisDragGizmo.prototype.dispose = function () {
  87549. this._dragBehavior.detach();
  87550. _super.prototype.dispose.call(this);
  87551. };
  87552. return AxisDragGizmo;
  87553. }(BABYLON.Gizmo));
  87554. BABYLON.AxisDragGizmo = AxisDragGizmo;
  87555. })(BABYLON || (BABYLON = {}));
  87556. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  87557. var BABYLON;
  87558. (function (BABYLON) {
  87559. /**
  87560. * Single axis scale gizmo
  87561. */
  87562. var AxisScaleGizmo = /** @class */ (function (_super) {
  87563. __extends(AxisScaleGizmo, _super);
  87564. /**
  87565. * Creates an AxisScaleGizmo
  87566. * @param gizmoLayer The utility layer the gizmo will be added to
  87567. * @param dragAxis The axis which the gizmo will be able to scale on
  87568. * @param color The color of the gizmo
  87569. */
  87570. function AxisScaleGizmo(gizmoLayer, dragAxis, color) {
  87571. var _this = _super.call(this, gizmoLayer) || this;
  87572. // Create Material
  87573. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87574. coloredMaterial.disableLighting = true;
  87575. coloredMaterial.emissiveColor = color;
  87576. // Build mesh on root node
  87577. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 1 }, gizmoLayer.utilityLayerScene);
  87578. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87579. _this._rootMesh.addChild(arrowMesh);
  87580. _this._rootMesh.addChild(arrowTail);
  87581. // Position arrow pointing in its drag axis
  87582. arrowMesh.scaling.scaleInPlace(0.1);
  87583. arrowMesh.material = coloredMaterial;
  87584. arrowMesh.rotation.x = Math.PI / 2;
  87585. arrowMesh.position.z += 0.3;
  87586. arrowTail.rotation.x = Math.PI / 2;
  87587. arrowTail.material = coloredMaterial;
  87588. arrowTail.position.z += 0.2;
  87589. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  87590. // Add drag behavior to handle events when the gizmo is dragged
  87591. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  87592. _this._dragBehavior.moveAttached = false;
  87593. _this._rootMesh.addBehavior(_this._dragBehavior);
  87594. _this._dragBehavior.onDragObservable.add(function (event) {
  87595. if (!_this.interactionsEnabled) {
  87596. return;
  87597. }
  87598. if (_this.attachedMesh) {
  87599. _this.attachedMesh.scaling.addInPlace(event.delta);
  87600. }
  87601. });
  87602. return _this;
  87603. }
  87604. AxisScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87605. this._dragBehavior.enabled = value;
  87606. };
  87607. /**
  87608. * Disposes of the gizmo
  87609. */
  87610. AxisScaleGizmo.prototype.dispose = function () {
  87611. this._dragBehavior.detach();
  87612. _super.prototype.dispose.call(this);
  87613. };
  87614. return AxisScaleGizmo;
  87615. }(BABYLON.Gizmo));
  87616. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  87617. })(BABYLON || (BABYLON = {}));
  87618. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  87619. var BABYLON;
  87620. (function (BABYLON) {
  87621. /**
  87622. * Single plane rotation gizmo
  87623. */
  87624. var PlaneRotationGizmo = /** @class */ (function (_super) {
  87625. __extends(PlaneRotationGizmo, _super);
  87626. /**
  87627. * Creates a PlaneRotationGizmo
  87628. * @param gizmoLayer The utility layer the gizmo will be added to
  87629. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  87630. * @param color The color of the gizmo
  87631. */
  87632. function PlaneRotationGizmo(gizmoLayer, planeNormal, color) {
  87633. var _this = _super.call(this, gizmoLayer) || this;
  87634. // Create Material
  87635. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87636. coloredMaterial.disableLighting = true;
  87637. coloredMaterial.emissiveColor = color;
  87638. // Build mesh on root node
  87639. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.3, 20, gizmoLayer.utilityLayerScene, false);
  87640. _this._rootMesh.addChild(rotationMesh);
  87641. // Position arrow pointing in its drag axis
  87642. rotationMesh.scaling.scaleInPlace(0.1);
  87643. rotationMesh.material = coloredMaterial;
  87644. rotationMesh.rotation.x = Math.PI / 2;
  87645. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  87646. // Add drag behavior to handle events when the gizmo is dragged
  87647. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  87648. _this._dragBehavior.moveAttached = false;
  87649. _this._rootMesh.addBehavior(_this._dragBehavior);
  87650. var lastDragPosition = null;
  87651. _this._dragBehavior.onDragStartObservable.add(function (e) {
  87652. if (!_this.interactionsEnabled) {
  87653. return;
  87654. }
  87655. lastDragPosition = e.dragPlanePoint;
  87656. });
  87657. _this._dragBehavior.onDragObservable.add(function (event) {
  87658. if (!_this.interactionsEnabled) {
  87659. return;
  87660. }
  87661. if (_this.attachedMesh && lastDragPosition) {
  87662. if (!_this.attachedMesh.rotationQuaternion) {
  87663. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  87664. }
  87665. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  87666. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  87667. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  87668. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  87669. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  87670. var angle = Math.atan2(cross.length(), dot);
  87671. var up = planeNormal.clone();
  87672. // Flip up vector depending on which side the camera is on
  87673. if (gizmoLayer.utilityLayerScene.activeCamera) {
  87674. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  87675. if (BABYLON.Vector3.Dot(camVec, up) > 0) {
  87676. up.scaleInPlace(-1);
  87677. }
  87678. }
  87679. var halfCircleSide = BABYLON.Vector3.Dot(up, cross) > 0.0;
  87680. if (halfCircleSide)
  87681. angle = -angle;
  87682. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  87683. var quaternionCoefficient = Math.sin(angle / 2);
  87684. var amountToRotate = new BABYLON.Quaternion(up.x * quaternionCoefficient, up.y * quaternionCoefficient, up.z * quaternionCoefficient, Math.cos(angle / 2));
  87685. // Rotate selected mesh quaternion over fixed axis
  87686. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  87687. lastDragPosition = event.dragPlanePoint;
  87688. }
  87689. });
  87690. return _this;
  87691. }
  87692. PlaneRotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87693. this._dragBehavior.enabled = value;
  87694. };
  87695. /**
  87696. * Disposes of the gizmo
  87697. */
  87698. PlaneRotationGizmo.prototype.dispose = function () {
  87699. this._dragBehavior.detach();
  87700. _super.prototype.dispose.call(this);
  87701. };
  87702. return PlaneRotationGizmo;
  87703. }(BABYLON.Gizmo));
  87704. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  87705. })(BABYLON || (BABYLON = {}));
  87706. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  87707. var BABYLON;
  87708. (function (BABYLON) {
  87709. /**
  87710. * Gizmo that enables dragging a mesh along 3 axis
  87711. */
  87712. var PositionGizmo = /** @class */ (function (_super) {
  87713. __extends(PositionGizmo, _super);
  87714. /**
  87715. * Creates a PositionGizmo
  87716. * @param gizmoLayer The utility layer the gizmo will be added to
  87717. */
  87718. function PositionGizmo(gizmoLayer) {
  87719. var _this = _super.call(this, gizmoLayer) || this;
  87720. _this._xDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87721. _this._yDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87722. _this._zDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87723. return _this;
  87724. }
  87725. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  87726. set: function (mesh) {
  87727. this._xDrag.attachedMesh = mesh;
  87728. this._yDrag.attachedMesh = mesh;
  87729. this._zDrag.attachedMesh = mesh;
  87730. },
  87731. enumerable: true,
  87732. configurable: true
  87733. });
  87734. PositionGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87735. this._xDrag.interactionsEnabled = value;
  87736. this._yDrag.interactionsEnabled = value;
  87737. this._zDrag.interactionsEnabled = value;
  87738. };
  87739. /**
  87740. * Disposes of the gizmo
  87741. */
  87742. PositionGizmo.prototype.dispose = function () {
  87743. this._xDrag.dispose();
  87744. this._yDrag.dispose();
  87745. this._zDrag.dispose();
  87746. };
  87747. return PositionGizmo;
  87748. }(BABYLON.Gizmo));
  87749. BABYLON.PositionGizmo = PositionGizmo;
  87750. })(BABYLON || (BABYLON = {}));
  87751. //# sourceMappingURL=babylon.positionGizmo.js.map
  87752. var BABYLON;
  87753. (function (BABYLON) {
  87754. /**
  87755. * Gizmo that enables rotating a mesh along 3 axis
  87756. */
  87757. var RotationGizmo = /** @class */ (function (_super) {
  87758. __extends(RotationGizmo, _super);
  87759. /**
  87760. * Creates a RotationGizmo
  87761. * @param gizmoLayer The utility layer the gizmo will be added to
  87762. */
  87763. function RotationGizmo(gizmoLayer) {
  87764. var _this = _super.call(this, gizmoLayer) || this;
  87765. _this._xDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87766. _this._yDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87767. _this._zDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87768. return _this;
  87769. }
  87770. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  87771. set: function (mesh) {
  87772. this._xDrag.attachedMesh = mesh;
  87773. this._yDrag.attachedMesh = mesh;
  87774. this._zDrag.attachedMesh = mesh;
  87775. },
  87776. enumerable: true,
  87777. configurable: true
  87778. });
  87779. RotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87780. this._xDrag.interactionsEnabled = value;
  87781. this._yDrag.interactionsEnabled = value;
  87782. this._zDrag.interactionsEnabled = value;
  87783. };
  87784. /**
  87785. * Disposes of the gizmo
  87786. */
  87787. RotationGizmo.prototype.dispose = function () {
  87788. this._xDrag.dispose();
  87789. this._yDrag.dispose();
  87790. this._zDrag.dispose();
  87791. };
  87792. return RotationGizmo;
  87793. }(BABYLON.Gizmo));
  87794. BABYLON.RotationGizmo = RotationGizmo;
  87795. })(BABYLON || (BABYLON = {}));
  87796. //# sourceMappingURL=babylon.rotationGizmo.js.map
  87797. var BABYLON;
  87798. (function (BABYLON) {
  87799. /**
  87800. * Gizmo that enables scaling a mesh along 3 axis
  87801. */
  87802. var ScaleGizmo = /** @class */ (function (_super) {
  87803. __extends(ScaleGizmo, _super);
  87804. /**
  87805. * Creates a ScaleGizmo
  87806. * @param gizmoLayer The utility layer the gizmo will be added to
  87807. */
  87808. function ScaleGizmo(gizmoLayer) {
  87809. var _this = _super.call(this, gizmoLayer) || this;
  87810. _this._xDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87811. _this._yDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87812. _this._zDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87813. return _this;
  87814. }
  87815. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  87816. set: function (mesh) {
  87817. this._xDrag.attachedMesh = mesh;
  87818. this._yDrag.attachedMesh = mesh;
  87819. this._zDrag.attachedMesh = mesh;
  87820. },
  87821. enumerable: true,
  87822. configurable: true
  87823. });
  87824. ScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87825. this._xDrag.interactionsEnabled = value;
  87826. this._yDrag.interactionsEnabled = value;
  87827. this._zDrag.interactionsEnabled = value;
  87828. };
  87829. /**
  87830. * Disposes of the gizmo
  87831. */
  87832. ScaleGizmo.prototype.dispose = function () {
  87833. this._xDrag.dispose();
  87834. this._yDrag.dispose();
  87835. this._zDrag.dispose();
  87836. };
  87837. return ScaleGizmo;
  87838. }(BABYLON.Gizmo));
  87839. BABYLON.ScaleGizmo = ScaleGizmo;
  87840. })(BABYLON || (BABYLON = {}));
  87841. //# sourceMappingURL=babylon.scaleGizmo.js.map
  87842. var BABYLON;
  87843. (function (BABYLON) {
  87844. /**
  87845. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  87846. */
  87847. var GizmoManager = /** @class */ (function () {
  87848. /**
  87849. * Instatiates a gizmo manager
  87850. * @param scene the scene to overlay the gizmos on top of
  87851. * @param options If only a single gizmo should exist at one time
  87852. */
  87853. function GizmoManager(scene, options) {
  87854. var _this = this;
  87855. this.scene = scene;
  87856. // Set of gizmos that are currently in the scene for each mesh
  87857. this._gizmoSet = {};
  87858. this._pointerObserver = null;
  87859. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  87860. // Options parsing
  87861. if (!options) {
  87862. options = {};
  87863. }
  87864. if (options.singleGizmo === undefined) {
  87865. options.singleGizmo = true;
  87866. }
  87867. // Instatiate/dispose gizmos based on pointer actions
  87868. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  87869. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  87870. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  87871. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  87872. if (options.singleGizmo) {
  87873. _this._clearGizmos();
  87874. }
  87875. // Enable gizmo when mesh is selected
  87876. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  87877. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  87878. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  87879. }
  87880. else {
  87881. if (!options.singleGizmo) {
  87882. // Disable gizmo when clicked again
  87883. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  87884. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  87885. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  87886. }
  87887. }
  87888. }
  87889. else {
  87890. if (options.singleGizmo) {
  87891. // Disable gizmo when clicked away
  87892. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  87893. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  87894. if (gizmoPick && !gizmoPick.hit) {
  87895. _this._clearGizmos();
  87896. }
  87897. }
  87898. }
  87899. }
  87900. }
  87901. });
  87902. }
  87903. /**
  87904. * Disposes of the gizmo manager
  87905. */
  87906. GizmoManager.prototype.dispose = function () {
  87907. this.scene.onPointerObservable.remove(this._pointerObserver);
  87908. this._clearGizmos();
  87909. this._gizmoLayer.dispose();
  87910. };
  87911. GizmoManager.prototype._clearGizmos = function () {
  87912. for (var key in this._gizmoSet) {
  87913. if (this._gizmoSet.hasOwnProperty(key)) {
  87914. this._gizmoSet[key].positionGizmo.dispose();
  87915. this._gizmoSet[key].rotationGizmo.dispose();
  87916. delete this._gizmoSet[key];
  87917. }
  87918. }
  87919. };
  87920. return GizmoManager;
  87921. }());
  87922. BABYLON.GizmoManager = GizmoManager;
  87923. })(BABYLON || (BABYLON = {}));
  87924. //# sourceMappingURL=babylon.gizmoManager.js.map
  87925. var BABYLON;
  87926. (function (BABYLON) {
  87927. /**
  87928. * Defines a target to use with MorphTargetManager
  87929. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  87930. */
  87931. var MorphTarget = /** @class */ (function () {
  87932. /**
  87933. * Creates a new MorphTarget
  87934. * @param name defines the name of the target
  87935. * @param influence defines the influence to use
  87936. */
  87937. function MorphTarget(
  87938. /** defines the name of the target */
  87939. name, influence, scene) {
  87940. if (influence === void 0) { influence = 0; }
  87941. if (scene === void 0) { scene = null; }
  87942. this.name = name;
  87943. /**
  87944. * Gets or sets the list of animations
  87945. */
  87946. this.animations = new Array();
  87947. this._positions = null;
  87948. this._normals = null;
  87949. this._tangents = null;
  87950. /**
  87951. * Observable raised when the influence changes
  87952. */
  87953. this.onInfluenceChanged = new BABYLON.Observable();
  87954. this._animationPropertiesOverride = null;
  87955. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87956. this.influence = influence;
  87957. }
  87958. Object.defineProperty(MorphTarget.prototype, "influence", {
  87959. /**
  87960. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  87961. */
  87962. get: function () {
  87963. return this._influence;
  87964. },
  87965. set: function (influence) {
  87966. if (this._influence === influence) {
  87967. return;
  87968. }
  87969. var previous = this._influence;
  87970. this._influence = influence;
  87971. if (this.onInfluenceChanged.hasObservers) {
  87972. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  87973. }
  87974. },
  87975. enumerable: true,
  87976. configurable: true
  87977. });
  87978. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  87979. /**
  87980. * Gets or sets the animation properties override
  87981. */
  87982. get: function () {
  87983. if (!this._animationPropertiesOverride && this._scene) {
  87984. return this._scene.animationPropertiesOverride;
  87985. }
  87986. return this._animationPropertiesOverride;
  87987. },
  87988. set: function (value) {
  87989. this._animationPropertiesOverride = value;
  87990. },
  87991. enumerable: true,
  87992. configurable: true
  87993. });
  87994. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  87995. /**
  87996. * Gets a boolean defining if the target contains position data
  87997. */
  87998. get: function () {
  87999. return !!this._positions;
  88000. },
  88001. enumerable: true,
  88002. configurable: true
  88003. });
  88004. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  88005. /**
  88006. * Gets a boolean defining if the target contains normal data
  88007. */
  88008. get: function () {
  88009. return !!this._normals;
  88010. },
  88011. enumerable: true,
  88012. configurable: true
  88013. });
  88014. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  88015. /**
  88016. * Gets a boolean defining if the target contains tangent data
  88017. */
  88018. get: function () {
  88019. return !!this._tangents;
  88020. },
  88021. enumerable: true,
  88022. configurable: true
  88023. });
  88024. /**
  88025. * Affects position data to this target
  88026. * @param data defines the position data to use
  88027. */
  88028. MorphTarget.prototype.setPositions = function (data) {
  88029. this._positions = data;
  88030. };
  88031. /**
  88032. * Gets the position data stored in this target
  88033. * @returns a FloatArray containing the position data (or null if not present)
  88034. */
  88035. MorphTarget.prototype.getPositions = function () {
  88036. return this._positions;
  88037. };
  88038. /**
  88039. * Affects normal data to this target
  88040. * @param data defines the normal data to use
  88041. */
  88042. MorphTarget.prototype.setNormals = function (data) {
  88043. this._normals = data;
  88044. };
  88045. /**
  88046. * Gets the normal data stored in this target
  88047. * @returns a FloatArray containing the normal data (or null if not present)
  88048. */
  88049. MorphTarget.prototype.getNormals = function () {
  88050. return this._normals;
  88051. };
  88052. /**
  88053. * Affects tangent data to this target
  88054. * @param data defines the tangent data to use
  88055. */
  88056. MorphTarget.prototype.setTangents = function (data) {
  88057. this._tangents = data;
  88058. };
  88059. /**
  88060. * Gets the tangent data stored in this target
  88061. * @returns a FloatArray containing the tangent data (or null if not present)
  88062. */
  88063. MorphTarget.prototype.getTangents = function () {
  88064. return this._tangents;
  88065. };
  88066. /**
  88067. * Serializes the current target into a Serialization object
  88068. * @returns the serialized object
  88069. */
  88070. MorphTarget.prototype.serialize = function () {
  88071. var serializationObject = {};
  88072. serializationObject.name = this.name;
  88073. serializationObject.influence = this.influence;
  88074. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  88075. if (this.hasNormals) {
  88076. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  88077. }
  88078. if (this.hasTangents) {
  88079. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  88080. }
  88081. // Animations
  88082. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  88083. return serializationObject;
  88084. };
  88085. // Statics
  88086. /**
  88087. * Creates a new target from serialized data
  88088. * @param serializationObject defines the serialized data to use
  88089. * @returns a new MorphTarget
  88090. */
  88091. MorphTarget.Parse = function (serializationObject) {
  88092. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  88093. result.setPositions(serializationObject.positions);
  88094. if (serializationObject.normals) {
  88095. result.setNormals(serializationObject.normals);
  88096. }
  88097. if (serializationObject.tangents) {
  88098. result.setTangents(serializationObject.tangents);
  88099. }
  88100. // Animations
  88101. if (serializationObject.animations) {
  88102. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  88103. var parsedAnimation = serializationObject.animations[animationIndex];
  88104. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  88105. }
  88106. }
  88107. return result;
  88108. };
  88109. /**
  88110. * Creates a MorphTarget from mesh data
  88111. * @param mesh defines the source mesh
  88112. * @param name defines the name to use for the new target
  88113. * @param influence defines the influence to attach to the target
  88114. * @returns a new MorphTarget
  88115. */
  88116. MorphTarget.FromMesh = function (mesh, name, influence) {
  88117. if (!name) {
  88118. name = mesh.name;
  88119. }
  88120. var result = new MorphTarget(name, influence, mesh.getScene());
  88121. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  88122. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  88123. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  88124. }
  88125. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  88126. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  88127. }
  88128. return result;
  88129. };
  88130. return MorphTarget;
  88131. }());
  88132. BABYLON.MorphTarget = MorphTarget;
  88133. })(BABYLON || (BABYLON = {}));
  88134. //# sourceMappingURL=babylon.morphTarget.js.map
  88135. var BABYLON;
  88136. (function (BABYLON) {
  88137. /**
  88138. * This class is used to deform meshes using morphing between different targets
  88139. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  88140. */
  88141. var MorphTargetManager = /** @class */ (function () {
  88142. /**
  88143. * Creates a new MorphTargetManager
  88144. * @param scene defines the current scene
  88145. */
  88146. function MorphTargetManager(scene) {
  88147. if (scene === void 0) { scene = null; }
  88148. this._targets = new Array();
  88149. this._targetObservable = new Array();
  88150. this._activeTargets = new BABYLON.SmartArray(16);
  88151. this._supportsNormals = false;
  88152. this._supportsTangents = false;
  88153. this._vertexCount = 0;
  88154. this._uniqueId = 0;
  88155. this._tempInfluences = new Array();
  88156. if (!scene) {
  88157. scene = BABYLON.Engine.LastCreatedScene;
  88158. }
  88159. this._scene = scene;
  88160. if (this._scene) {
  88161. this._scene.morphTargetManagers.push(this);
  88162. this._uniqueId = this._scene.getUniqueId();
  88163. }
  88164. }
  88165. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  88166. /**
  88167. * Gets the unique ID of this manager
  88168. */
  88169. get: function () {
  88170. return this._uniqueId;
  88171. },
  88172. enumerable: true,
  88173. configurable: true
  88174. });
  88175. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  88176. /**
  88177. * Gets the number of vertices handled by this manager
  88178. */
  88179. get: function () {
  88180. return this._vertexCount;
  88181. },
  88182. enumerable: true,
  88183. configurable: true
  88184. });
  88185. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  88186. /**
  88187. * Gets a boolean indicating if this manager supports morphing of normals
  88188. */
  88189. get: function () {
  88190. return this._supportsNormals;
  88191. },
  88192. enumerable: true,
  88193. configurable: true
  88194. });
  88195. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  88196. /**
  88197. * Gets a boolean indicating if this manager supports morphing of tangents
  88198. */
  88199. get: function () {
  88200. return this._supportsTangents;
  88201. },
  88202. enumerable: true,
  88203. configurable: true
  88204. });
  88205. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  88206. /**
  88207. * Gets the number of targets stored in this manager
  88208. */
  88209. get: function () {
  88210. return this._targets.length;
  88211. },
  88212. enumerable: true,
  88213. configurable: true
  88214. });
  88215. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  88216. /**
  88217. * Gets the number of influencers (ie. the number of targets with influences > 0)
  88218. */
  88219. get: function () {
  88220. return this._activeTargets.length;
  88221. },
  88222. enumerable: true,
  88223. configurable: true
  88224. });
  88225. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  88226. /**
  88227. * Gets the list of influences (one per target)
  88228. */
  88229. get: function () {
  88230. return this._influences;
  88231. },
  88232. enumerable: true,
  88233. configurable: true
  88234. });
  88235. /**
  88236. * Gets the active target at specified index. An active target is a target with an influence > 0
  88237. * @param index defines the index to check
  88238. * @returns the requested target
  88239. */
  88240. MorphTargetManager.prototype.getActiveTarget = function (index) {
  88241. return this._activeTargets.data[index];
  88242. };
  88243. /**
  88244. * Gets the target at specified index
  88245. * @param index defines the index to check
  88246. * @returns the requested target
  88247. */
  88248. MorphTargetManager.prototype.getTarget = function (index) {
  88249. return this._targets[index];
  88250. };
  88251. /**
  88252. * Add a new target to this manager
  88253. * @param target defines the target to add
  88254. */
  88255. MorphTargetManager.prototype.addTarget = function (target) {
  88256. var _this = this;
  88257. this._targets.push(target);
  88258. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  88259. _this._syncActiveTargets(needUpdate);
  88260. }));
  88261. this._syncActiveTargets(true);
  88262. };
  88263. /**
  88264. * Removes a target from the manager
  88265. * @param target defines the target to remove
  88266. */
  88267. MorphTargetManager.prototype.removeTarget = function (target) {
  88268. var index = this._targets.indexOf(target);
  88269. if (index >= 0) {
  88270. this._targets.splice(index, 1);
  88271. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  88272. this._syncActiveTargets(true);
  88273. }
  88274. };
  88275. /**
  88276. * Serializes the current manager into a Serialization object
  88277. * @returns the serialized object
  88278. */
  88279. MorphTargetManager.prototype.serialize = function () {
  88280. var serializationObject = {};
  88281. serializationObject.id = this.uniqueId;
  88282. serializationObject.targets = [];
  88283. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  88284. var target = _a[_i];
  88285. serializationObject.targets.push(target.serialize());
  88286. }
  88287. return serializationObject;
  88288. };
  88289. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  88290. var influenceCount = 0;
  88291. this._activeTargets.reset();
  88292. this._supportsNormals = true;
  88293. this._supportsTangents = true;
  88294. this._vertexCount = 0;
  88295. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  88296. var target = _a[_i];
  88297. this._activeTargets.push(target);
  88298. this._tempInfluences[influenceCount++] = target.influence;
  88299. var positions = target.getPositions();
  88300. if (positions) {
  88301. this._supportsNormals = this._supportsNormals && target.hasNormals;
  88302. this._supportsTangents = this._supportsTangents && target.hasTangents;
  88303. var vertexCount = positions.length / 3;
  88304. if (this._vertexCount === 0) {
  88305. this._vertexCount = vertexCount;
  88306. }
  88307. else if (this._vertexCount !== vertexCount) {
  88308. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  88309. return;
  88310. }
  88311. }
  88312. }
  88313. if (!this._influences || this._influences.length !== influenceCount) {
  88314. this._influences = new Float32Array(influenceCount);
  88315. }
  88316. for (var index = 0; index < influenceCount; index++) {
  88317. this._influences[index] = this._tempInfluences[index];
  88318. }
  88319. if (needUpdate) {
  88320. this.synchronize();
  88321. }
  88322. };
  88323. /**
  88324. * Syncrhonize the targets with all the meshes using this morph target manager
  88325. */
  88326. MorphTargetManager.prototype.synchronize = function () {
  88327. if (!this._scene) {
  88328. return;
  88329. }
  88330. // Flag meshes as dirty to resync with the active targets
  88331. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  88332. var mesh = _a[_i];
  88333. if (mesh.morphTargetManager === this) {
  88334. mesh._syncGeometryWithMorphTargetManager();
  88335. }
  88336. }
  88337. };
  88338. // Statics
  88339. /**
  88340. * Creates a new MorphTargetManager from serialized data
  88341. * @param serializationObject defines the serialized data
  88342. * @param scene defines the hosting scene
  88343. * @returns the new MorphTargetManager
  88344. */
  88345. MorphTargetManager.Parse = function (serializationObject, scene) {
  88346. var result = new MorphTargetManager(scene);
  88347. result._uniqueId = serializationObject.id;
  88348. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  88349. var targetData = _a[_i];
  88350. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  88351. }
  88352. return result;
  88353. };
  88354. return MorphTargetManager;
  88355. }());
  88356. BABYLON.MorphTargetManager = MorphTargetManager;
  88357. })(BABYLON || (BABYLON = {}));
  88358. //# sourceMappingURL=babylon.morphTargetManager.js.map
  88359. var BABYLON;
  88360. (function (BABYLON) {
  88361. var Octree = /** @class */ (function () {
  88362. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  88363. if (maxDepth === void 0) { maxDepth = 2; }
  88364. this.maxDepth = maxDepth;
  88365. this.dynamicContent = new Array();
  88366. this._maxBlockCapacity = maxBlockCapacity || 64;
  88367. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  88368. this._creationFunc = creationFunc;
  88369. }
  88370. // Methods
  88371. Octree.prototype.update = function (worldMin, worldMax, entries) {
  88372. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  88373. };
  88374. Octree.prototype.addMesh = function (entry) {
  88375. for (var index = 0; index < this.blocks.length; index++) {
  88376. var block = this.blocks[index];
  88377. block.addEntry(entry);
  88378. }
  88379. };
  88380. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  88381. this._selectionContent.reset();
  88382. for (var index = 0; index < this.blocks.length; index++) {
  88383. var block = this.blocks[index];
  88384. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  88385. }
  88386. if (allowDuplicate) {
  88387. this._selectionContent.concat(this.dynamicContent);
  88388. }
  88389. else {
  88390. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88391. }
  88392. return this._selectionContent;
  88393. };
  88394. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  88395. this._selectionContent.reset();
  88396. for (var index = 0; index < this.blocks.length; index++) {
  88397. var block = this.blocks[index];
  88398. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  88399. }
  88400. if (allowDuplicate) {
  88401. this._selectionContent.concat(this.dynamicContent);
  88402. }
  88403. else {
  88404. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88405. }
  88406. return this._selectionContent;
  88407. };
  88408. Octree.prototype.intersectsRay = function (ray) {
  88409. this._selectionContent.reset();
  88410. for (var index = 0; index < this.blocks.length; index++) {
  88411. var block = this.blocks[index];
  88412. block.intersectsRay(ray, this._selectionContent);
  88413. }
  88414. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88415. return this._selectionContent;
  88416. };
  88417. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  88418. target.blocks = new Array();
  88419. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  88420. // Segmenting space
  88421. for (var x = 0; x < 2; x++) {
  88422. for (var y = 0; y < 2; y++) {
  88423. for (var z = 0; z < 2; z++) {
  88424. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  88425. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  88426. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  88427. block.addEntries(entries);
  88428. target.blocks.push(block);
  88429. }
  88430. }
  88431. }
  88432. };
  88433. Octree.CreationFuncForMeshes = function (entry, block) {
  88434. var boundingInfo = entry.getBoundingInfo();
  88435. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  88436. block.entries.push(entry);
  88437. }
  88438. };
  88439. Octree.CreationFuncForSubMeshes = function (entry, block) {
  88440. var boundingInfo = entry.getBoundingInfo();
  88441. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  88442. block.entries.push(entry);
  88443. }
  88444. };
  88445. return Octree;
  88446. }());
  88447. BABYLON.Octree = Octree;
  88448. })(BABYLON || (BABYLON = {}));
  88449. //# sourceMappingURL=babylon.octree.js.map
  88450. var BABYLON;
  88451. (function (BABYLON) {
  88452. var OctreeBlock = /** @class */ (function () {
  88453. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  88454. this.entries = new Array();
  88455. this._boundingVectors = new Array();
  88456. this._capacity = capacity;
  88457. this._depth = depth;
  88458. this._maxDepth = maxDepth;
  88459. this._creationFunc = creationFunc;
  88460. this._minPoint = minPoint;
  88461. this._maxPoint = maxPoint;
  88462. this._boundingVectors.push(minPoint.clone());
  88463. this._boundingVectors.push(maxPoint.clone());
  88464. this._boundingVectors.push(minPoint.clone());
  88465. this._boundingVectors[2].x = maxPoint.x;
  88466. this._boundingVectors.push(minPoint.clone());
  88467. this._boundingVectors[3].y = maxPoint.y;
  88468. this._boundingVectors.push(minPoint.clone());
  88469. this._boundingVectors[4].z = maxPoint.z;
  88470. this._boundingVectors.push(maxPoint.clone());
  88471. this._boundingVectors[5].z = minPoint.z;
  88472. this._boundingVectors.push(maxPoint.clone());
  88473. this._boundingVectors[6].x = minPoint.x;
  88474. this._boundingVectors.push(maxPoint.clone());
  88475. this._boundingVectors[7].y = minPoint.y;
  88476. }
  88477. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  88478. // Property
  88479. get: function () {
  88480. return this._capacity;
  88481. },
  88482. enumerable: true,
  88483. configurable: true
  88484. });
  88485. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  88486. get: function () {
  88487. return this._minPoint;
  88488. },
  88489. enumerable: true,
  88490. configurable: true
  88491. });
  88492. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  88493. get: function () {
  88494. return this._maxPoint;
  88495. },
  88496. enumerable: true,
  88497. configurable: true
  88498. });
  88499. // Methods
  88500. OctreeBlock.prototype.addEntry = function (entry) {
  88501. if (this.blocks) {
  88502. for (var index = 0; index < this.blocks.length; index++) {
  88503. var block = this.blocks[index];
  88504. block.addEntry(entry);
  88505. }
  88506. return;
  88507. }
  88508. this._creationFunc(entry, this);
  88509. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  88510. this.createInnerBlocks();
  88511. }
  88512. };
  88513. OctreeBlock.prototype.addEntries = function (entries) {
  88514. for (var index = 0; index < entries.length; index++) {
  88515. var mesh = entries[index];
  88516. this.addEntry(mesh);
  88517. }
  88518. };
  88519. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  88520. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  88521. if (this.blocks) {
  88522. for (var index = 0; index < this.blocks.length; index++) {
  88523. var block = this.blocks[index];
  88524. block.select(frustumPlanes, selection, allowDuplicate);
  88525. }
  88526. return;
  88527. }
  88528. if (allowDuplicate) {
  88529. selection.concat(this.entries);
  88530. }
  88531. else {
  88532. selection.concatWithNoDuplicate(this.entries);
  88533. }
  88534. }
  88535. };
  88536. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  88537. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  88538. if (this.blocks) {
  88539. for (var index = 0; index < this.blocks.length; index++) {
  88540. var block = this.blocks[index];
  88541. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  88542. }
  88543. return;
  88544. }
  88545. if (allowDuplicate) {
  88546. selection.concat(this.entries);
  88547. }
  88548. else {
  88549. selection.concatWithNoDuplicate(this.entries);
  88550. }
  88551. }
  88552. };
  88553. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  88554. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  88555. if (this.blocks) {
  88556. for (var index = 0; index < this.blocks.length; index++) {
  88557. var block = this.blocks[index];
  88558. block.intersectsRay(ray, selection);
  88559. }
  88560. return;
  88561. }
  88562. selection.concatWithNoDuplicate(this.entries);
  88563. }
  88564. };
  88565. OctreeBlock.prototype.createInnerBlocks = function () {
  88566. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  88567. };
  88568. return OctreeBlock;
  88569. }());
  88570. BABYLON.OctreeBlock = OctreeBlock;
  88571. })(BABYLON || (BABYLON = {}));
  88572. //# sourceMappingURL=babylon.octreeBlock.js.map
  88573. var BABYLON;
  88574. (function (BABYLON) {
  88575. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  88576. __extends(VRDistortionCorrectionPostProcess, _super);
  88577. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  88578. var _this = _super.call(this, name, "vrDistortionCorrection", [
  88579. 'LensCenter',
  88580. 'Scale',
  88581. 'ScaleIn',
  88582. 'HmdWarpParam'
  88583. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  88584. _this._isRightEye = isRightEye;
  88585. _this._distortionFactors = vrMetrics.distortionK;
  88586. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  88587. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  88588. _this.adaptScaleToCurrentViewport = true;
  88589. _this.onSizeChangedObservable.add(function () {
  88590. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  88591. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  88592. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  88593. });
  88594. _this.onApplyObservable.add(function (effect) {
  88595. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  88596. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  88597. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  88598. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  88599. });
  88600. return _this;
  88601. }
  88602. return VRDistortionCorrectionPostProcess;
  88603. }(BABYLON.PostProcess));
  88604. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  88605. })(BABYLON || (BABYLON = {}));
  88606. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  88607. var BABYLON;
  88608. (function (BABYLON) {
  88609. /**
  88610. * Postprocess used to generate anaglyphic rendering
  88611. */
  88612. var AnaglyphPostProcess = /** @class */ (function (_super) {
  88613. __extends(AnaglyphPostProcess, _super);
  88614. /**
  88615. * Creates a new AnaglyphPostProcess
  88616. * @param name defines postprocess name
  88617. * @param options defines creation options or target ratio scale
  88618. * @param rigCameras defines cameras using this postprocess
  88619. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  88620. * @param engine defines hosting engine
  88621. * @param reusable defines if the postprocess will be reused multiple times per frame
  88622. */
  88623. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  88624. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  88625. _this._passedProcess = rigCameras[0]._rigPostProcess;
  88626. _this.onApplyObservable.add(function (effect) {
  88627. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  88628. });
  88629. return _this;
  88630. }
  88631. return AnaglyphPostProcess;
  88632. }(BABYLON.PostProcess));
  88633. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  88634. })(BABYLON || (BABYLON = {}));
  88635. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  88636. var BABYLON;
  88637. (function (BABYLON) {
  88638. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  88639. __extends(StereoscopicInterlacePostProcess, _super);
  88640. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  88641. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  88642. _this._passedProcess = rigCameras[0]._rigPostProcess;
  88643. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  88644. _this.onSizeChangedObservable.add(function () {
  88645. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  88646. });
  88647. _this.onApplyObservable.add(function (effect) {
  88648. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  88649. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  88650. });
  88651. return _this;
  88652. }
  88653. return StereoscopicInterlacePostProcess;
  88654. }(BABYLON.PostProcess));
  88655. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  88656. })(BABYLON || (BABYLON = {}));
  88657. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  88658. var BABYLON;
  88659. (function (BABYLON) {
  88660. /**
  88661. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  88662. * Screen rotation is taken into account.
  88663. */
  88664. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  88665. function FreeCameraDeviceOrientationInput() {
  88666. var _this = this;
  88667. this._screenOrientationAngle = 0;
  88668. this._screenQuaternion = new BABYLON.Quaternion();
  88669. this._alpha = 0;
  88670. this._beta = 0;
  88671. this._gamma = 0;
  88672. this._orientationChanged = function () {
  88673. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  88674. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  88675. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  88676. };
  88677. this._deviceOrientation = function (evt) {
  88678. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  88679. _this._beta = evt.beta !== null ? evt.beta : 0;
  88680. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  88681. };
  88682. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  88683. this._orientationChanged();
  88684. }
  88685. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  88686. get: function () {
  88687. return this._camera;
  88688. },
  88689. set: function (camera) {
  88690. this._camera = camera;
  88691. if (this._camera != null && !this._camera.rotationQuaternion) {
  88692. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  88693. }
  88694. },
  88695. enumerable: true,
  88696. configurable: true
  88697. });
  88698. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  88699. window.addEventListener("orientationchange", this._orientationChanged);
  88700. window.addEventListener("deviceorientation", this._deviceOrientation);
  88701. //In certain cases, the attach control is called AFTER orientation was changed,
  88702. //So this is needed.
  88703. this._orientationChanged();
  88704. };
  88705. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  88706. window.removeEventListener("orientationchange", this._orientationChanged);
  88707. window.removeEventListener("deviceorientation", this._deviceOrientation);
  88708. };
  88709. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  88710. //if no device orientation provided, don't update the rotation.
  88711. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  88712. if (!this._alpha)
  88713. return;
  88714. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  88715. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  88716. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  88717. //Mirror on XY Plane
  88718. this._camera.rotationQuaternion.z *= -1;
  88719. this._camera.rotationQuaternion.w *= -1;
  88720. };
  88721. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  88722. return "FreeCameraDeviceOrientationInput";
  88723. };
  88724. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  88725. return "deviceOrientation";
  88726. };
  88727. return FreeCameraDeviceOrientationInput;
  88728. }());
  88729. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  88730. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  88731. })(BABYLON || (BABYLON = {}));
  88732. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  88733. var BABYLON;
  88734. (function (BABYLON) {
  88735. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  88736. function ArcRotateCameraVRDeviceOrientationInput() {
  88737. this.alphaCorrection = 1;
  88738. this.betaCorrection = 1;
  88739. this.gammaCorrection = 1;
  88740. this._alpha = 0;
  88741. this._gamma = 0;
  88742. this._dirty = false;
  88743. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  88744. }
  88745. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  88746. this.camera.attachControl(element, noPreventDefault);
  88747. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  88748. };
  88749. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  88750. if (evt.alpha !== null) {
  88751. this._alpha = +evt.alpha | 0;
  88752. }
  88753. if (evt.gamma !== null) {
  88754. this._gamma = +evt.gamma | 0;
  88755. }
  88756. this._dirty = true;
  88757. };
  88758. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  88759. if (this._dirty) {
  88760. this._dirty = false;
  88761. if (this._gamma < 0) {
  88762. this._gamma = 180 + this._gamma;
  88763. }
  88764. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  88765. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  88766. }
  88767. };
  88768. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  88769. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  88770. };
  88771. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  88772. return "ArcRotateCameraVRDeviceOrientationInput";
  88773. };
  88774. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  88775. return "VRDeviceOrientation";
  88776. };
  88777. return ArcRotateCameraVRDeviceOrientationInput;
  88778. }());
  88779. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  88780. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  88781. })(BABYLON || (BABYLON = {}));
  88782. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  88783. var BABYLON;
  88784. (function (BABYLON) {
  88785. var VRCameraMetrics = /** @class */ (function () {
  88786. function VRCameraMetrics() {
  88787. this.compensateDistortion = true;
  88788. }
  88789. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  88790. get: function () {
  88791. return this.hResolution / (2 * this.vResolution);
  88792. },
  88793. enumerable: true,
  88794. configurable: true
  88795. });
  88796. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  88797. get: function () {
  88798. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  88799. },
  88800. enumerable: true,
  88801. configurable: true
  88802. });
  88803. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  88804. get: function () {
  88805. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  88806. var h = (4 * meters) / this.hScreenSize;
  88807. return BABYLON.Matrix.Translation(h, 0, 0);
  88808. },
  88809. enumerable: true,
  88810. configurable: true
  88811. });
  88812. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  88813. get: function () {
  88814. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  88815. var h = (4 * meters) / this.hScreenSize;
  88816. return BABYLON.Matrix.Translation(-h, 0, 0);
  88817. },
  88818. enumerable: true,
  88819. configurable: true
  88820. });
  88821. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  88822. get: function () {
  88823. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  88824. },
  88825. enumerable: true,
  88826. configurable: true
  88827. });
  88828. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  88829. get: function () {
  88830. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  88831. },
  88832. enumerable: true,
  88833. configurable: true
  88834. });
  88835. VRCameraMetrics.GetDefault = function () {
  88836. var result = new VRCameraMetrics();
  88837. result.hResolution = 1280;
  88838. result.vResolution = 800;
  88839. result.hScreenSize = 0.149759993;
  88840. result.vScreenSize = 0.0935999975;
  88841. result.vScreenCenter = 0.0467999987;
  88842. result.eyeToScreenDistance = 0.0410000011;
  88843. result.lensSeparationDistance = 0.0635000020;
  88844. result.interpupillaryDistance = 0.0640000030;
  88845. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  88846. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  88847. result.postProcessScaleFactor = 1.714605507808412;
  88848. result.lensCenterOffset = 0.151976421;
  88849. return result;
  88850. };
  88851. return VRCameraMetrics;
  88852. }());
  88853. BABYLON.VRCameraMetrics = VRCameraMetrics;
  88854. })(BABYLON || (BABYLON = {}));
  88855. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  88856. var BABYLON;
  88857. (function (BABYLON) {
  88858. /**
  88859. * This represents a WebVR camera.
  88860. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  88861. * @example http://doc.babylonjs.com/how_to/webvr_camera
  88862. */
  88863. var WebVRFreeCamera = /** @class */ (function (_super) {
  88864. __extends(WebVRFreeCamera, _super);
  88865. /**
  88866. * Instantiates a WebVRFreeCamera.
  88867. * @param name The name of the WebVRFreeCamera
  88868. * @param position The starting anchor position for the camera
  88869. * @param scene The scene the camera belongs to
  88870. * @param webVROptions a set of customizable options for the webVRCamera
  88871. */
  88872. function WebVRFreeCamera(name, position, scene, webVROptions) {
  88873. if (webVROptions === void 0) { webVROptions = {}; }
  88874. var _this = _super.call(this, name, position, scene) || this;
  88875. _this.webVROptions = webVROptions;
  88876. /**
  88877. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  88878. */
  88879. _this._vrDevice = null;
  88880. /**
  88881. * The rawPose of the vrDevice.
  88882. */
  88883. _this.rawPose = null;
  88884. _this._specsVersion = "1.1";
  88885. _this._attached = false;
  88886. _this._descendants = [];
  88887. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  88888. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  88889. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  88890. _this._standingMatrix = null;
  88891. /**
  88892. * Represents device position in babylon space.
  88893. */
  88894. _this.devicePosition = BABYLON.Vector3.Zero();
  88895. /**
  88896. * Represents device rotation in babylon space.
  88897. */
  88898. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  88899. /**
  88900. * The scale of the device to be used when translating from device space to babylon space.
  88901. */
  88902. _this.deviceScaleFactor = 1;
  88903. _this._deviceToWorld = BABYLON.Matrix.Identity();
  88904. _this._worldToDevice = BABYLON.Matrix.Identity();
  88905. /**
  88906. * References to the webVR controllers for the vrDevice.
  88907. */
  88908. _this.controllers = [];
  88909. /**
  88910. * Emits an event when a controller is attached.
  88911. */
  88912. _this.onControllersAttachedObservable = new BABYLON.Observable();
  88913. /**
  88914. * Emits an event when a controller's mesh has been loaded;
  88915. */
  88916. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  88917. /**
  88918. * If the rig cameras be used as parent instead of this camera.
  88919. */
  88920. _this.rigParenting = true;
  88921. _this._defaultHeight = undefined;
  88922. _this._workingVector = BABYLON.Vector3.Zero();
  88923. _this._oneVector = BABYLON.Vector3.One();
  88924. _this._workingMatrix = BABYLON.Matrix.Identity();
  88925. _this._cache.position = BABYLON.Vector3.Zero();
  88926. if (webVROptions.defaultHeight) {
  88927. _this._defaultHeight = webVROptions.defaultHeight;
  88928. _this.position.y = _this._defaultHeight;
  88929. }
  88930. _this.minZ = 0.1;
  88931. //legacy support - the compensation boolean was removed.
  88932. if (arguments.length === 5) {
  88933. _this.webVROptions = arguments[4];
  88934. }
  88935. // default webVR options
  88936. if (_this.webVROptions.trackPosition == undefined) {
  88937. _this.webVROptions.trackPosition = true;
  88938. }
  88939. if (_this.webVROptions.controllerMeshes == undefined) {
  88940. _this.webVROptions.controllerMeshes = true;
  88941. }
  88942. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  88943. _this.webVROptions.defaultLightingOnControllers = true;
  88944. }
  88945. _this.rotationQuaternion = new BABYLON.Quaternion();
  88946. if (_this.webVROptions && _this.webVROptions.positionScale) {
  88947. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  88948. }
  88949. //enable VR
  88950. var engine = _this.getEngine();
  88951. _this._onVREnabled = function (success) { if (success) {
  88952. _this.initControllers();
  88953. } };
  88954. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  88955. engine.initWebVR().add(function (event) {
  88956. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  88957. return;
  88958. }
  88959. _this._vrDevice = event.vrDisplay;
  88960. //reset the rig parameters.
  88961. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  88962. if (_this._attached) {
  88963. _this.getEngine().enableVR();
  88964. }
  88965. });
  88966. if (typeof (VRFrameData) !== "undefined")
  88967. _this._frameData = new VRFrameData();
  88968. /**
  88969. * The idea behind the following lines:
  88970. * objects that have the camera as parent should actually have the rig cameras as a parent.
  88971. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  88972. * the second will not show it correctly.
  88973. *
  88974. * To solve this - each object that has the camera as parent will be added to a protected array.
  88975. * When the rig camera renders, it will take this array and set all of those to be its children.
  88976. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  88977. * Amazing!
  88978. */
  88979. scene.onBeforeCameraRenderObservable.add(function (camera) {
  88980. if (camera.parent === _this && _this.rigParenting) {
  88981. _this._descendants = _this.getDescendants(true, function (n) {
  88982. // don't take the cameras or the controllers!
  88983. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  88984. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  88985. return !isController && !isRigCamera;
  88986. });
  88987. _this._descendants.forEach(function (node) {
  88988. node.parent = camera;
  88989. });
  88990. }
  88991. });
  88992. scene.onAfterCameraRenderObservable.add(function (camera) {
  88993. if (camera.parent === _this && _this.rigParenting) {
  88994. _this._descendants.forEach(function (node) {
  88995. node.parent = _this;
  88996. });
  88997. }
  88998. });
  88999. return _this;
  89000. }
  89001. /**
  89002. * Gets the device distance from the ground in meters.
  89003. * @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.
  89004. */
  89005. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  89006. if (this._standingMatrix) {
  89007. // Add standing matrix offset to get real offset from ground in room
  89008. this._standingMatrix.getTranslationToRef(this._workingVector);
  89009. return this._deviceRoomPosition.y + this._workingVector.y;
  89010. }
  89011. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  89012. return this._defaultHeight || 0;
  89013. };
  89014. /**
  89015. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  89016. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  89017. */
  89018. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  89019. var _this = this;
  89020. if (callback === void 0) { callback = function (bool) { }; }
  89021. // Use standing matrix if available
  89022. this.getEngine().initWebVRAsync().then(function (result) {
  89023. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  89024. callback(false);
  89025. }
  89026. else {
  89027. _this._standingMatrix = new BABYLON.Matrix();
  89028. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  89029. if (!_this.getScene().useRightHandedSystem) {
  89030. [2, 6, 8, 9, 14].forEach(function (num) {
  89031. if (_this._standingMatrix) {
  89032. _this._standingMatrix.m[num] *= -1;
  89033. }
  89034. });
  89035. }
  89036. callback(true);
  89037. }
  89038. });
  89039. };
  89040. /**
  89041. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  89042. * @returns A promise with a boolean set to if the standing matrix is supported.
  89043. */
  89044. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  89045. var _this = this;
  89046. return new Promise(function (res, rej) {
  89047. _this.useStandingMatrix(function (supported) {
  89048. res(supported);
  89049. });
  89050. });
  89051. };
  89052. /**
  89053. * Disposes the camera
  89054. */
  89055. WebVRFreeCamera.prototype.dispose = function () {
  89056. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  89057. _super.prototype.dispose.call(this);
  89058. };
  89059. /**
  89060. * Gets a vrController by name.
  89061. * @param name The name of the controller to retreive
  89062. * @returns the controller matching the name specified or null if not found
  89063. */
  89064. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  89065. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  89066. var gp = _a[_i];
  89067. if (gp.hand === name) {
  89068. return gp;
  89069. }
  89070. }
  89071. return null;
  89072. };
  89073. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  89074. /**
  89075. * The controller corrisponding to the users left hand.
  89076. */
  89077. get: function () {
  89078. if (!this._leftController) {
  89079. this._leftController = this.getControllerByName("left");
  89080. }
  89081. return this._leftController;
  89082. },
  89083. enumerable: true,
  89084. configurable: true
  89085. });
  89086. ;
  89087. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  89088. /**
  89089. * The controller corrisponding to the users right hand.
  89090. */
  89091. get: function () {
  89092. if (!this._rightController) {
  89093. this._rightController = this.getControllerByName("right");
  89094. }
  89095. return this._rightController;
  89096. },
  89097. enumerable: true,
  89098. configurable: true
  89099. });
  89100. ;
  89101. /**
  89102. * Casts a ray forward from the vrCamera's gaze.
  89103. * @param length Length of the ray (default: 100)
  89104. * @returns the ray corrisponding to the gaze
  89105. */
  89106. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  89107. if (length === void 0) { length = 100; }
  89108. if (this.leftCamera) {
  89109. // Use left eye to avoid computation to compute center on every call
  89110. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  89111. }
  89112. else {
  89113. return _super.prototype.getForwardRay.call(this, length);
  89114. }
  89115. };
  89116. /**
  89117. * Updates the camera based on device's frame data
  89118. */
  89119. WebVRFreeCamera.prototype._checkInputs = function () {
  89120. if (this._vrDevice && this._vrDevice.isPresenting) {
  89121. this._vrDevice.getFrameData(this._frameData);
  89122. this.updateFromDevice(this._frameData.pose);
  89123. }
  89124. _super.prototype._checkInputs.call(this);
  89125. };
  89126. /**
  89127. * Updates the poseControlled values based on the input device pose.
  89128. * @param poseData Pose coming from the device
  89129. */
  89130. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  89131. if (poseData && poseData.orientation) {
  89132. this.rawPose = poseData;
  89133. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  89134. if (this.getScene().useRightHandedSystem) {
  89135. this._deviceRoomRotationQuaternion.z *= -1;
  89136. this._deviceRoomRotationQuaternion.w *= -1;
  89137. }
  89138. if (this.webVROptions.trackPosition && this.rawPose.position) {
  89139. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  89140. if (this.getScene().useRightHandedSystem) {
  89141. this._deviceRoomPosition.z *= -1;
  89142. }
  89143. }
  89144. }
  89145. };
  89146. /**
  89147. * WebVR's attach control will start broadcasting frames to the device.
  89148. * Note that in certain browsers (chrome for example) this function must be called
  89149. * within a user-interaction callback. Example:
  89150. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  89151. *
  89152. * @param element html element to attach the vrDevice to
  89153. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  89154. */
  89155. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  89156. _super.prototype.attachControl.call(this, element, noPreventDefault);
  89157. this._attached = true;
  89158. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  89159. if (this._vrDevice) {
  89160. this.getEngine().enableVR();
  89161. }
  89162. };
  89163. /**
  89164. * Detaches the camera from the html element and disables VR
  89165. *
  89166. * @param element html element to detach from
  89167. */
  89168. WebVRFreeCamera.prototype.detachControl = function (element) {
  89169. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  89170. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  89171. _super.prototype.detachControl.call(this, element);
  89172. this._attached = false;
  89173. this.getEngine().disableVR();
  89174. };
  89175. /**
  89176. * @returns the name of this class
  89177. */
  89178. WebVRFreeCamera.prototype.getClassName = function () {
  89179. return "WebVRFreeCamera";
  89180. };
  89181. /**
  89182. * Calls resetPose on the vrDisplay
  89183. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  89184. */
  89185. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  89186. //uses the vrDisplay's "resetPose()".
  89187. //pitch and roll won't be affected.
  89188. this._vrDevice.resetPose();
  89189. };
  89190. /**
  89191. * Updates the rig cameras (left and right eye)
  89192. */
  89193. WebVRFreeCamera.prototype._updateRigCameras = function () {
  89194. var camLeft = this._rigCameras[0];
  89195. var camRight = this._rigCameras[1];
  89196. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  89197. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  89198. camLeft.position.copyFrom(this._deviceRoomPosition);
  89199. camRight.position.copyFrom(this._deviceRoomPosition);
  89200. };
  89201. /**
  89202. * Updates the cached values of the camera
  89203. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  89204. */
  89205. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  89206. var _this = this;
  89207. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  89208. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  89209. if (!this.updateCacheCalled) {
  89210. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  89211. this.updateCacheCalled = true;
  89212. this.update();
  89213. }
  89214. // Set working vector to the device position in room space rotated by the new rotation
  89215. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  89216. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  89217. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  89218. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  89219. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  89220. // Add translation from anchor position
  89221. this._deviceToWorld.getTranslationToRef(this._workingVector);
  89222. this._workingVector.addInPlace(this.position);
  89223. this._workingVector.subtractInPlace(this._cache.position);
  89224. this._deviceToWorld.setTranslation(this._workingVector);
  89225. // Set an inverted matrix to be used when updating the camera
  89226. this._deviceToWorld.invertToRef(this._worldToDevice);
  89227. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  89228. this.controllers.forEach(function (controller) {
  89229. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  89230. controller.update();
  89231. });
  89232. }
  89233. if (!ignoreParentClass) {
  89234. _super.prototype._updateCache.call(this);
  89235. }
  89236. this.updateCacheCalled = false;
  89237. };
  89238. /**
  89239. * Updates the current device position and rotation in the babylon world
  89240. */
  89241. WebVRFreeCamera.prototype.update = function () {
  89242. // Get current device position in babylon world
  89243. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  89244. // Get current device rotation in babylon world
  89245. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  89246. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  89247. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  89248. _super.prototype.update.call(this);
  89249. };
  89250. /**
  89251. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  89252. * @returns an identity matrix
  89253. */
  89254. WebVRFreeCamera.prototype._getViewMatrix = function () {
  89255. return BABYLON.Matrix.Identity();
  89256. };
  89257. /**
  89258. * This function is called by the two RIG cameras.
  89259. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  89260. */
  89261. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  89262. var _this = this;
  89263. // Update the parent camera prior to using a child camera to avoid desynchronization
  89264. var parentCamera = this._cameraRigParams["parentCamera"];
  89265. parentCamera._updateCache();
  89266. //WebVR 1.1
  89267. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  89268. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  89269. if (!this.getScene().useRightHandedSystem) {
  89270. [2, 6, 8, 9, 14].forEach(function (num) {
  89271. _this._webvrViewMatrix.m[num] *= -1;
  89272. });
  89273. }
  89274. // update the camera rotation matrix
  89275. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  89276. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  89277. // Computing target and final matrix
  89278. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  89279. // should the view matrix be updated with scale and position offset?
  89280. if (parentCamera.deviceScaleFactor !== 1) {
  89281. this._webvrViewMatrix.invert();
  89282. // scale the position, if set
  89283. if (parentCamera.deviceScaleFactor) {
  89284. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  89285. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  89286. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  89287. }
  89288. this._webvrViewMatrix.invert();
  89289. }
  89290. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  89291. // Compute global position
  89292. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  89293. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  89294. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  89295. this._workingMatrix.getTranslationToRef(this._globalPosition);
  89296. this._markSyncedWithParent();
  89297. return this._webvrViewMatrix;
  89298. };
  89299. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  89300. var _this = this;
  89301. var parentCamera = this.parent;
  89302. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  89303. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  89304. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  89305. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  89306. //babylon compatible matrix
  89307. if (!this.getScene().useRightHandedSystem) {
  89308. [8, 9, 10, 11].forEach(function (num) {
  89309. _this._projectionMatrix.m[num] *= -1;
  89310. });
  89311. }
  89312. return this._projectionMatrix;
  89313. };
  89314. /**
  89315. * Initializes the controllers and their meshes
  89316. */
  89317. WebVRFreeCamera.prototype.initControllers = function () {
  89318. var _this = this;
  89319. this.controllers = [];
  89320. var manager = this.getScene().gamepadManager;
  89321. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  89322. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  89323. var webVrController = gamepad;
  89324. if (webVrController.defaultModel) {
  89325. webVrController.defaultModel.setEnabled(false);
  89326. }
  89327. if (webVrController.hand === "right") {
  89328. _this._rightController = null;
  89329. }
  89330. if (webVrController.hand === "left") {
  89331. _this._leftController = null;
  89332. }
  89333. var controllerIndex = _this.controllers.indexOf(webVrController);
  89334. if (controllerIndex !== -1) {
  89335. _this.controllers.splice(controllerIndex, 1);
  89336. }
  89337. }
  89338. });
  89339. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  89340. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  89341. var webVrController_1 = gamepad;
  89342. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  89343. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  89344. if (_this.webVROptions.controllerMeshes) {
  89345. if (webVrController_1.defaultModel) {
  89346. webVrController_1.defaultModel.setEnabled(true);
  89347. }
  89348. else {
  89349. // Load the meshes
  89350. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  89351. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  89352. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  89353. if (_this.webVROptions.defaultLightingOnControllers) {
  89354. if (!_this._lightOnControllers) {
  89355. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  89356. }
  89357. var activateLightOnSubMeshes_1 = function (mesh, light) {
  89358. var children = mesh.getChildren();
  89359. if (children.length !== 0) {
  89360. children.forEach(function (mesh) {
  89361. light.includedOnlyMeshes.push(mesh);
  89362. activateLightOnSubMeshes_1(mesh, light);
  89363. });
  89364. }
  89365. };
  89366. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  89367. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  89368. }
  89369. });
  89370. }
  89371. }
  89372. webVrController_1.attachToPoseControlledCamera(_this);
  89373. // since this is async - sanity check. Is the controller already stored?
  89374. if (_this.controllers.indexOf(webVrController_1) === -1) {
  89375. //add to the controllers array
  89376. _this.controllers.push(webVrController_1);
  89377. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  89378. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  89379. // So we're overriding setting left & right manually to be sure
  89380. var firstViveWandDetected = false;
  89381. for (var i = 0; i < _this.controllers.length; i++) {
  89382. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  89383. if (!firstViveWandDetected) {
  89384. firstViveWandDetected = true;
  89385. _this.controllers[i].hand = "left";
  89386. }
  89387. else {
  89388. _this.controllers[i].hand = "right";
  89389. }
  89390. }
  89391. }
  89392. //did we find enough controllers? Great! let the developer know.
  89393. if (_this.controllers.length >= 2) {
  89394. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  89395. }
  89396. }
  89397. }
  89398. });
  89399. };
  89400. return WebVRFreeCamera;
  89401. }(BABYLON.FreeCamera));
  89402. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  89403. })(BABYLON || (BABYLON = {}));
  89404. //# sourceMappingURL=babylon.webVRCamera.js.map
  89405. var BABYLON;
  89406. (function (BABYLON) {
  89407. // We're mainly based on the logic defined into the FreeCamera code
  89408. /**
  89409. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  89410. * being tilted forward or back and left or right.
  89411. */
  89412. var DeviceOrientationCamera = /** @class */ (function (_super) {
  89413. __extends(DeviceOrientationCamera, _super);
  89414. /**
  89415. * Creates a new device orientation camera
  89416. * @param name The name of the camera
  89417. * @param position The start position camera
  89418. * @param scene The scene the camera belongs to
  89419. */
  89420. function DeviceOrientationCamera(name, position, scene) {
  89421. var _this = _super.call(this, name, position, scene) || this;
  89422. _this._quaternionCache = new BABYLON.Quaternion();
  89423. _this.inputs.addDeviceOrientation();
  89424. return _this;
  89425. }
  89426. /**
  89427. * Gets the current instance class name ("DeviceOrientationCamera").
  89428. * This helps avoiding instanceof at run time.
  89429. * @returns the class name
  89430. */
  89431. DeviceOrientationCamera.prototype.getClassName = function () {
  89432. return "DeviceOrientationCamera";
  89433. };
  89434. /**
  89435. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  89436. */
  89437. DeviceOrientationCamera.prototype._checkInputs = function () {
  89438. _super.prototype._checkInputs.call(this);
  89439. this._quaternionCache.copyFrom(this.rotationQuaternion);
  89440. if (this._initialQuaternion) {
  89441. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  89442. }
  89443. };
  89444. /**
  89445. * Reset the camera to its default orientation on the specified axis only.
  89446. * @param axis The axis to reset
  89447. */
  89448. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  89449. var _this = this;
  89450. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  89451. //can only work if this camera has a rotation quaternion already.
  89452. if (!this.rotationQuaternion)
  89453. return;
  89454. if (!this._initialQuaternion) {
  89455. this._initialQuaternion = new BABYLON.Quaternion();
  89456. }
  89457. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  89458. ['x', 'y', 'z'].forEach(function (axisName) {
  89459. if (!axis[axisName]) {
  89460. _this._initialQuaternion[axisName] = 0;
  89461. }
  89462. else {
  89463. _this._initialQuaternion[axisName] *= -1;
  89464. }
  89465. });
  89466. this._initialQuaternion.normalize();
  89467. //force rotation update
  89468. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  89469. };
  89470. return DeviceOrientationCamera;
  89471. }(BABYLON.FreeCamera));
  89472. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  89473. })(BABYLON || (BABYLON = {}));
  89474. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  89475. var BABYLON;
  89476. (function (BABYLON) {
  89477. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  89478. __extends(VRDeviceOrientationFreeCamera, _super);
  89479. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  89480. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89481. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89482. var _this = _super.call(this, name, position, scene) || this;
  89483. vrCameraMetrics.compensateDistortion = compensateDistortion;
  89484. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  89485. return _this;
  89486. }
  89487. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  89488. return "VRDeviceOrientationFreeCamera";
  89489. };
  89490. return VRDeviceOrientationFreeCamera;
  89491. }(BABYLON.DeviceOrientationCamera));
  89492. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  89493. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  89494. __extends(VRDeviceOrientationGamepadCamera, _super);
  89495. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  89496. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89497. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89498. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  89499. _this.inputs.addGamepad();
  89500. return _this;
  89501. }
  89502. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  89503. return "VRDeviceOrientationGamepadCamera";
  89504. };
  89505. return VRDeviceOrientationGamepadCamera;
  89506. }(VRDeviceOrientationFreeCamera));
  89507. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  89508. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  89509. __extends(VRDeviceOrientationArcRotateCamera, _super);
  89510. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  89511. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89512. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89513. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89514. vrCameraMetrics.compensateDistortion = compensateDistortion;
  89515. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  89516. _this.inputs.addVRDeviceOrientation();
  89517. return _this;
  89518. }
  89519. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  89520. return "VRDeviceOrientationArcRotateCamera";
  89521. };
  89522. return VRDeviceOrientationArcRotateCamera;
  89523. }(BABYLON.ArcRotateCamera));
  89524. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  89525. })(BABYLON || (BABYLON = {}));
  89526. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  89527. var BABYLON;
  89528. (function (BABYLON) {
  89529. /**
  89530. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  89531. */
  89532. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  89533. __extends(AnaglyphFreeCamera, _super);
  89534. /**
  89535. * Creates a new AnaglyphFreeCamera
  89536. * @param name defines camera name
  89537. * @param position defines initial position
  89538. * @param interaxialDistance defines distance between each color axis
  89539. * @param scene defines the hosting scene
  89540. */
  89541. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  89542. var _this = _super.call(this, name, position, scene) || this;
  89543. _this.interaxialDistance = interaxialDistance;
  89544. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89545. return _this;
  89546. }
  89547. /**
  89548. * Gets camera class name
  89549. * @returns AnaglyphFreeCamera
  89550. */
  89551. AnaglyphFreeCamera.prototype.getClassName = function () {
  89552. return "AnaglyphFreeCamera";
  89553. };
  89554. return AnaglyphFreeCamera;
  89555. }(BABYLON.FreeCamera));
  89556. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  89557. /**
  89558. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  89559. */
  89560. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  89561. __extends(AnaglyphArcRotateCamera, _super);
  89562. /**
  89563. * Creates a new AnaglyphArcRotateCamera
  89564. * @param name defines camera name
  89565. * @param alpha defines alpha angle (in radians)
  89566. * @param beta defines beta angle (in radians)
  89567. * @param radius defines radius
  89568. * @param target defines camera target
  89569. * @param interaxialDistance defines distance between each color axis
  89570. * @param scene defines the hosting scene
  89571. */
  89572. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  89573. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89574. _this.interaxialDistance = interaxialDistance;
  89575. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89576. return _this;
  89577. }
  89578. /**
  89579. * Gets camera class name
  89580. * @returns AnaglyphArcRotateCamera
  89581. */
  89582. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  89583. return "AnaglyphArcRotateCamera";
  89584. };
  89585. return AnaglyphArcRotateCamera;
  89586. }(BABYLON.ArcRotateCamera));
  89587. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  89588. /**
  89589. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  89590. */
  89591. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  89592. __extends(AnaglyphGamepadCamera, _super);
  89593. /**
  89594. * Creates a new AnaglyphGamepadCamera
  89595. * @param name defines camera name
  89596. * @param position defines initial position
  89597. * @param interaxialDistance defines distance between each color axis
  89598. * @param scene defines the hosting scene
  89599. */
  89600. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  89601. var _this = _super.call(this, name, position, scene) || this;
  89602. _this.interaxialDistance = interaxialDistance;
  89603. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89604. return _this;
  89605. }
  89606. /**
  89607. * Gets camera class name
  89608. * @returns AnaglyphGamepadCamera
  89609. */
  89610. AnaglyphGamepadCamera.prototype.getClassName = function () {
  89611. return "AnaglyphGamepadCamera";
  89612. };
  89613. return AnaglyphGamepadCamera;
  89614. }(BABYLON.GamepadCamera));
  89615. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  89616. /**
  89617. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  89618. */
  89619. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  89620. __extends(AnaglyphUniversalCamera, _super);
  89621. /**
  89622. * Creates a new AnaglyphUniversalCamera
  89623. * @param name defines camera name
  89624. * @param position defines initial position
  89625. * @param interaxialDistance defines distance between each color axis
  89626. * @param scene defines the hosting scene
  89627. */
  89628. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  89629. var _this = _super.call(this, name, position, scene) || this;
  89630. _this.interaxialDistance = interaxialDistance;
  89631. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89632. return _this;
  89633. }
  89634. /**
  89635. * Gets camera class name
  89636. * @returns AnaglyphUniversalCamera
  89637. */
  89638. AnaglyphUniversalCamera.prototype.getClassName = function () {
  89639. return "AnaglyphUniversalCamera";
  89640. };
  89641. return AnaglyphUniversalCamera;
  89642. }(BABYLON.UniversalCamera));
  89643. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  89644. /**
  89645. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  89646. */
  89647. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  89648. __extends(StereoscopicFreeCamera, _super);
  89649. /**
  89650. * Creates a new StereoscopicFreeCamera
  89651. * @param name defines camera name
  89652. * @param position defines initial position
  89653. * @param interaxialDistance defines distance between each color axis
  89654. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89655. * @param scene defines the hosting scene
  89656. */
  89657. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89658. var _this = _super.call(this, name, position, scene) || this;
  89659. _this.interaxialDistance = interaxialDistance;
  89660. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89661. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89662. return _this;
  89663. }
  89664. /**
  89665. * Gets camera class name
  89666. * @returns StereoscopicFreeCamera
  89667. */
  89668. StereoscopicFreeCamera.prototype.getClassName = function () {
  89669. return "StereoscopicFreeCamera";
  89670. };
  89671. return StereoscopicFreeCamera;
  89672. }(BABYLON.FreeCamera));
  89673. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  89674. /**
  89675. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  89676. */
  89677. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  89678. __extends(StereoscopicArcRotateCamera, _super);
  89679. /**
  89680. * Creates a new StereoscopicArcRotateCamera
  89681. * @param name defines camera name
  89682. * @param alpha defines alpha angle (in radians)
  89683. * @param beta defines beta angle (in radians)
  89684. * @param radius defines radius
  89685. * @param target defines camera target
  89686. * @param interaxialDistance defines distance between each color axis
  89687. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89688. * @param scene defines the hosting scene
  89689. */
  89690. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  89691. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89692. _this.interaxialDistance = interaxialDistance;
  89693. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89694. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89695. return _this;
  89696. }
  89697. /**
  89698. * Gets camera class name
  89699. * @returns StereoscopicArcRotateCamera
  89700. */
  89701. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  89702. return "StereoscopicArcRotateCamera";
  89703. };
  89704. return StereoscopicArcRotateCamera;
  89705. }(BABYLON.ArcRotateCamera));
  89706. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  89707. /**
  89708. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  89709. */
  89710. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  89711. __extends(StereoscopicGamepadCamera, _super);
  89712. /**
  89713. * Creates a new StereoscopicGamepadCamera
  89714. * @param name defines camera name
  89715. * @param position defines initial position
  89716. * @param interaxialDistance defines distance between each color axis
  89717. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89718. * @param scene defines the hosting scene
  89719. */
  89720. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89721. var _this = _super.call(this, name, position, scene) || this;
  89722. _this.interaxialDistance = interaxialDistance;
  89723. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89724. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89725. return _this;
  89726. }
  89727. /**
  89728. * Gets camera class name
  89729. * @returns StereoscopicGamepadCamera
  89730. */
  89731. StereoscopicGamepadCamera.prototype.getClassName = function () {
  89732. return "StereoscopicGamepadCamera";
  89733. };
  89734. return StereoscopicGamepadCamera;
  89735. }(BABYLON.GamepadCamera));
  89736. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  89737. /**
  89738. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  89739. */
  89740. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  89741. __extends(StereoscopicUniversalCamera, _super);
  89742. /**
  89743. * Creates a new StereoscopicUniversalCamera
  89744. * @param name defines camera name
  89745. * @param position defines initial position
  89746. * @param interaxialDistance defines distance between each color axis
  89747. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89748. * @param scene defines the hosting scene
  89749. */
  89750. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89751. var _this = _super.call(this, name, position, scene) || this;
  89752. _this.interaxialDistance = interaxialDistance;
  89753. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89754. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89755. return _this;
  89756. }
  89757. /**
  89758. * Gets camera class name
  89759. * @returns StereoscopicUniversalCamera
  89760. */
  89761. StereoscopicUniversalCamera.prototype.getClassName = function () {
  89762. return "StereoscopicUniversalCamera";
  89763. };
  89764. return StereoscopicUniversalCamera;
  89765. }(BABYLON.UniversalCamera));
  89766. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  89767. })(BABYLON || (BABYLON = {}));
  89768. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  89769. var BABYLON;
  89770. (function (BABYLON) {
  89771. var VRExperienceHelperGazer = /** @class */ (function () {
  89772. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  89773. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  89774. this.scene = scene;
  89775. this._pointerDownOnMeshAsked = false;
  89776. this._isActionableMesh = false;
  89777. this._teleportationRequestInitiated = false;
  89778. this._teleportationBackRequestInitiated = false;
  89779. this._rotationRightAsked = false;
  89780. this._rotationLeftAsked = false;
  89781. this._dpadPressed = true;
  89782. this._activePointer = false;
  89783. this._id = VRExperienceHelperGazer._idCounter++;
  89784. // Gaze tracker
  89785. if (!gazeTrackerToClone) {
  89786. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  89787. this._gazeTracker.bakeCurrentTransformIntoVertices();
  89788. this._gazeTracker.isPickable = false;
  89789. this._gazeTracker.isVisible = false;
  89790. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  89791. targetMat.specularColor = BABYLON.Color3.Black();
  89792. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  89793. targetMat.backFaceCulling = false;
  89794. this._gazeTracker.material = targetMat;
  89795. }
  89796. else {
  89797. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  89798. }
  89799. }
  89800. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  89801. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  89802. };
  89803. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  89804. this._pointerDownOnMeshAsked = true;
  89805. if (this._currentHit) {
  89806. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  89807. }
  89808. };
  89809. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  89810. if (this._currentHit) {
  89811. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  89812. }
  89813. this._pointerDownOnMeshAsked = false;
  89814. };
  89815. VRExperienceHelperGazer.prototype._activatePointer = function () {
  89816. this._activePointer = true;
  89817. };
  89818. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  89819. this._activePointer = false;
  89820. };
  89821. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  89822. if (distance === void 0) { distance = 100; }
  89823. };
  89824. VRExperienceHelperGazer.prototype.dispose = function () {
  89825. this._interactionsEnabled = false;
  89826. this._teleportationEnabled = false;
  89827. if (this._gazeTracker) {
  89828. this._gazeTracker.dispose();
  89829. }
  89830. };
  89831. VRExperienceHelperGazer._idCounter = 0;
  89832. return VRExperienceHelperGazer;
  89833. }());
  89834. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  89835. __extends(VRExperienceHelperControllerGazer, _super);
  89836. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  89837. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  89838. _this.webVRController = webVRController;
  89839. // Laser pointer
  89840. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  89841. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  89842. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  89843. laserPointerMaterial.alpha = 0.6;
  89844. _this._laserPointer.material = laserPointerMaterial;
  89845. _this._laserPointer.rotation.x = Math.PI / 2;
  89846. _this._laserPointer.position.z = -0.5;
  89847. _this._laserPointer.isVisible = false;
  89848. if (!webVRController.mesh) {
  89849. // Create an empty mesh that is used prior to loading the high quality model
  89850. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  89851. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  89852. preloadPointerPose.rotation.x = -0.7;
  89853. preloadMesh.addChild(preloadPointerPose);
  89854. webVRController.attachToMesh(preloadMesh);
  89855. }
  89856. _this._setLaserPointerParent(webVRController.mesh);
  89857. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  89858. _this._setLaserPointerParent(mesh);
  89859. });
  89860. return _this;
  89861. }
  89862. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  89863. return this.webVRController.getForwardRay(length);
  89864. };
  89865. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  89866. _super.prototype._activatePointer.call(this);
  89867. this._laserPointer.isVisible = true;
  89868. };
  89869. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  89870. _super.prototype._deactivatePointer.call(this);
  89871. this._laserPointer.isVisible = false;
  89872. };
  89873. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  89874. this._laserPointer.material.emissiveColor = color;
  89875. };
  89876. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  89877. var makeNotPick = function (root) {
  89878. root.name += " laserPointer";
  89879. root.getChildMeshes().forEach(function (c) {
  89880. makeNotPick(c);
  89881. });
  89882. };
  89883. makeNotPick(mesh);
  89884. var childMeshes = mesh.getChildMeshes();
  89885. this.webVRController._pointingPoseNode = null;
  89886. for (var i = 0; i < childMeshes.length; i++) {
  89887. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  89888. mesh = childMeshes[i];
  89889. this.webVRController._pointingPoseNode = mesh;
  89890. break;
  89891. }
  89892. }
  89893. this._laserPointer.parent = mesh;
  89894. };
  89895. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  89896. if (distance === void 0) { distance = 100; }
  89897. this._laserPointer.scaling.y = distance;
  89898. this._laserPointer.position.z = -distance / 2;
  89899. };
  89900. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  89901. _super.prototype.dispose.call(this);
  89902. this._laserPointer.dispose();
  89903. if (this._meshAttachedObserver) {
  89904. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  89905. }
  89906. };
  89907. return VRExperienceHelperControllerGazer;
  89908. }(VRExperienceHelperGazer));
  89909. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  89910. __extends(VRExperienceHelperCameraGazer, _super);
  89911. function VRExperienceHelperCameraGazer(getCamera, scene) {
  89912. var _this = _super.call(this, scene) || this;
  89913. _this.getCamera = getCamera;
  89914. return _this;
  89915. }
  89916. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  89917. var camera = this.getCamera();
  89918. if (camera) {
  89919. return camera.getForwardRay(length);
  89920. }
  89921. else {
  89922. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  89923. }
  89924. };
  89925. return VRExperienceHelperCameraGazer;
  89926. }(VRExperienceHelperGazer));
  89927. /**
  89928. * Helps to quickly add VR support to an existing scene.
  89929. * See http://doc.babylonjs.com/how_to/webvr_helper
  89930. */
  89931. var VRExperienceHelper = /** @class */ (function () {
  89932. /**
  89933. * Instantiates a VRExperienceHelper.
  89934. * Helps to quickly add VR support to an existing scene.
  89935. * @param scene The scene the VRExperienceHelper belongs to.
  89936. * @param webVROptions Options to modify the vr experience helper's behavior.
  89937. */
  89938. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  89939. if (webVROptions === void 0) { webVROptions = {}; }
  89940. var _this = this;
  89941. this.webVROptions = webVROptions;
  89942. // Can the system support WebVR, even if a headset isn't plugged in?
  89943. this._webVRsupported = false;
  89944. // If WebVR is supported, is a headset plugged in and are we ready to present?
  89945. this._webVRready = false;
  89946. // Are we waiting for the requestPresent callback to complete?
  89947. this._webVRrequesting = false;
  89948. // Are we presenting to the headset right now?
  89949. this._webVRpresenting = false;
  89950. // Are we presenting in the fullscreen fallback?
  89951. this._fullscreenVRpresenting = false;
  89952. /**
  89953. * Observable raised when entering VR.
  89954. */
  89955. this.onEnteringVRObservable = new BABYLON.Observable();
  89956. /**
  89957. * Observable raised when exiting VR.
  89958. */
  89959. this.onExitingVRObservable = new BABYLON.Observable();
  89960. /**
  89961. * Observable raised when controller mesh is loaded.
  89962. */
  89963. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  89964. this._useCustomVRButton = false;
  89965. this._teleportationRequested = false;
  89966. this._teleportActive = false;
  89967. this._floorMeshesCollection = [];
  89968. this._rotationAllowed = true;
  89969. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  89970. this._isDefaultTeleportationTarget = true;
  89971. this._teleportationFillColor = "#444444";
  89972. this._teleportationBorderColor = "#FFFFFF";
  89973. this._rotationAngle = 0;
  89974. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  89975. this._padSensibilityUp = 0.65;
  89976. this._padSensibilityDown = 0.35;
  89977. this.leftController = null;
  89978. this.rightController = null;
  89979. /**
  89980. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  89981. */
  89982. this.onNewMeshSelected = new BABYLON.Observable();
  89983. /**
  89984. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  89985. */
  89986. this.onNewMeshPicked = new BABYLON.Observable();
  89987. /**
  89988. * Observable raised before camera teleportation
  89989. */
  89990. this.onBeforeCameraTeleport = new BABYLON.Observable();
  89991. /**
  89992. * Observable raised after camera teleportation
  89993. */
  89994. this.onAfterCameraTeleport = new BABYLON.Observable();
  89995. /**
  89996. * Observable raised when current selected mesh gets unselected
  89997. */
  89998. this.onSelectedMeshUnselected = new BABYLON.Observable();
  89999. /**
  90000. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  90001. */
  90002. this.teleportationEnabled = true;
  90003. this._teleportationInitialized = false;
  90004. this._interactionsEnabled = false;
  90005. this._interactionsRequested = false;
  90006. this._displayGaze = true;
  90007. this._displayLaserPointer = true;
  90008. this._onResize = function () {
  90009. _this.moveButtonToBottomRight();
  90010. if (_this._fullscreenVRpresenting && _this._webVRready) {
  90011. _this.exitVR();
  90012. }
  90013. };
  90014. this._onFullscreenChange = function () {
  90015. if (document.fullscreen !== undefined) {
  90016. _this._fullscreenVRpresenting = document.fullscreen;
  90017. }
  90018. else if (document.mozFullScreen !== undefined) {
  90019. _this._fullscreenVRpresenting = document.mozFullScreen;
  90020. }
  90021. else if (document.webkitIsFullScreen !== undefined) {
  90022. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  90023. }
  90024. else if (document.msIsFullScreen !== undefined) {
  90025. _this._fullscreenVRpresenting = document.msIsFullScreen;
  90026. }
  90027. if (!_this._fullscreenVRpresenting && _this._canvas) {
  90028. _this.exitVR();
  90029. if (!_this._useCustomVRButton) {
  90030. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  90031. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  90032. }
  90033. }
  90034. };
  90035. this.beforeRender = function () {
  90036. if (_this.leftController && _this.leftController._activePointer) {
  90037. _this._castRayAndSelectObject(_this.leftController);
  90038. }
  90039. if (_this.rightController && _this.rightController._activePointer) {
  90040. _this._castRayAndSelectObject(_this.rightController);
  90041. }
  90042. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  90043. _this._castRayAndSelectObject(_this._cameraGazer);
  90044. }
  90045. else {
  90046. _this._cameraGazer._gazeTracker.isVisible = false;
  90047. }
  90048. };
  90049. this._onNewGamepadConnected = function (gamepad) {
  90050. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  90051. if (gamepad.leftStick) {
  90052. gamepad.onleftstickchanged(function (stickValues) {
  90053. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  90054. // Listening to classic/xbox gamepad only if no VR controller is active
  90055. if ((!_this.leftController && !_this.rightController) ||
  90056. ((_this.leftController && !_this.leftController._activePointer) &&
  90057. (_this.rightController && !_this.rightController._activePointer))) {
  90058. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  90059. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  90060. }
  90061. }
  90062. });
  90063. }
  90064. if (gamepad.rightStick) {
  90065. gamepad.onrightstickchanged(function (stickValues) {
  90066. if (_this._teleportationInitialized) {
  90067. _this._checkRotate(stickValues, _this._cameraGazer);
  90068. }
  90069. });
  90070. }
  90071. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  90072. gamepad.onbuttondown(function (buttonPressed) {
  90073. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  90074. _this._cameraGazer._selectionPointerDown();
  90075. }
  90076. });
  90077. gamepad.onbuttonup(function (buttonPressed) {
  90078. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  90079. _this._cameraGazer._selectionPointerUp();
  90080. }
  90081. });
  90082. }
  90083. }
  90084. else {
  90085. var webVRController = gamepad;
  90086. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  90087. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  90088. _this.rightController = controller;
  90089. }
  90090. else {
  90091. _this.leftController = controller;
  90092. }
  90093. _this._tryEnableInteractionOnController(controller);
  90094. }
  90095. };
  90096. // 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
  90097. this._tryEnableInteractionOnController = function (controller) {
  90098. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  90099. _this._enableInteractionOnController(controller);
  90100. }
  90101. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  90102. _this._enableTeleportationOnController(controller);
  90103. }
  90104. };
  90105. this._onNewGamepadDisconnected = function (gamepad) {
  90106. if (gamepad instanceof BABYLON.WebVRController) {
  90107. if (gamepad.hand === "left" && _this.leftController != null) {
  90108. _this.leftController.dispose();
  90109. _this.leftController = null;
  90110. }
  90111. if (gamepad.hand === "right" && _this.rightController != null) {
  90112. _this.rightController.dispose();
  90113. _this.rightController = null;
  90114. }
  90115. }
  90116. };
  90117. this._workingVector = BABYLON.Vector3.Zero();
  90118. this._workingQuaternion = BABYLON.Quaternion.Identity();
  90119. this._workingMatrix = BABYLON.Matrix.Identity();
  90120. this._scene = scene;
  90121. this._canvas = scene.getEngine().getRenderingCanvas();
  90122. // Parse options
  90123. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  90124. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  90125. }
  90126. if (webVROptions.createDeviceOrientationCamera === undefined) {
  90127. webVROptions.createDeviceOrientationCamera = true;
  90128. }
  90129. if (webVROptions.laserToggle === undefined) {
  90130. webVROptions.laserToggle = true;
  90131. }
  90132. if (webVROptions.defaultHeight === undefined) {
  90133. webVROptions.defaultHeight = 1.7;
  90134. }
  90135. if (webVROptions.useCustomVRButton) {
  90136. this._useCustomVRButton = true;
  90137. if (webVROptions.customVRButton) {
  90138. this._btnVR = webVROptions.customVRButton;
  90139. }
  90140. }
  90141. if (webVROptions.rayLength) {
  90142. this._rayLength = webVROptions.rayLength;
  90143. }
  90144. this._defaultHeight = webVROptions.defaultHeight;
  90145. if (webVROptions.positionScale) {
  90146. this._rayLength *= webVROptions.positionScale;
  90147. this._defaultHeight *= webVROptions.positionScale;
  90148. }
  90149. // Set position
  90150. if (this._scene.activeCamera) {
  90151. this._position = this._scene.activeCamera.position.clone();
  90152. }
  90153. else {
  90154. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  90155. }
  90156. // Set non-vr camera
  90157. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  90158. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  90159. // Copy data from existing camera
  90160. if (this._scene.activeCamera) {
  90161. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  90162. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  90163. // Set rotation from previous camera
  90164. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  90165. var targetCamera = this._scene.activeCamera;
  90166. if (targetCamera.rotationQuaternion) {
  90167. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  90168. }
  90169. else {
  90170. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  90171. }
  90172. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  90173. }
  90174. }
  90175. this._scene.activeCamera = this._deviceOrientationCamera;
  90176. if (this._canvas) {
  90177. this._scene.activeCamera.attachControl(this._canvas);
  90178. }
  90179. }
  90180. else {
  90181. this._existingCamera = this._scene.activeCamera;
  90182. }
  90183. // Create VR cameras
  90184. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  90185. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  90186. }
  90187. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  90188. this._webVRCamera.useStandingMatrix();
  90189. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  90190. // Create default button
  90191. if (!this._useCustomVRButton) {
  90192. this._btnVR = document.createElement("BUTTON");
  90193. this._btnVR.className = "babylonVRicon";
  90194. this._btnVR.id = "babylonVRiconbtn";
  90195. this._btnVR.title = "Click to switch to VR";
  90196. 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) }";
  90197. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  90198. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  90199. // css += ".babylonVRicon.vrdisplaysupported { }";
  90200. // css += ".babylonVRicon.vrdisplayready { }";
  90201. // css += ".babylonVRicon.vrdisplayrequesting { }";
  90202. var style = document.createElement('style');
  90203. style.appendChild(document.createTextNode(css));
  90204. document.getElementsByTagName('head')[0].appendChild(style);
  90205. this.moveButtonToBottomRight();
  90206. }
  90207. // VR button click event
  90208. if (this._btnVR) {
  90209. this._btnVR.addEventListener("click", function () {
  90210. if (!_this.isInVRMode) {
  90211. _this.enterVR();
  90212. }
  90213. else {
  90214. _this.exitVR();
  90215. }
  90216. });
  90217. }
  90218. // Window events
  90219. window.addEventListener("resize", this._onResize);
  90220. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  90221. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  90222. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  90223. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  90224. // Display vr button when headset is connected
  90225. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  90226. this.displayVRButton();
  90227. }
  90228. else {
  90229. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  90230. if (e.vrDisplay) {
  90231. _this.displayVRButton();
  90232. }
  90233. });
  90234. }
  90235. // Exiting VR mode using 'ESC' key on desktop
  90236. this._onKeyDown = function (event) {
  90237. if (event.keyCode === 27 && _this.isInVRMode) {
  90238. _this.exitVR();
  90239. }
  90240. };
  90241. document.addEventListener("keydown", this._onKeyDown);
  90242. // Exiting VR mode double tapping the touch screen
  90243. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  90244. if (_this.isInVRMode) {
  90245. _this.exitVR();
  90246. if (_this._fullscreenVRpresenting) {
  90247. _this._scene.getEngine().switchFullscreen(true);
  90248. }
  90249. }
  90250. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  90251. // Listen for WebVR display changes
  90252. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  90253. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  90254. this._onVRRequestPresentStart = function () {
  90255. _this._webVRrequesting = true;
  90256. _this.updateButtonVisibility();
  90257. };
  90258. this._onVRRequestPresentComplete = function (success) {
  90259. _this._webVRrequesting = false;
  90260. _this.updateButtonVisibility();
  90261. };
  90262. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  90263. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  90264. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  90265. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  90266. scene.onDisposeObservable.add(function () {
  90267. _this.dispose();
  90268. });
  90269. // Gamepad connection events
  90270. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  90271. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  90272. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  90273. this.updateButtonVisibility();
  90274. //create easing functions
  90275. this._circleEase = new BABYLON.CircleEase();
  90276. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  90277. if (this.webVROptions.floorMeshes) {
  90278. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  90279. }
  90280. }
  90281. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  90282. /** Return this.onEnteringVRObservable
  90283. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  90284. */
  90285. get: function () {
  90286. return this.onEnteringVRObservable;
  90287. },
  90288. enumerable: true,
  90289. configurable: true
  90290. });
  90291. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  90292. /** Return this.onExitingVRObservable
  90293. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  90294. */
  90295. get: function () {
  90296. return this.onExitingVRObservable;
  90297. },
  90298. enumerable: true,
  90299. configurable: true
  90300. });
  90301. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  90302. /** Return this.onControllerMeshLoadedObservable
  90303. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  90304. */
  90305. get: function () {
  90306. return this.onControllerMeshLoadedObservable;
  90307. },
  90308. enumerable: true,
  90309. configurable: true
  90310. });
  90311. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  90312. /**
  90313. * The mesh used to display where the user is going to teleport.
  90314. */
  90315. get: function () {
  90316. return this._teleportationTarget;
  90317. },
  90318. /**
  90319. * Sets the mesh to be used to display where the user is going to teleport.
  90320. */
  90321. set: function (value) {
  90322. if (value) {
  90323. value.name = "teleportationTarget";
  90324. this._isDefaultTeleportationTarget = false;
  90325. this._teleportationTarget = value;
  90326. }
  90327. },
  90328. enumerable: true,
  90329. configurable: true
  90330. });
  90331. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  90332. /**
  90333. * The mesh used to display where the user is selecting,
  90334. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  90335. * See http://doc.babylonjs.com/resources/baking_transformations
  90336. */
  90337. get: function () {
  90338. return this._cameraGazer._gazeTracker;
  90339. },
  90340. set: function (value) {
  90341. if (value) {
  90342. this._cameraGazer._gazeTracker = value;
  90343. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  90344. this._cameraGazer._gazeTracker.isPickable = false;
  90345. this._cameraGazer._gazeTracker.isVisible = false;
  90346. this._cameraGazer._gazeTracker.name = "gazeTracker";
  90347. if (this.leftController) {
  90348. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  90349. }
  90350. if (this.rightController) {
  90351. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  90352. }
  90353. }
  90354. },
  90355. enumerable: true,
  90356. configurable: true
  90357. });
  90358. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  90359. /**
  90360. * If the ray of the gaze should be displayed.
  90361. */
  90362. get: function () {
  90363. return this._displayGaze;
  90364. },
  90365. /**
  90366. * Sets if the ray of the gaze should be displayed.
  90367. */
  90368. set: function (value) {
  90369. this._displayGaze = value;
  90370. if (!value) {
  90371. this._cameraGazer._gazeTracker.isVisible = false;
  90372. if (this.leftController) {
  90373. this.leftController._gazeTracker.isVisible = false;
  90374. }
  90375. if (this.rightController) {
  90376. this.rightController._gazeTracker.isVisible = false;
  90377. }
  90378. }
  90379. },
  90380. enumerable: true,
  90381. configurable: true
  90382. });
  90383. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  90384. /**
  90385. * If the ray of the LaserPointer should be displayed.
  90386. */
  90387. get: function () {
  90388. return this._displayLaserPointer;
  90389. },
  90390. /**
  90391. * Sets if the ray of the LaserPointer should be displayed.
  90392. */
  90393. set: function (value) {
  90394. this._displayLaserPointer = value;
  90395. if (!value) {
  90396. if (this.rightController) {
  90397. this.rightController._deactivatePointer();
  90398. this.rightController._gazeTracker.isVisible = false;
  90399. }
  90400. if (this.leftController) {
  90401. this.leftController._deactivatePointer();
  90402. this.leftController._gazeTracker.isVisible = false;
  90403. }
  90404. }
  90405. else {
  90406. if (this.rightController) {
  90407. this.rightController._activatePointer();
  90408. }
  90409. if (this.leftController) {
  90410. this.leftController._activatePointer();
  90411. }
  90412. }
  90413. },
  90414. enumerable: true,
  90415. configurable: true
  90416. });
  90417. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  90418. /**
  90419. * The deviceOrientationCamera used as the camera when not in VR.
  90420. */
  90421. get: function () {
  90422. return this._deviceOrientationCamera;
  90423. },
  90424. enumerable: true,
  90425. configurable: true
  90426. });
  90427. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  90428. /**
  90429. * Based on the current WebVR support, returns the current VR camera used.
  90430. */
  90431. get: function () {
  90432. if (this._webVRready) {
  90433. return this._webVRCamera;
  90434. }
  90435. else {
  90436. return this._scene.activeCamera;
  90437. }
  90438. },
  90439. enumerable: true,
  90440. configurable: true
  90441. });
  90442. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  90443. /**
  90444. * The webVRCamera which is used when in VR.
  90445. */
  90446. get: function () {
  90447. return this._webVRCamera;
  90448. },
  90449. enumerable: true,
  90450. configurable: true
  90451. });
  90452. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  90453. /**
  90454. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  90455. */
  90456. get: function () {
  90457. return this._vrDeviceOrientationCamera;
  90458. },
  90459. enumerable: true,
  90460. configurable: true
  90461. });
  90462. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  90463. get: function () {
  90464. var result = this._cameraGazer._teleportationRequestInitiated
  90465. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  90466. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  90467. return result;
  90468. },
  90469. enumerable: true,
  90470. configurable: true
  90471. });
  90472. // Raised when one of the controller has loaded successfully its associated default mesh
  90473. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  90474. if (this.leftController && this.leftController.webVRController == webVRController) {
  90475. if (webVRController.mesh) {
  90476. this.leftController._setLaserPointerParent(webVRController.mesh);
  90477. }
  90478. }
  90479. if (this.rightController && this.rightController.webVRController == webVRController) {
  90480. if (webVRController.mesh) {
  90481. this.rightController._setLaserPointerParent(webVRController.mesh);
  90482. }
  90483. }
  90484. try {
  90485. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  90486. }
  90487. catch (err) {
  90488. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  90489. }
  90490. };
  90491. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  90492. /**
  90493. * Gets a value indicating if we are currently in VR mode.
  90494. */
  90495. get: function () {
  90496. return this._webVRpresenting || this._fullscreenVRpresenting;
  90497. },
  90498. enumerable: true,
  90499. configurable: true
  90500. });
  90501. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  90502. var vrDisplay = this._scene.getEngine().getVRDevice();
  90503. if (vrDisplay) {
  90504. var wasPresenting = this._webVRpresenting;
  90505. // A VR display is connected
  90506. this._webVRpresenting = vrDisplay.isPresenting;
  90507. if (wasPresenting && !this._webVRpresenting)
  90508. this.exitVR();
  90509. }
  90510. else {
  90511. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  90512. }
  90513. this.updateButtonVisibility();
  90514. };
  90515. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  90516. this._webVRsupported = eventArgs.vrSupported;
  90517. this._webVRready = !!eventArgs.vrDisplay;
  90518. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  90519. this.updateButtonVisibility();
  90520. };
  90521. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  90522. if (this._canvas && !this._useCustomVRButton) {
  90523. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  90524. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  90525. }
  90526. };
  90527. VRExperienceHelper.prototype.displayVRButton = function () {
  90528. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  90529. document.body.appendChild(this._btnVR);
  90530. this._btnVRDisplayed = true;
  90531. }
  90532. };
  90533. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  90534. if (!this._btnVR || this._useCustomVRButton) {
  90535. return;
  90536. }
  90537. this._btnVR.className = "babylonVRicon";
  90538. if (this.isInVRMode) {
  90539. this._btnVR.className += " vrdisplaypresenting";
  90540. }
  90541. else {
  90542. if (this._webVRready)
  90543. this._btnVR.className += " vrdisplayready";
  90544. if (this._webVRsupported)
  90545. this._btnVR.className += " vrdisplaysupported";
  90546. if (this._webVRrequesting)
  90547. this._btnVR.className += " vrdisplayrequesting";
  90548. }
  90549. };
  90550. /**
  90551. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  90552. * Otherwise, will use the fullscreen API.
  90553. */
  90554. VRExperienceHelper.prototype.enterVR = function () {
  90555. if (this.onEnteringVRObservable) {
  90556. try {
  90557. this.onEnteringVRObservable.notifyObservers(this);
  90558. }
  90559. catch (err) {
  90560. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  90561. }
  90562. }
  90563. if (this._scene.activeCamera) {
  90564. this._position = this._scene.activeCamera.position.clone();
  90565. // make sure that we return to the last active camera
  90566. this._existingCamera = this._scene.activeCamera;
  90567. }
  90568. if (this._webVRrequesting)
  90569. return;
  90570. // If WebVR is supported and a headset is connected
  90571. if (this._webVRready) {
  90572. if (!this._webVRpresenting) {
  90573. this._webVRCamera.position = this._position;
  90574. this._scene.activeCamera = this._webVRCamera;
  90575. }
  90576. }
  90577. else if (this._vrDeviceOrientationCamera) {
  90578. this._vrDeviceOrientationCamera.position = this._position;
  90579. if (this._scene.activeCamera) {
  90580. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  90581. }
  90582. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  90583. this._scene.getEngine().switchFullscreen(true);
  90584. this.updateButtonVisibility();
  90585. }
  90586. if (this._scene.activeCamera && this._canvas) {
  90587. this._scene.activeCamera.attachControl(this._canvas);
  90588. }
  90589. if (this._interactionsEnabled) {
  90590. this._scene.registerBeforeRender(this.beforeRender);
  90591. }
  90592. };
  90593. /**
  90594. * Attempt to exit VR, or fullscreen.
  90595. */
  90596. VRExperienceHelper.prototype.exitVR = function () {
  90597. if (this.onExitingVRObservable) {
  90598. try {
  90599. this.onExitingVRObservable.notifyObservers(this);
  90600. }
  90601. catch (err) {
  90602. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  90603. }
  90604. }
  90605. if (this._webVRpresenting) {
  90606. this._scene.getEngine().disableVR();
  90607. }
  90608. if (this._scene.activeCamera) {
  90609. this._position = this._scene.activeCamera.position.clone();
  90610. }
  90611. if (this._deviceOrientationCamera) {
  90612. this._deviceOrientationCamera.position = this._position;
  90613. this._scene.activeCamera = this._deviceOrientationCamera;
  90614. if (this._canvas) {
  90615. this._scene.activeCamera.attachControl(this._canvas);
  90616. }
  90617. }
  90618. else if (this._existingCamera) {
  90619. this._existingCamera.position = this._position;
  90620. this._scene.activeCamera = this._existingCamera;
  90621. }
  90622. this.updateButtonVisibility();
  90623. if (this._interactionsEnabled) {
  90624. this._scene.unregisterBeforeRender(this.beforeRender);
  90625. }
  90626. // resize to update width and height when exiting vr exits fullscreen
  90627. this._scene.getEngine().resize();
  90628. };
  90629. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  90630. /**
  90631. * The position of the vr experience helper.
  90632. */
  90633. get: function () {
  90634. return this._position;
  90635. },
  90636. /**
  90637. * Sets the position of the vr experience helper.
  90638. */
  90639. set: function (value) {
  90640. this._position = value;
  90641. if (this._scene.activeCamera) {
  90642. this._scene.activeCamera.position = value;
  90643. }
  90644. },
  90645. enumerable: true,
  90646. configurable: true
  90647. });
  90648. /**
  90649. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  90650. */
  90651. VRExperienceHelper.prototype.enableInteractions = function () {
  90652. var _this = this;
  90653. if (!this._interactionsEnabled) {
  90654. this._interactionsRequested = true;
  90655. if (this.leftController) {
  90656. this._enableInteractionOnController(this.leftController);
  90657. }
  90658. if (this.rightController) {
  90659. this._enableInteractionOnController(this.rightController);
  90660. }
  90661. this.raySelectionPredicate = function (mesh) {
  90662. return mesh.isVisible;
  90663. };
  90664. this.meshSelectionPredicate = function (mesh) {
  90665. return true;
  90666. };
  90667. this._raySelectionPredicate = function (mesh) {
  90668. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  90669. && mesh.name.indexOf("teleportationTarget") === -1
  90670. && mesh.name.indexOf("torusTeleportation") === -1
  90671. && mesh.name.indexOf("laserPointer") === -1)) {
  90672. return _this.raySelectionPredicate(mesh);
  90673. }
  90674. return false;
  90675. };
  90676. this._interactionsEnabled = true;
  90677. }
  90678. };
  90679. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  90680. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  90681. if (this._floorMeshesCollection[i].id === mesh.id) {
  90682. return true;
  90683. }
  90684. }
  90685. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  90686. return true;
  90687. }
  90688. return false;
  90689. };
  90690. /**
  90691. * Adds a floor mesh to be used for teleportation.
  90692. * @param floorMesh the mesh to be used for teleportation.
  90693. */
  90694. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  90695. if (!this._floorMeshesCollection) {
  90696. return;
  90697. }
  90698. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  90699. return;
  90700. }
  90701. this._floorMeshesCollection.push(floorMesh);
  90702. };
  90703. /**
  90704. * Removes a floor mesh from being used for teleportation.
  90705. * @param floorMesh the mesh to be removed.
  90706. */
  90707. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  90708. if (!this._floorMeshesCollection) {
  90709. return;
  90710. }
  90711. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  90712. if (meshIndex !== -1) {
  90713. this._floorMeshesCollection.splice(meshIndex, 1);
  90714. }
  90715. };
  90716. /**
  90717. * Enables interactions and teleportation using the VR controllers and gaze.
  90718. * @param vrTeleportationOptions options to modify teleportation behavior.
  90719. */
  90720. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  90721. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  90722. if (!this._teleportationInitialized) {
  90723. this._teleportationRequested = true;
  90724. this.enableInteractions();
  90725. if (vrTeleportationOptions.floorMeshName) {
  90726. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  90727. }
  90728. if (vrTeleportationOptions.floorMeshes) {
  90729. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  90730. }
  90731. if (this.leftController != null) {
  90732. this._enableTeleportationOnController(this.leftController);
  90733. }
  90734. if (this.rightController != null) {
  90735. this._enableTeleportationOnController(this.rightController);
  90736. }
  90737. // Creates an image processing post process for the vignette not relying
  90738. // on the main scene configuration for image processing to reduce setup and spaces
  90739. // (gamma/linear) conflicts.
  90740. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  90741. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  90742. imageProcessingConfiguration.vignetteEnabled = true;
  90743. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  90744. this._webVRCamera.detachPostProcess(this._postProcessMove);
  90745. this._teleportationInitialized = true;
  90746. if (this._isDefaultTeleportationTarget) {
  90747. this._createTeleportationCircles();
  90748. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  90749. }
  90750. }
  90751. };
  90752. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  90753. var _this = this;
  90754. var controllerMesh = controller.webVRController.mesh;
  90755. if (controllerMesh) {
  90756. controller._interactionsEnabled = true;
  90757. controller._activatePointer();
  90758. if (this.webVROptions.laserToggle) {
  90759. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  90760. // Enabling / disabling laserPointer
  90761. if (_this._displayLaserPointer && stateObject.value === 1) {
  90762. if (controller._activePointer) {
  90763. controller._deactivatePointer();
  90764. }
  90765. else {
  90766. controller._activatePointer();
  90767. }
  90768. if (_this.displayGaze) {
  90769. controller._gazeTracker.isVisible = controller._activePointer;
  90770. }
  90771. }
  90772. });
  90773. }
  90774. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  90775. if (!controller._pointerDownOnMeshAsked) {
  90776. if (stateObject.value > _this._padSensibilityUp) {
  90777. controller._selectionPointerDown();
  90778. }
  90779. }
  90780. else if (stateObject.value < _this._padSensibilityDown) {
  90781. controller._selectionPointerUp();
  90782. }
  90783. });
  90784. }
  90785. };
  90786. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  90787. // Dont teleport if another gaze already requested teleportation
  90788. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  90789. return;
  90790. }
  90791. if (!gazer._teleportationRequestInitiated) {
  90792. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  90793. gazer._activatePointer();
  90794. gazer._teleportationRequestInitiated = true;
  90795. }
  90796. }
  90797. else {
  90798. // Listening to the proper controller values changes to confirm teleportation
  90799. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  90800. if (this._teleportActive) {
  90801. this._teleportCamera(this._haloCenter);
  90802. }
  90803. gazer._teleportationRequestInitiated = false;
  90804. }
  90805. }
  90806. };
  90807. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  90808. // Only rotate when user is not currently selecting a teleportation location
  90809. if (gazer._teleportationRequestInitiated) {
  90810. return;
  90811. }
  90812. if (!gazer._rotationLeftAsked) {
  90813. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  90814. gazer._rotationLeftAsked = true;
  90815. if (this._rotationAllowed) {
  90816. this._rotateCamera(false);
  90817. }
  90818. }
  90819. }
  90820. else {
  90821. if (stateObject.x > -this._padSensibilityDown) {
  90822. gazer._rotationLeftAsked = false;
  90823. }
  90824. }
  90825. if (!gazer._rotationRightAsked) {
  90826. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  90827. gazer._rotationRightAsked = true;
  90828. if (this._rotationAllowed) {
  90829. this._rotateCamera(true);
  90830. }
  90831. }
  90832. }
  90833. else {
  90834. if (stateObject.x < this._padSensibilityDown) {
  90835. gazer._rotationRightAsked = false;
  90836. }
  90837. }
  90838. };
  90839. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  90840. // Only teleport backwards when user is not currently selecting a teleportation location
  90841. if (gazer._teleportationRequestInitiated) {
  90842. return;
  90843. }
  90844. // Teleport backwards
  90845. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  90846. if (!gazer._teleportationBackRequestInitiated) {
  90847. if (!this.currentVRCamera) {
  90848. return;
  90849. }
  90850. // Get rotation and position of the current camera
  90851. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  90852. var position = this.currentVRCamera.position;
  90853. // If the camera has device position, use that instead
  90854. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  90855. rotation = this.currentVRCamera.deviceRotationQuaternion;
  90856. position = this.currentVRCamera.devicePosition;
  90857. }
  90858. // Get matrix with only the y rotation of the device rotation
  90859. rotation.toEulerAnglesToRef(this._workingVector);
  90860. this._workingVector.z = 0;
  90861. this._workingVector.x = 0;
  90862. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  90863. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  90864. // Rotate backwards ray by device rotation to cast at the ground behind the user
  90865. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  90866. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  90867. var ray = new BABYLON.Ray(position, this._workingVector);
  90868. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  90869. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  90870. this._teleportCamera(hit.pickedPoint);
  90871. }
  90872. gazer._teleportationBackRequestInitiated = true;
  90873. }
  90874. }
  90875. else {
  90876. gazer._teleportationBackRequestInitiated = false;
  90877. }
  90878. };
  90879. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  90880. var _this = this;
  90881. var controllerMesh = controller.webVRController.mesh;
  90882. if (controllerMesh) {
  90883. if (!controller._interactionsEnabled) {
  90884. this._enableInteractionOnController(controller);
  90885. }
  90886. controller._interactionsEnabled = true;
  90887. controller._teleportationEnabled = true;
  90888. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  90889. controller._dpadPressed = false;
  90890. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  90891. controller._dpadPressed = stateObject.pressed;
  90892. if (!controller._dpadPressed) {
  90893. controller._rotationLeftAsked = false;
  90894. controller._rotationRightAsked = false;
  90895. controller._teleportationBackRequestInitiated = false;
  90896. }
  90897. });
  90898. }
  90899. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  90900. if (_this.teleportationEnabled) {
  90901. _this._checkTeleportBackwards(stateObject, controller);
  90902. _this._checkTeleportWithRay(stateObject, controller);
  90903. }
  90904. _this._checkRotate(stateObject, controller);
  90905. });
  90906. }
  90907. };
  90908. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  90909. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  90910. this._teleportationTarget.isPickable = false;
  90911. var length = 512;
  90912. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  90913. dynamicTexture.hasAlpha = true;
  90914. var context = dynamicTexture.getContext();
  90915. var centerX = length / 2;
  90916. var centerY = length / 2;
  90917. var radius = 200;
  90918. context.beginPath();
  90919. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  90920. context.fillStyle = this._teleportationFillColor;
  90921. context.fill();
  90922. context.lineWidth = 10;
  90923. context.strokeStyle = this._teleportationBorderColor;
  90924. context.stroke();
  90925. context.closePath();
  90926. dynamicTexture.update();
  90927. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  90928. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  90929. this._teleportationTarget.material = teleportationCircleMaterial;
  90930. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  90931. torus.isPickable = false;
  90932. torus.parent = this._teleportationTarget;
  90933. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  90934. var keys = [];
  90935. keys.push({
  90936. frame: 0,
  90937. value: 0
  90938. });
  90939. keys.push({
  90940. frame: 30,
  90941. value: 0.4
  90942. });
  90943. keys.push({
  90944. frame: 60,
  90945. value: 0
  90946. });
  90947. animationInnerCircle.setKeys(keys);
  90948. var easingFunction = new BABYLON.SineEase();
  90949. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  90950. animationInnerCircle.setEasingFunction(easingFunction);
  90951. torus.animations = [];
  90952. torus.animations.push(animationInnerCircle);
  90953. this._scene.beginAnimation(torus, 0, 60, true);
  90954. this._hideTeleportationTarget();
  90955. };
  90956. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  90957. this._teleportActive = true;
  90958. if (this._teleportationInitialized) {
  90959. this._teleportationTarget.isVisible = true;
  90960. if (this._isDefaultTeleportationTarget) {
  90961. this._teleportationTarget.getChildren()[0].isVisible = true;
  90962. }
  90963. }
  90964. };
  90965. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  90966. this._teleportActive = false;
  90967. if (this._teleportationInitialized) {
  90968. this._teleportationTarget.isVisible = false;
  90969. if (this._isDefaultTeleportationTarget) {
  90970. this._teleportationTarget.getChildren()[0].isVisible = false;
  90971. }
  90972. }
  90973. };
  90974. VRExperienceHelper.prototype._rotateCamera = function (right) {
  90975. var _this = this;
  90976. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  90977. return;
  90978. }
  90979. if (right) {
  90980. this._rotationAngle++;
  90981. }
  90982. else {
  90983. this._rotationAngle--;
  90984. }
  90985. this.currentVRCamera.animations = [];
  90986. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  90987. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90988. var animationRotationKeys = [];
  90989. animationRotationKeys.push({
  90990. frame: 0,
  90991. value: this.currentVRCamera.rotationQuaternion
  90992. });
  90993. animationRotationKeys.push({
  90994. frame: 6,
  90995. value: target
  90996. });
  90997. animationRotation.setKeys(animationRotationKeys);
  90998. animationRotation.setEasingFunction(this._circleEase);
  90999. this.currentVRCamera.animations.push(animationRotation);
  91000. this._postProcessMove.animations = [];
  91001. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91002. var vignetteWeightKeys = [];
  91003. vignetteWeightKeys.push({
  91004. frame: 0,
  91005. value: 0
  91006. });
  91007. vignetteWeightKeys.push({
  91008. frame: 3,
  91009. value: 4
  91010. });
  91011. vignetteWeightKeys.push({
  91012. frame: 6,
  91013. value: 0
  91014. });
  91015. animationPP.setKeys(vignetteWeightKeys);
  91016. animationPP.setEasingFunction(this._circleEase);
  91017. this._postProcessMove.animations.push(animationPP);
  91018. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91019. var vignetteStretchKeys = [];
  91020. vignetteStretchKeys.push({
  91021. frame: 0,
  91022. value: 0
  91023. });
  91024. vignetteStretchKeys.push({
  91025. frame: 3,
  91026. value: 10
  91027. });
  91028. vignetteStretchKeys.push({
  91029. frame: 6,
  91030. value: 0
  91031. });
  91032. animationPP2.setKeys(vignetteStretchKeys);
  91033. animationPP2.setEasingFunction(this._circleEase);
  91034. this._postProcessMove.animations.push(animationPP2);
  91035. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  91036. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  91037. this._postProcessMove.samples = 4;
  91038. this._webVRCamera.attachPostProcess(this._postProcessMove);
  91039. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  91040. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  91041. });
  91042. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  91043. };
  91044. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  91045. if (hit.pickedPoint) {
  91046. if (gazer._teleportationRequestInitiated) {
  91047. this._displayTeleportationTarget();
  91048. this._haloCenter.copyFrom(hit.pickedPoint);
  91049. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  91050. }
  91051. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  91052. if (pickNormal) {
  91053. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  91054. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  91055. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  91056. }
  91057. this._teleportationTarget.position.y += 0.1;
  91058. }
  91059. };
  91060. VRExperienceHelper.prototype._teleportCamera = function (location) {
  91061. var _this = this;
  91062. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  91063. return;
  91064. }
  91065. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  91066. // offset of the headset from the anchor.
  91067. if (this.webVRCamera.leftCamera) {
  91068. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  91069. this._workingVector.subtractInPlace(this.webVRCamera.position);
  91070. location.subtractToRef(this._workingVector, this._workingVector);
  91071. }
  91072. else {
  91073. this._workingVector.copyFrom(location);
  91074. }
  91075. // Add height to account for user's height offset
  91076. if (this.isInVRMode) {
  91077. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  91078. }
  91079. else {
  91080. this._workingVector.y += this._defaultHeight;
  91081. }
  91082. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  91083. // Create animation from the camera's position to the new location
  91084. this.currentVRCamera.animations = [];
  91085. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91086. var animationCameraTeleportationKeys = [{
  91087. frame: 0,
  91088. value: this.currentVRCamera.position
  91089. },
  91090. {
  91091. frame: 11,
  91092. value: this._workingVector
  91093. }
  91094. ];
  91095. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  91096. animationCameraTeleportation.setEasingFunction(this._circleEase);
  91097. this.currentVRCamera.animations.push(animationCameraTeleportation);
  91098. this._postProcessMove.animations = [];
  91099. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91100. var vignetteWeightKeys = [];
  91101. vignetteWeightKeys.push({
  91102. frame: 0,
  91103. value: 0
  91104. });
  91105. vignetteWeightKeys.push({
  91106. frame: 5,
  91107. value: 8
  91108. });
  91109. vignetteWeightKeys.push({
  91110. frame: 11,
  91111. value: 0
  91112. });
  91113. animationPP.setKeys(vignetteWeightKeys);
  91114. this._postProcessMove.animations.push(animationPP);
  91115. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91116. var vignetteStretchKeys = [];
  91117. vignetteStretchKeys.push({
  91118. frame: 0,
  91119. value: 0
  91120. });
  91121. vignetteStretchKeys.push({
  91122. frame: 5,
  91123. value: 10
  91124. });
  91125. vignetteStretchKeys.push({
  91126. frame: 11,
  91127. value: 0
  91128. });
  91129. animationPP2.setKeys(vignetteStretchKeys);
  91130. this._postProcessMove.animations.push(animationPP2);
  91131. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  91132. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  91133. this._webVRCamera.attachPostProcess(this._postProcessMove);
  91134. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  91135. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  91136. });
  91137. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  91138. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  91139. });
  91140. this._hideTeleportationTarget();
  91141. };
  91142. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  91143. if (normal) {
  91144. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  91145. if (angle < Math.PI / 2) {
  91146. normal.scaleInPlace(-1);
  91147. }
  91148. }
  91149. return normal;
  91150. };
  91151. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  91152. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  91153. return;
  91154. }
  91155. var ray = gazer._getForwardRay(this._rayLength);
  91156. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  91157. if (hit) {
  91158. // Populate the contrllers mesh that can be used for drag/drop
  91159. if (gazer._laserPointer) {
  91160. hit.originMesh = gazer._laserPointer.parent;
  91161. }
  91162. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  91163. }
  91164. gazer._currentHit = hit;
  91165. // Moving the gazeTracker on the mesh face targetted
  91166. if (hit && hit.pickedPoint) {
  91167. if (this._displayGaze) {
  91168. var multiplier = 1;
  91169. gazer._gazeTracker.isVisible = true;
  91170. if (gazer._isActionableMesh) {
  91171. multiplier = 3;
  91172. }
  91173. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  91174. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  91175. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  91176. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  91177. // To avoid z-fighting
  91178. var deltaFighting = 0.002;
  91179. if (pickNormal) {
  91180. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  91181. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  91182. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  91183. }
  91184. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  91185. if (gazer._gazeTracker.position.x < 0) {
  91186. gazer._gazeTracker.position.x += deltaFighting;
  91187. }
  91188. else {
  91189. gazer._gazeTracker.position.x -= deltaFighting;
  91190. }
  91191. if (gazer._gazeTracker.position.y < 0) {
  91192. gazer._gazeTracker.position.y += deltaFighting;
  91193. }
  91194. else {
  91195. gazer._gazeTracker.position.y -= deltaFighting;
  91196. }
  91197. if (gazer._gazeTracker.position.z < 0) {
  91198. gazer._gazeTracker.position.z += deltaFighting;
  91199. }
  91200. else {
  91201. gazer._gazeTracker.position.z -= deltaFighting;
  91202. }
  91203. }
  91204. // Changing the size of the laser pointer based on the distance from the targetted point
  91205. gazer._updatePointerDistance(hit.distance);
  91206. }
  91207. else {
  91208. gazer._updatePointerDistance();
  91209. gazer._gazeTracker.isVisible = false;
  91210. }
  91211. if (hit && hit.pickedMesh) {
  91212. // The object selected is the floor, we're in a teleportation scenario
  91213. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  91214. // Moving the teleportation area to this targetted point
  91215. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  91216. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  91217. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91218. }
  91219. gazer._currentMeshSelected = null;
  91220. if (gazer._teleportationRequestInitiated) {
  91221. this._moveTeleportationSelectorTo(hit, gazer, ray);
  91222. }
  91223. return;
  91224. }
  91225. // If not, we're in a selection scenario
  91226. //this._teleportationAllowed = false;
  91227. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  91228. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  91229. this.onNewMeshPicked.notifyObservers(hit);
  91230. gazer._currentMeshSelected = hit.pickedMesh;
  91231. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  91232. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  91233. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  91234. gazer._isActionableMesh = true;
  91235. }
  91236. else {
  91237. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91238. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91239. gazer._isActionableMesh = false;
  91240. }
  91241. try {
  91242. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  91243. }
  91244. catch (err) {
  91245. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  91246. }
  91247. }
  91248. else {
  91249. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91250. gazer._currentMeshSelected = null;
  91251. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91252. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91253. }
  91254. }
  91255. }
  91256. else {
  91257. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91258. gazer._currentMeshSelected = null;
  91259. //this._teleportationAllowed = false;
  91260. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91261. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91262. }
  91263. };
  91264. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  91265. if (mesh) {
  91266. this.onSelectedMeshUnselected.notifyObservers(mesh);
  91267. }
  91268. };
  91269. /**
  91270. * Sets the color of the laser ray from the vr controllers.
  91271. * @param color new color for the ray.
  91272. */
  91273. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  91274. if (this.leftController) {
  91275. this.leftController._setLaserPointerColor(color);
  91276. }
  91277. if (this.rightController) {
  91278. this.rightController._setLaserPointerColor(color);
  91279. }
  91280. };
  91281. /**
  91282. * Sets the color of the ray from the vr headsets gaze.
  91283. * @param color new color for the ray.
  91284. */
  91285. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  91286. if (!this._cameraGazer._gazeTracker.material) {
  91287. return;
  91288. }
  91289. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  91290. if (this.leftController) {
  91291. this.leftController._gazeTracker.material.emissiveColor = color;
  91292. }
  91293. if (this.rightController) {
  91294. this.rightController._gazeTracker.material.emissiveColor = color;
  91295. }
  91296. };
  91297. /**
  91298. * Exits VR and disposes of the vr experience helper
  91299. */
  91300. VRExperienceHelper.prototype.dispose = function () {
  91301. if (this.isInVRMode) {
  91302. this.exitVR();
  91303. }
  91304. if (this._postProcessMove) {
  91305. this._postProcessMove.dispose();
  91306. }
  91307. if (this._webVRCamera) {
  91308. this._webVRCamera.dispose();
  91309. }
  91310. if (this._vrDeviceOrientationCamera) {
  91311. this._vrDeviceOrientationCamera.dispose();
  91312. }
  91313. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  91314. document.body.removeChild(this._btnVR);
  91315. }
  91316. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  91317. this._deviceOrientationCamera.dispose();
  91318. }
  91319. if (this._cameraGazer) {
  91320. this._cameraGazer.dispose();
  91321. }
  91322. if (this.leftController) {
  91323. this.leftController.dispose();
  91324. }
  91325. if (this.rightController) {
  91326. this.rightController.dispose();
  91327. }
  91328. if (this._teleportationTarget) {
  91329. this._teleportationTarget.dispose();
  91330. }
  91331. this._floorMeshesCollection = [];
  91332. document.removeEventListener("keydown", this._onKeyDown);
  91333. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91334. window.removeEventListener("resize", this._onResize);
  91335. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  91336. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  91337. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  91338. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  91339. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  91340. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  91341. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  91342. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91343. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  91344. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  91345. this._scene.unregisterBeforeRender(this.beforeRender);
  91346. };
  91347. /**
  91348. * Gets the name of the VRExperienceHelper class
  91349. * @returns "VRExperienceHelper"
  91350. */
  91351. VRExperienceHelper.prototype.getClassName = function () {
  91352. return "VRExperienceHelper";
  91353. };
  91354. return VRExperienceHelper;
  91355. }());
  91356. BABYLON.VRExperienceHelper = VRExperienceHelper;
  91357. })(BABYLON || (BABYLON = {}));
  91358. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  91359. // Mainly based on these 2 articles :
  91360. // 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
  91361. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  91362. var BABYLON;
  91363. (function (BABYLON) {
  91364. /**
  91365. * Defines the potential axis of a Joystick
  91366. */
  91367. var JoystickAxis;
  91368. (function (JoystickAxis) {
  91369. /** X axis */
  91370. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  91371. /** Y axis */
  91372. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  91373. /** Z axis */
  91374. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  91375. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  91376. /**
  91377. * Class used to define virtual joystick (used in touch mode)
  91378. */
  91379. var VirtualJoystick = /** @class */ (function () {
  91380. /**
  91381. * Creates a new virtual joystick
  91382. * @param leftJoystick defines that the joystick is for left hand (false by default)
  91383. */
  91384. function VirtualJoystick(leftJoystick) {
  91385. var _this = this;
  91386. if (leftJoystick) {
  91387. this._leftJoystick = true;
  91388. }
  91389. else {
  91390. this._leftJoystick = false;
  91391. }
  91392. VirtualJoystick._globalJoystickIndex++;
  91393. // By default left & right arrow keys are moving the X
  91394. // and up & down keys are moving the Y
  91395. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  91396. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  91397. this.reverseLeftRight = false;
  91398. this.reverseUpDown = false;
  91399. // collections of pointers
  91400. this._touches = new BABYLON.StringDictionary();
  91401. this.deltaPosition = BABYLON.Vector3.Zero();
  91402. this._joystickSensibility = 25;
  91403. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  91404. this._onResize = function (evt) {
  91405. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  91406. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  91407. if (VirtualJoystick.vjCanvas) {
  91408. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  91409. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  91410. }
  91411. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  91412. };
  91413. // injecting a canvas element on top of the canvas 3D game
  91414. if (!VirtualJoystick.vjCanvas) {
  91415. window.addEventListener("resize", this._onResize, false);
  91416. VirtualJoystick.vjCanvas = document.createElement("canvas");
  91417. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  91418. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  91419. VirtualJoystick.vjCanvas.width = window.innerWidth;
  91420. VirtualJoystick.vjCanvas.height = window.innerHeight;
  91421. VirtualJoystick.vjCanvas.style.width = "100%";
  91422. VirtualJoystick.vjCanvas.style.height = "100%";
  91423. VirtualJoystick.vjCanvas.style.position = "absolute";
  91424. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  91425. VirtualJoystick.vjCanvas.style.top = "0px";
  91426. VirtualJoystick.vjCanvas.style.left = "0px";
  91427. VirtualJoystick.vjCanvas.style.zIndex = "5";
  91428. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  91429. // Support for jQuery PEP polyfill
  91430. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  91431. var context = VirtualJoystick.vjCanvas.getContext('2d');
  91432. if (!context) {
  91433. throw new Error("Unable to create canvas for virtual joystick");
  91434. }
  91435. VirtualJoystick.vjCanvasContext = context;
  91436. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  91437. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  91438. document.body.appendChild(VirtualJoystick.vjCanvas);
  91439. }
  91440. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  91441. this.pressed = false;
  91442. // default joystick color
  91443. this._joystickColor = "cyan";
  91444. this._joystickPointerID = -1;
  91445. // current joystick position
  91446. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  91447. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  91448. // origin joystick position
  91449. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  91450. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  91451. this._onPointerDownHandlerRef = function (evt) {
  91452. _this._onPointerDown(evt);
  91453. };
  91454. this._onPointerMoveHandlerRef = function (evt) {
  91455. _this._onPointerMove(evt);
  91456. };
  91457. this._onPointerUpHandlerRef = function (evt) {
  91458. _this._onPointerUp(evt);
  91459. };
  91460. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  91461. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  91462. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  91463. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  91464. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  91465. evt.preventDefault(); // Disables system menu
  91466. }, false);
  91467. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  91468. }
  91469. /**
  91470. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  91471. * @param newJoystickSensibility defines the new sensibility
  91472. */
  91473. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  91474. this._joystickSensibility = newJoystickSensibility;
  91475. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  91476. };
  91477. VirtualJoystick.prototype._onPointerDown = function (e) {
  91478. var positionOnScreenCondition;
  91479. e.preventDefault();
  91480. if (this._leftJoystick === true) {
  91481. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  91482. }
  91483. else {
  91484. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  91485. }
  91486. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  91487. // First contact will be dedicated to the virtual joystick
  91488. this._joystickPointerID = e.pointerId;
  91489. this._joystickPointerStartPos.x = e.clientX;
  91490. this._joystickPointerStartPos.y = e.clientY;
  91491. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  91492. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  91493. this._deltaJoystickVector.x = 0;
  91494. this._deltaJoystickVector.y = 0;
  91495. this.pressed = true;
  91496. this._touches.add(e.pointerId.toString(), e);
  91497. }
  91498. else {
  91499. // You can only trigger the action buttons with a joystick declared
  91500. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  91501. this._action();
  91502. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  91503. }
  91504. }
  91505. };
  91506. VirtualJoystick.prototype._onPointerMove = function (e) {
  91507. // If the current pointer is the one associated to the joystick (first touch contact)
  91508. if (this._joystickPointerID == e.pointerId) {
  91509. this._joystickPointerPos.x = e.clientX;
  91510. this._joystickPointerPos.y = e.clientY;
  91511. this._deltaJoystickVector = this._joystickPointerPos.clone();
  91512. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  91513. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  91514. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  91515. switch (this._axisTargetedByLeftAndRight) {
  91516. case JoystickAxis.X:
  91517. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  91518. break;
  91519. case JoystickAxis.Y:
  91520. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  91521. break;
  91522. case JoystickAxis.Z:
  91523. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  91524. break;
  91525. }
  91526. var directionUpDown = this.reverseUpDown ? 1 : -1;
  91527. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  91528. switch (this._axisTargetedByUpAndDown) {
  91529. case JoystickAxis.X:
  91530. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  91531. break;
  91532. case JoystickAxis.Y:
  91533. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  91534. break;
  91535. case JoystickAxis.Z:
  91536. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  91537. break;
  91538. }
  91539. }
  91540. else {
  91541. var data = this._touches.get(e.pointerId.toString());
  91542. if (data) {
  91543. data.x = e.clientX;
  91544. data.y = e.clientY;
  91545. }
  91546. }
  91547. };
  91548. VirtualJoystick.prototype._onPointerUp = function (e) {
  91549. if (this._joystickPointerID == e.pointerId) {
  91550. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  91551. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  91552. this._joystickPointerID = -1;
  91553. this.pressed = false;
  91554. }
  91555. else {
  91556. var touch = this._touches.get(e.pointerId.toString());
  91557. if (touch) {
  91558. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  91559. }
  91560. }
  91561. this._deltaJoystickVector.x = 0;
  91562. this._deltaJoystickVector.y = 0;
  91563. this._touches.remove(e.pointerId.toString());
  91564. };
  91565. /**
  91566. * Change the color of the virtual joystick
  91567. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  91568. */
  91569. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  91570. this._joystickColor = newColor;
  91571. };
  91572. /**
  91573. * Defines a callback to call when the joystick is touched
  91574. * @param action defines the callback
  91575. */
  91576. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  91577. this._action = action;
  91578. };
  91579. /**
  91580. * Defines which axis you'd like to control for left & right
  91581. * @param axis defines the axis to use
  91582. */
  91583. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  91584. switch (axis) {
  91585. case JoystickAxis.X:
  91586. case JoystickAxis.Y:
  91587. case JoystickAxis.Z:
  91588. this._axisTargetedByLeftAndRight = axis;
  91589. break;
  91590. default:
  91591. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  91592. break;
  91593. }
  91594. };
  91595. /**
  91596. * Defines which axis you'd like to control for up & down
  91597. * @param axis defines the axis to use
  91598. */
  91599. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  91600. switch (axis) {
  91601. case JoystickAxis.X:
  91602. case JoystickAxis.Y:
  91603. case JoystickAxis.Z:
  91604. this._axisTargetedByUpAndDown = axis;
  91605. break;
  91606. default:
  91607. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  91608. break;
  91609. }
  91610. };
  91611. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  91612. var _this = this;
  91613. if (this.pressed) {
  91614. this._touches.forEach(function (key, touch) {
  91615. if (touch.pointerId === _this._joystickPointerID) {
  91616. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  91617. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  91618. VirtualJoystick.vjCanvasContext.beginPath();
  91619. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  91620. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91621. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  91622. VirtualJoystick.vjCanvasContext.stroke();
  91623. VirtualJoystick.vjCanvasContext.closePath();
  91624. VirtualJoystick.vjCanvasContext.beginPath();
  91625. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91626. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  91627. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  91628. VirtualJoystick.vjCanvasContext.stroke();
  91629. VirtualJoystick.vjCanvasContext.closePath();
  91630. VirtualJoystick.vjCanvasContext.beginPath();
  91631. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91632. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  91633. VirtualJoystick.vjCanvasContext.stroke();
  91634. VirtualJoystick.vjCanvasContext.closePath();
  91635. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  91636. }
  91637. else {
  91638. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  91639. VirtualJoystick.vjCanvasContext.beginPath();
  91640. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  91641. VirtualJoystick.vjCanvasContext.beginPath();
  91642. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  91643. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  91644. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  91645. VirtualJoystick.vjCanvasContext.stroke();
  91646. VirtualJoystick.vjCanvasContext.closePath();
  91647. touch.prevX = touch.x;
  91648. touch.prevY = touch.y;
  91649. }
  91650. ;
  91651. });
  91652. }
  91653. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  91654. };
  91655. /**
  91656. * Release internal HTML canvas
  91657. */
  91658. VirtualJoystick.prototype.releaseCanvas = function () {
  91659. if (VirtualJoystick.vjCanvas) {
  91660. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  91661. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  91662. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  91663. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  91664. window.removeEventListener("resize", this._onResize);
  91665. document.body.removeChild(VirtualJoystick.vjCanvas);
  91666. VirtualJoystick.vjCanvas = null;
  91667. }
  91668. };
  91669. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  91670. VirtualJoystick._globalJoystickIndex = 0;
  91671. return VirtualJoystick;
  91672. }());
  91673. BABYLON.VirtualJoystick = VirtualJoystick;
  91674. })(BABYLON || (BABYLON = {}));
  91675. //# sourceMappingURL=babylon.virtualJoystick.js.map
  91676. var BABYLON;
  91677. (function (BABYLON) {
  91678. // We're mainly based on the logic defined into the FreeCamera code
  91679. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  91680. __extends(VirtualJoysticksCamera, _super);
  91681. function VirtualJoysticksCamera(name, position, scene) {
  91682. var _this = _super.call(this, name, position, scene) || this;
  91683. _this.inputs.addVirtualJoystick();
  91684. return _this;
  91685. }
  91686. VirtualJoysticksCamera.prototype.getClassName = function () {
  91687. return "VirtualJoysticksCamera";
  91688. };
  91689. return VirtualJoysticksCamera;
  91690. }(BABYLON.FreeCamera));
  91691. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  91692. })(BABYLON || (BABYLON = {}));
  91693. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  91694. var BABYLON;
  91695. (function (BABYLON) {
  91696. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  91697. function FreeCameraVirtualJoystickInput() {
  91698. }
  91699. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  91700. return this._leftjoystick;
  91701. };
  91702. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  91703. return this._rightjoystick;
  91704. };
  91705. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  91706. if (this._leftjoystick) {
  91707. var camera = this.camera;
  91708. var speed = camera._computeLocalCameraSpeed() * 50;
  91709. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  91710. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  91711. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  91712. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  91713. if (!this._leftjoystick.pressed) {
  91714. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  91715. }
  91716. if (!this._rightjoystick.pressed) {
  91717. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  91718. }
  91719. }
  91720. };
  91721. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  91722. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  91723. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  91724. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  91725. this._leftjoystick.setJoystickSensibility(0.15);
  91726. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  91727. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  91728. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  91729. this._rightjoystick.reverseUpDown = true;
  91730. this._rightjoystick.setJoystickSensibility(0.05);
  91731. this._rightjoystick.setJoystickColor("yellow");
  91732. };
  91733. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  91734. this._leftjoystick.releaseCanvas();
  91735. this._rightjoystick.releaseCanvas();
  91736. };
  91737. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  91738. return "FreeCameraVirtualJoystickInput";
  91739. };
  91740. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  91741. return "virtualJoystick";
  91742. };
  91743. return FreeCameraVirtualJoystickInput;
  91744. }());
  91745. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  91746. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  91747. })(BABYLON || (BABYLON = {}));
  91748. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  91749. var BABYLON;
  91750. (function (BABYLON) {
  91751. var SimplificationSettings = /** @class */ (function () {
  91752. function SimplificationSettings(quality, distance, optimizeMesh) {
  91753. this.quality = quality;
  91754. this.distance = distance;
  91755. this.optimizeMesh = optimizeMesh;
  91756. }
  91757. return SimplificationSettings;
  91758. }());
  91759. BABYLON.SimplificationSettings = SimplificationSettings;
  91760. var SimplificationQueue = /** @class */ (function () {
  91761. function SimplificationQueue() {
  91762. this.running = false;
  91763. this._simplificationArray = [];
  91764. }
  91765. SimplificationQueue.prototype.addTask = function (task) {
  91766. this._simplificationArray.push(task);
  91767. };
  91768. SimplificationQueue.prototype.executeNext = function () {
  91769. var task = this._simplificationArray.pop();
  91770. if (task) {
  91771. this.running = true;
  91772. this.runSimplification(task);
  91773. }
  91774. else {
  91775. this.running = false;
  91776. }
  91777. };
  91778. SimplificationQueue.prototype.runSimplification = function (task) {
  91779. var _this = this;
  91780. if (task.parallelProcessing) {
  91781. //parallel simplifier
  91782. task.settings.forEach(function (setting) {
  91783. var simplifier = _this.getSimplifier(task);
  91784. simplifier.simplify(setting, function (newMesh) {
  91785. task.mesh.addLODLevel(setting.distance, newMesh);
  91786. newMesh.isVisible = true;
  91787. //check if it is the last
  91788. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  91789. //all done, run the success callback.
  91790. task.successCallback();
  91791. }
  91792. _this.executeNext();
  91793. });
  91794. });
  91795. }
  91796. else {
  91797. //single simplifier.
  91798. var simplifier = this.getSimplifier(task);
  91799. var runDecimation = function (setting, callback) {
  91800. simplifier.simplify(setting, function (newMesh) {
  91801. task.mesh.addLODLevel(setting.distance, newMesh);
  91802. newMesh.isVisible = true;
  91803. //run the next quality level
  91804. callback();
  91805. });
  91806. };
  91807. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  91808. runDecimation(task.settings[loop.index], function () {
  91809. loop.executeNext();
  91810. });
  91811. }, function () {
  91812. //execution ended, run the success callback.
  91813. if (task.successCallback) {
  91814. task.successCallback();
  91815. }
  91816. _this.executeNext();
  91817. });
  91818. }
  91819. };
  91820. SimplificationQueue.prototype.getSimplifier = function (task) {
  91821. switch (task.simplificationType) {
  91822. case SimplificationType.QUADRATIC:
  91823. default:
  91824. return new QuadraticErrorSimplification(task.mesh);
  91825. }
  91826. };
  91827. return SimplificationQueue;
  91828. }());
  91829. BABYLON.SimplificationQueue = SimplificationQueue;
  91830. /**
  91831. * The implemented types of simplification
  91832. * At the moment only Quadratic Error Decimation is implemented
  91833. */
  91834. var SimplificationType;
  91835. (function (SimplificationType) {
  91836. /** Quadratic error decimation */
  91837. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  91838. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  91839. var DecimationTriangle = /** @class */ (function () {
  91840. function DecimationTriangle(vertices) {
  91841. this.vertices = vertices;
  91842. this.error = new Array(4);
  91843. this.deleted = false;
  91844. this.isDirty = false;
  91845. this.deletePending = false;
  91846. this.borderFactor = 0;
  91847. }
  91848. return DecimationTriangle;
  91849. }());
  91850. BABYLON.DecimationTriangle = DecimationTriangle;
  91851. var DecimationVertex = /** @class */ (function () {
  91852. function DecimationVertex(position, id) {
  91853. this.position = position;
  91854. this.id = id;
  91855. this.isBorder = true;
  91856. this.q = new QuadraticMatrix();
  91857. this.triangleCount = 0;
  91858. this.triangleStart = 0;
  91859. this.originalOffsets = [];
  91860. }
  91861. DecimationVertex.prototype.updatePosition = function (newPosition) {
  91862. this.position.copyFrom(newPosition);
  91863. };
  91864. return DecimationVertex;
  91865. }());
  91866. BABYLON.DecimationVertex = DecimationVertex;
  91867. var QuadraticMatrix = /** @class */ (function () {
  91868. function QuadraticMatrix(data) {
  91869. this.data = new Array(10);
  91870. for (var i = 0; i < 10; ++i) {
  91871. if (data && data[i]) {
  91872. this.data[i] = data[i];
  91873. }
  91874. else {
  91875. this.data[i] = 0;
  91876. }
  91877. }
  91878. }
  91879. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  91880. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  91881. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  91882. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  91883. return det;
  91884. };
  91885. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  91886. for (var i = 0; i < 10; ++i) {
  91887. this.data[i] += matrix.data[i];
  91888. }
  91889. };
  91890. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  91891. for (var i = 0; i < 10; ++i) {
  91892. this.data[i] += data[i];
  91893. }
  91894. };
  91895. QuadraticMatrix.prototype.add = function (matrix) {
  91896. var m = new QuadraticMatrix();
  91897. for (var i = 0; i < 10; ++i) {
  91898. m.data[i] = this.data[i] + matrix.data[i];
  91899. }
  91900. return m;
  91901. };
  91902. QuadraticMatrix.FromData = function (a, b, c, d) {
  91903. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  91904. };
  91905. //returning an array to avoid garbage collection
  91906. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  91907. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  91908. };
  91909. return QuadraticMatrix;
  91910. }());
  91911. BABYLON.QuadraticMatrix = QuadraticMatrix;
  91912. var Reference = /** @class */ (function () {
  91913. function Reference(vertexId, triangleId) {
  91914. this.vertexId = vertexId;
  91915. this.triangleId = triangleId;
  91916. }
  91917. return Reference;
  91918. }());
  91919. BABYLON.Reference = Reference;
  91920. /**
  91921. * An implementation of the Quadratic Error simplification algorithm.
  91922. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  91923. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  91924. * @author RaananW
  91925. */
  91926. var QuadraticErrorSimplification = /** @class */ (function () {
  91927. function QuadraticErrorSimplification(_mesh) {
  91928. this._mesh = _mesh;
  91929. this.syncIterations = 5000;
  91930. this.aggressiveness = 7;
  91931. this.decimationIterations = 100;
  91932. this.boundingBoxEpsilon = BABYLON.Epsilon;
  91933. }
  91934. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  91935. var _this = this;
  91936. this.initDecimatedMesh();
  91937. //iterating through the submeshes array, one after the other.
  91938. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  91939. _this.initWithMesh(loop.index, function () {
  91940. _this.runDecimation(settings, loop.index, function () {
  91941. loop.executeNext();
  91942. });
  91943. }, settings.optimizeMesh);
  91944. }, function () {
  91945. setTimeout(function () {
  91946. successCallback(_this._reconstructedMesh);
  91947. }, 0);
  91948. });
  91949. };
  91950. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  91951. var _this = this;
  91952. var targetCount = ~~(this.triangles.length * settings.quality);
  91953. var deletedTriangles = 0;
  91954. var triangleCount = this.triangles.length;
  91955. var iterationFunction = function (iteration, callback) {
  91956. setTimeout(function () {
  91957. if (iteration % 5 === 0) {
  91958. _this.updateMesh(iteration === 0);
  91959. }
  91960. for (var i = 0; i < _this.triangles.length; ++i) {
  91961. _this.triangles[i].isDirty = false;
  91962. }
  91963. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  91964. var trianglesIterator = function (i) {
  91965. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  91966. var t = _this.triangles[tIdx];
  91967. if (!t)
  91968. return;
  91969. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  91970. return;
  91971. }
  91972. for (var j = 0; j < 3; ++j) {
  91973. if (t.error[j] < threshold) {
  91974. var deleted0 = [];
  91975. var deleted1 = [];
  91976. var v0 = t.vertices[j];
  91977. var v1 = t.vertices[(j + 1) % 3];
  91978. if (v0.isBorder || v1.isBorder)
  91979. continue;
  91980. var p = BABYLON.Vector3.Zero();
  91981. var n = BABYLON.Vector3.Zero();
  91982. var uv = BABYLON.Vector2.Zero();
  91983. var color = new BABYLON.Color4(0, 0, 0, 1);
  91984. _this.calculateError(v0, v1, p, n, uv, color);
  91985. var delTr = new Array();
  91986. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  91987. continue;
  91988. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  91989. continue;
  91990. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  91991. continue;
  91992. var uniqueArray = new Array();
  91993. delTr.forEach(function (deletedT) {
  91994. if (uniqueArray.indexOf(deletedT) === -1) {
  91995. deletedT.deletePending = true;
  91996. uniqueArray.push(deletedT);
  91997. }
  91998. });
  91999. if (uniqueArray.length % 2 !== 0) {
  92000. continue;
  92001. }
  92002. v0.q = v1.q.add(v0.q);
  92003. v0.updatePosition(p);
  92004. var tStart = _this.references.length;
  92005. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  92006. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  92007. var tCount = _this.references.length - tStart;
  92008. if (tCount <= v0.triangleCount) {
  92009. if (tCount) {
  92010. for (var c = 0; c < tCount; c++) {
  92011. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  92012. }
  92013. }
  92014. }
  92015. else {
  92016. v0.triangleStart = tStart;
  92017. }
  92018. v0.triangleCount = tCount;
  92019. break;
  92020. }
  92021. }
  92022. };
  92023. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  92024. }, 0);
  92025. };
  92026. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  92027. if (triangleCount - deletedTriangles <= targetCount)
  92028. loop.breakLoop();
  92029. else {
  92030. iterationFunction(loop.index, function () {
  92031. loop.executeNext();
  92032. });
  92033. }
  92034. }, function () {
  92035. setTimeout(function () {
  92036. //reconstruct this part of the mesh
  92037. _this.reconstructMesh(submeshIndex);
  92038. successCallback();
  92039. }, 0);
  92040. });
  92041. };
  92042. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  92043. var _this = this;
  92044. this.vertices = [];
  92045. this.triangles = [];
  92046. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  92047. var indices = this._mesh.getIndices();
  92048. var submesh = this._mesh.subMeshes[submeshIndex];
  92049. var findInVertices = function (positionToSearch) {
  92050. if (optimizeMesh) {
  92051. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  92052. if (_this.vertices[ii].position.equals(positionToSearch)) {
  92053. return _this.vertices[ii];
  92054. }
  92055. }
  92056. }
  92057. return null;
  92058. };
  92059. var vertexReferences = [];
  92060. var vertexInit = function (i) {
  92061. if (!positionData) {
  92062. return;
  92063. }
  92064. var offset = i + submesh.verticesStart;
  92065. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  92066. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  92067. vertex.originalOffsets.push(offset);
  92068. if (vertex.id === _this.vertices.length) {
  92069. _this.vertices.push(vertex);
  92070. }
  92071. vertexReferences.push(vertex.id);
  92072. };
  92073. //var totalVertices = mesh.getTotalVertices();
  92074. var totalVertices = submesh.verticesCount;
  92075. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  92076. var indicesInit = function (i) {
  92077. if (!indices) {
  92078. return;
  92079. }
  92080. var offset = (submesh.indexStart / 3) + i;
  92081. var pos = (offset * 3);
  92082. var i0 = indices[pos + 0];
  92083. var i1 = indices[pos + 1];
  92084. var i2 = indices[pos + 2];
  92085. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  92086. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  92087. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  92088. var triangle = new DecimationTriangle([v0, v1, v2]);
  92089. triangle.originalOffset = pos;
  92090. _this.triangles.push(triangle);
  92091. };
  92092. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  92093. _this.init(callback);
  92094. });
  92095. });
  92096. };
  92097. QuadraticErrorSimplification.prototype.init = function (callback) {
  92098. var _this = this;
  92099. var triangleInit1 = function (i) {
  92100. var t = _this.triangles[i];
  92101. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  92102. for (var j = 0; j < 3; j++) {
  92103. 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))));
  92104. }
  92105. };
  92106. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  92107. var triangleInit2 = function (i) {
  92108. var t = _this.triangles[i];
  92109. for (var j = 0; j < 3; ++j) {
  92110. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  92111. }
  92112. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  92113. };
  92114. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  92115. callback();
  92116. });
  92117. });
  92118. };
  92119. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  92120. var newTriangles = [];
  92121. var i;
  92122. for (i = 0; i < this.vertices.length; ++i) {
  92123. this.vertices[i].triangleCount = 0;
  92124. }
  92125. var t;
  92126. var j;
  92127. for (i = 0; i < this.triangles.length; ++i) {
  92128. if (!this.triangles[i].deleted) {
  92129. t = this.triangles[i];
  92130. for (j = 0; j < 3; ++j) {
  92131. t.vertices[j].triangleCount = 1;
  92132. }
  92133. newTriangles.push(t);
  92134. }
  92135. }
  92136. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  92137. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  92138. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  92139. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  92140. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  92141. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  92142. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  92143. var vertexCount = 0;
  92144. for (i = 0; i < this.vertices.length; ++i) {
  92145. var vertex = this.vertices[i];
  92146. vertex.id = vertexCount;
  92147. if (vertex.triangleCount) {
  92148. vertex.originalOffsets.forEach(function (originalOffset) {
  92149. if (!normalData) {
  92150. return;
  92151. }
  92152. newPositionData.push(vertex.position.x);
  92153. newPositionData.push(vertex.position.y);
  92154. newPositionData.push(vertex.position.z);
  92155. newNormalData.push(normalData[originalOffset * 3]);
  92156. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  92157. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  92158. if (uvs && uvs.length) {
  92159. newUVsData.push(uvs[(originalOffset * 2)]);
  92160. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  92161. }
  92162. else if (colorsData && colorsData.length) {
  92163. newColorsData.push(colorsData[(originalOffset * 4)]);
  92164. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  92165. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  92166. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  92167. }
  92168. ++vertexCount;
  92169. });
  92170. }
  92171. }
  92172. var startingIndex = this._reconstructedMesh.getTotalIndices();
  92173. var startingVertex = this._reconstructedMesh.getTotalVertices();
  92174. var submeshesArray = this._reconstructedMesh.subMeshes;
  92175. this._reconstructedMesh.subMeshes = [];
  92176. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  92177. var originalIndices = this._mesh.getIndices();
  92178. for (i = 0; i < newTriangles.length; ++i) {
  92179. t = newTriangles[i]; //now get the new referencing point for each vertex
  92180. [0, 1, 2].forEach(function (idx) {
  92181. var id = originalIndices[t.originalOffset + idx];
  92182. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  92183. if (offset < 0)
  92184. offset = 0;
  92185. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  92186. });
  92187. }
  92188. //overwriting the old vertex buffers and indices.
  92189. this._reconstructedMesh.setIndices(newIndicesArray);
  92190. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  92191. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  92192. if (newUVsData.length > 0)
  92193. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  92194. if (newColorsData.length > 0)
  92195. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  92196. //create submesh
  92197. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  92198. if (submeshIndex > 0) {
  92199. this._reconstructedMesh.subMeshes = [];
  92200. submeshesArray.forEach(function (submesh) {
  92201. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  92202. });
  92203. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  92204. }
  92205. };
  92206. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  92207. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  92208. this._reconstructedMesh.material = this._mesh.material;
  92209. this._reconstructedMesh.parent = this._mesh.parent;
  92210. this._reconstructedMesh.isVisible = false;
  92211. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  92212. };
  92213. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  92214. for (var i = 0; i < vertex1.triangleCount; ++i) {
  92215. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  92216. if (t.deleted)
  92217. continue;
  92218. var s = this.references[vertex1.triangleStart + i].vertexId;
  92219. var v1 = t.vertices[(s + 1) % 3];
  92220. var v2 = t.vertices[(s + 2) % 3];
  92221. if ((v1 === vertex2 || v2 === vertex2)) {
  92222. deletedArray[i] = true;
  92223. delTr.push(t);
  92224. continue;
  92225. }
  92226. var d1 = v1.position.subtract(point);
  92227. d1 = d1.normalize();
  92228. var d2 = v2.position.subtract(point);
  92229. d2 = d2.normalize();
  92230. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  92231. return true;
  92232. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  92233. deletedArray[i] = false;
  92234. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  92235. return true;
  92236. }
  92237. return false;
  92238. };
  92239. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  92240. var newDeleted = deletedTriangles;
  92241. for (var i = 0; i < vertex.triangleCount; ++i) {
  92242. var ref = this.references[vertex.triangleStart + i];
  92243. var t = this.triangles[ref.triangleId];
  92244. if (t.deleted)
  92245. continue;
  92246. if (deletedArray[i] && t.deletePending) {
  92247. t.deleted = true;
  92248. newDeleted++;
  92249. continue;
  92250. }
  92251. t.vertices[ref.vertexId] = origVertex;
  92252. t.isDirty = true;
  92253. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  92254. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  92255. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  92256. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  92257. this.references.push(ref);
  92258. }
  92259. return newDeleted;
  92260. };
  92261. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  92262. for (var i = 0; i < this.vertices.length; ++i) {
  92263. var vCount = [];
  92264. var vId = [];
  92265. var v = this.vertices[i];
  92266. var j;
  92267. for (j = 0; j < v.triangleCount; ++j) {
  92268. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  92269. for (var ii = 0; ii < 3; ii++) {
  92270. var ofs = 0;
  92271. var vv = triangle.vertices[ii];
  92272. while (ofs < vCount.length) {
  92273. if (vId[ofs] === vv.id)
  92274. break;
  92275. ++ofs;
  92276. }
  92277. if (ofs === vCount.length) {
  92278. vCount.push(1);
  92279. vId.push(vv.id);
  92280. }
  92281. else {
  92282. vCount[ofs]++;
  92283. }
  92284. }
  92285. }
  92286. for (j = 0; j < vCount.length; ++j) {
  92287. if (vCount[j] === 1) {
  92288. this.vertices[vId[j]].isBorder = true;
  92289. }
  92290. else {
  92291. this.vertices[vId[j]].isBorder = false;
  92292. }
  92293. }
  92294. }
  92295. };
  92296. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  92297. if (identifyBorders === void 0) { identifyBorders = false; }
  92298. var i;
  92299. if (!identifyBorders) {
  92300. var newTrianglesVector = [];
  92301. for (i = 0; i < this.triangles.length; ++i) {
  92302. if (!this.triangles[i].deleted) {
  92303. newTrianglesVector.push(this.triangles[i]);
  92304. }
  92305. }
  92306. this.triangles = newTrianglesVector;
  92307. }
  92308. for (i = 0; i < this.vertices.length; ++i) {
  92309. this.vertices[i].triangleCount = 0;
  92310. this.vertices[i].triangleStart = 0;
  92311. }
  92312. var t;
  92313. var j;
  92314. var v;
  92315. for (i = 0; i < this.triangles.length; ++i) {
  92316. t = this.triangles[i];
  92317. for (j = 0; j < 3; ++j) {
  92318. v = t.vertices[j];
  92319. v.triangleCount++;
  92320. }
  92321. }
  92322. var tStart = 0;
  92323. for (i = 0; i < this.vertices.length; ++i) {
  92324. this.vertices[i].triangleStart = tStart;
  92325. tStart += this.vertices[i].triangleCount;
  92326. this.vertices[i].triangleCount = 0;
  92327. }
  92328. var newReferences = new Array(this.triangles.length * 3);
  92329. for (i = 0; i < this.triangles.length; ++i) {
  92330. t = this.triangles[i];
  92331. for (j = 0; j < 3; ++j) {
  92332. v = t.vertices[j];
  92333. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  92334. v.triangleCount++;
  92335. }
  92336. }
  92337. this.references = newReferences;
  92338. if (identifyBorders) {
  92339. this.identifyBorder();
  92340. }
  92341. };
  92342. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  92343. var x = point.x;
  92344. var y = point.y;
  92345. var z = point.z;
  92346. 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
  92347. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  92348. };
  92349. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  92350. var q = vertex1.q.add(vertex2.q);
  92351. var border = vertex1.isBorder && vertex2.isBorder;
  92352. var error = 0;
  92353. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  92354. if (qDet !== 0 && !border) {
  92355. if (!pointResult) {
  92356. pointResult = BABYLON.Vector3.Zero();
  92357. }
  92358. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  92359. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  92360. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  92361. error = this.vertexError(q, pointResult);
  92362. }
  92363. else {
  92364. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  92365. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  92366. var error1 = this.vertexError(q, vertex1.position);
  92367. var error2 = this.vertexError(q, vertex2.position);
  92368. var error3 = this.vertexError(q, p3);
  92369. error = Math.min(error1, error2, error3);
  92370. if (error === error1) {
  92371. if (pointResult) {
  92372. pointResult.copyFrom(vertex1.position);
  92373. }
  92374. }
  92375. else if (error === error2) {
  92376. if (pointResult) {
  92377. pointResult.copyFrom(vertex2.position);
  92378. }
  92379. }
  92380. else {
  92381. if (pointResult) {
  92382. pointResult.copyFrom(p3);
  92383. }
  92384. }
  92385. }
  92386. return error;
  92387. };
  92388. return QuadraticErrorSimplification;
  92389. }());
  92390. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  92391. })(BABYLON || (BABYLON = {}));
  92392. //# sourceMappingURL=babylon.meshSimplification.js.map
  92393. var BABYLON;
  92394. (function (BABYLON) {
  92395. var MeshLODLevel = /** @class */ (function () {
  92396. function MeshLODLevel(distance, mesh) {
  92397. this.distance = distance;
  92398. this.mesh = mesh;
  92399. }
  92400. return MeshLODLevel;
  92401. }());
  92402. BABYLON.MeshLODLevel = MeshLODLevel;
  92403. })(BABYLON || (BABYLON = {}));
  92404. //# sourceMappingURL=babylon.meshLODLevel.js.map
  92405. var BABYLON;
  92406. (function (BABYLON) {
  92407. /**
  92408. * Defines the root class used to create scene optimization to use with SceneOptimizer
  92409. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92410. */
  92411. var SceneOptimization = /** @class */ (function () {
  92412. /**
  92413. * Creates the SceneOptimization object
  92414. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92415. * @param desc defines the description associated with the optimization
  92416. */
  92417. function SceneOptimization(
  92418. /**
  92419. * Defines the priority of this optimization (0 by default which means first in the list)
  92420. */
  92421. priority) {
  92422. if (priority === void 0) { priority = 0; }
  92423. this.priority = priority;
  92424. }
  92425. /**
  92426. * Gets a string describing the action executed by the current optimization
  92427. * @returns description string
  92428. */
  92429. SceneOptimization.prototype.getDescription = function () {
  92430. return "";
  92431. };
  92432. /**
  92433. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92434. * @param scene defines the current scene where to apply this optimization
  92435. * @param optimizer defines the current optimizer
  92436. * @returns true if everything that can be done was applied
  92437. */
  92438. SceneOptimization.prototype.apply = function (scene, optimizer) {
  92439. return true;
  92440. };
  92441. ;
  92442. return SceneOptimization;
  92443. }());
  92444. BABYLON.SceneOptimization = SceneOptimization;
  92445. /**
  92446. * Defines an optimization used to reduce the size of render target textures
  92447. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92448. */
  92449. var TextureOptimization = /** @class */ (function (_super) {
  92450. __extends(TextureOptimization, _super);
  92451. /**
  92452. * Creates the TextureOptimization object
  92453. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92454. * @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
  92455. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  92456. */
  92457. function TextureOptimization(
  92458. /**
  92459. * Defines the priority of this optimization (0 by default which means first in the list)
  92460. */
  92461. priority,
  92462. /**
  92463. * 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
  92464. */
  92465. maximumSize,
  92466. /**
  92467. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  92468. */
  92469. step) {
  92470. if (priority === void 0) { priority = 0; }
  92471. if (maximumSize === void 0) { maximumSize = 1024; }
  92472. if (step === void 0) { step = 0.5; }
  92473. var _this = _super.call(this, priority) || this;
  92474. _this.priority = priority;
  92475. _this.maximumSize = maximumSize;
  92476. _this.step = step;
  92477. return _this;
  92478. }
  92479. /**
  92480. * Gets a string describing the action executed by the current optimization
  92481. * @returns description string
  92482. */
  92483. TextureOptimization.prototype.getDescription = function () {
  92484. return "Reducing render target texture size to " + this.maximumSize;
  92485. };
  92486. /**
  92487. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92488. * @param scene defines the current scene where to apply this optimization
  92489. * @param optimizer defines the current optimizer
  92490. * @returns true if everything that can be done was applied
  92491. */
  92492. TextureOptimization.prototype.apply = function (scene, optimizer) {
  92493. var allDone = true;
  92494. for (var index = 0; index < scene.textures.length; index++) {
  92495. var texture = scene.textures[index];
  92496. if (!texture.canRescale || texture.getContext) {
  92497. continue;
  92498. }
  92499. var currentSize = texture.getSize();
  92500. var maxDimension = Math.max(currentSize.width, currentSize.height);
  92501. if (maxDimension > this.maximumSize) {
  92502. texture.scale(this.step);
  92503. allDone = false;
  92504. }
  92505. }
  92506. return allDone;
  92507. };
  92508. return TextureOptimization;
  92509. }(SceneOptimization));
  92510. BABYLON.TextureOptimization = TextureOptimization;
  92511. /**
  92512. * Defines an optimization used to increase or decrease the rendering resolution
  92513. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92514. */
  92515. var HardwareScalingOptimization = /** @class */ (function (_super) {
  92516. __extends(HardwareScalingOptimization, _super);
  92517. /**
  92518. * Creates the HardwareScalingOptimization object
  92519. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92520. * @param maximumScale defines the maximum scale to use (2 by default)
  92521. * @param step defines the step to use between two passes (0.5 by default)
  92522. */
  92523. function HardwareScalingOptimization(
  92524. /**
  92525. * Defines the priority of this optimization (0 by default which means first in the list)
  92526. */
  92527. priority,
  92528. /**
  92529. * Defines the maximum scale to use (2 by default)
  92530. */
  92531. maximumScale,
  92532. /**
  92533. * Defines the step to use between two passes (0.5 by default)
  92534. */
  92535. step) {
  92536. if (priority === void 0) { priority = 0; }
  92537. if (maximumScale === void 0) { maximumScale = 2; }
  92538. if (step === void 0) { step = 0.25; }
  92539. var _this = _super.call(this, priority) || this;
  92540. _this.priority = priority;
  92541. _this.maximumScale = maximumScale;
  92542. _this.step = step;
  92543. _this._currentScale = -1;
  92544. _this._directionOffset = 1;
  92545. return _this;
  92546. }
  92547. /**
  92548. * Gets a string describing the action executed by the current optimization
  92549. * @return description string
  92550. */
  92551. HardwareScalingOptimization.prototype.getDescription = function () {
  92552. return "Setting hardware scaling level to " + this._currentScale;
  92553. };
  92554. /**
  92555. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92556. * @param scene defines the current scene where to apply this optimization
  92557. * @param optimizer defines the current optimizer
  92558. * @returns true if everything that can be done was applied
  92559. */
  92560. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  92561. if (this._currentScale === -1) {
  92562. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  92563. if (this._currentScale > this.maximumScale) {
  92564. this._directionOffset = -1;
  92565. }
  92566. }
  92567. this._currentScale += this._directionOffset * this.step;
  92568. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  92569. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  92570. };
  92571. ;
  92572. return HardwareScalingOptimization;
  92573. }(SceneOptimization));
  92574. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  92575. /**
  92576. * Defines an optimization used to remove shadows
  92577. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92578. */
  92579. var ShadowsOptimization = /** @class */ (function (_super) {
  92580. __extends(ShadowsOptimization, _super);
  92581. function ShadowsOptimization() {
  92582. return _super !== null && _super.apply(this, arguments) || this;
  92583. }
  92584. /**
  92585. * Gets a string describing the action executed by the current optimization
  92586. * @return description string
  92587. */
  92588. ShadowsOptimization.prototype.getDescription = function () {
  92589. return "Turning shadows on/off";
  92590. };
  92591. /**
  92592. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92593. * @param scene defines the current scene where to apply this optimization
  92594. * @param optimizer defines the current optimizer
  92595. * @returns true if everything that can be done was applied
  92596. */
  92597. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  92598. scene.shadowsEnabled = optimizer.isInImprovementMode;
  92599. return true;
  92600. };
  92601. ;
  92602. return ShadowsOptimization;
  92603. }(SceneOptimization));
  92604. BABYLON.ShadowsOptimization = ShadowsOptimization;
  92605. /**
  92606. * Defines an optimization used to turn post-processes off
  92607. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92608. */
  92609. var PostProcessesOptimization = /** @class */ (function (_super) {
  92610. __extends(PostProcessesOptimization, _super);
  92611. function PostProcessesOptimization() {
  92612. return _super !== null && _super.apply(this, arguments) || this;
  92613. }
  92614. /**
  92615. * Gets a string describing the action executed by the current optimization
  92616. * @return description string
  92617. */
  92618. PostProcessesOptimization.prototype.getDescription = function () {
  92619. return "Turning post-processes on/off";
  92620. };
  92621. /**
  92622. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92623. * @param scene defines the current scene where to apply this optimization
  92624. * @param optimizer defines the current optimizer
  92625. * @returns true if everything that can be done was applied
  92626. */
  92627. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  92628. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  92629. return true;
  92630. };
  92631. ;
  92632. return PostProcessesOptimization;
  92633. }(SceneOptimization));
  92634. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  92635. /**
  92636. * Defines an optimization used to turn lens flares off
  92637. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92638. */
  92639. var LensFlaresOptimization = /** @class */ (function (_super) {
  92640. __extends(LensFlaresOptimization, _super);
  92641. function LensFlaresOptimization() {
  92642. return _super !== null && _super.apply(this, arguments) || this;
  92643. }
  92644. /**
  92645. * Gets a string describing the action executed by the current optimization
  92646. * @return description string
  92647. */
  92648. LensFlaresOptimization.prototype.getDescription = function () {
  92649. return "Turning lens flares on/off";
  92650. };
  92651. /**
  92652. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92653. * @param scene defines the current scene where to apply this optimization
  92654. * @param optimizer defines the current optimizer
  92655. * @returns true if everything that can be done was applied
  92656. */
  92657. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  92658. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  92659. return true;
  92660. };
  92661. ;
  92662. return LensFlaresOptimization;
  92663. }(SceneOptimization));
  92664. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  92665. /**
  92666. * Defines an optimization based on user defined callback.
  92667. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92668. */
  92669. var CustomOptimization = /** @class */ (function (_super) {
  92670. __extends(CustomOptimization, _super);
  92671. function CustomOptimization() {
  92672. return _super !== null && _super.apply(this, arguments) || this;
  92673. }
  92674. /**
  92675. * Gets a string describing the action executed by the current optimization
  92676. * @returns description string
  92677. */
  92678. CustomOptimization.prototype.getDescription = function () {
  92679. if (this.onGetDescription) {
  92680. return this.onGetDescription();
  92681. }
  92682. return "Running user defined callback";
  92683. };
  92684. /**
  92685. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92686. * @param scene defines the current scene where to apply this optimization
  92687. * @param optimizer defines the current optimizer
  92688. * @returns true if everything that can be done was applied
  92689. */
  92690. CustomOptimization.prototype.apply = function (scene, optimizer) {
  92691. if (this.onApply) {
  92692. return this.onApply(scene, optimizer);
  92693. }
  92694. return true;
  92695. };
  92696. ;
  92697. return CustomOptimization;
  92698. }(SceneOptimization));
  92699. BABYLON.CustomOptimization = CustomOptimization;
  92700. /**
  92701. * Defines an optimization used to turn particles off
  92702. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92703. */
  92704. var ParticlesOptimization = /** @class */ (function (_super) {
  92705. __extends(ParticlesOptimization, _super);
  92706. function ParticlesOptimization() {
  92707. return _super !== null && _super.apply(this, arguments) || this;
  92708. }
  92709. /**
  92710. * Gets a string describing the action executed by the current optimization
  92711. * @return description string
  92712. */
  92713. ParticlesOptimization.prototype.getDescription = function () {
  92714. return "Turning particles on/off";
  92715. };
  92716. /**
  92717. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92718. * @param scene defines the current scene where to apply this optimization
  92719. * @param optimizer defines the current optimizer
  92720. * @returns true if everything that can be done was applied
  92721. */
  92722. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  92723. scene.particlesEnabled = optimizer.isInImprovementMode;
  92724. return true;
  92725. };
  92726. ;
  92727. return ParticlesOptimization;
  92728. }(SceneOptimization));
  92729. BABYLON.ParticlesOptimization = ParticlesOptimization;
  92730. /**
  92731. * Defines an optimization used to turn render targets off
  92732. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92733. */
  92734. var RenderTargetsOptimization = /** @class */ (function (_super) {
  92735. __extends(RenderTargetsOptimization, _super);
  92736. function RenderTargetsOptimization() {
  92737. return _super !== null && _super.apply(this, arguments) || this;
  92738. }
  92739. /**
  92740. * Gets a string describing the action executed by the current optimization
  92741. * @return description string
  92742. */
  92743. RenderTargetsOptimization.prototype.getDescription = function () {
  92744. return "Turning render targets off";
  92745. };
  92746. /**
  92747. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92748. * @param scene defines the current scene where to apply this optimization
  92749. * @param optimizer defines the current optimizer
  92750. * @returns true if everything that can be done was applied
  92751. */
  92752. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  92753. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  92754. return true;
  92755. };
  92756. ;
  92757. return RenderTargetsOptimization;
  92758. }(SceneOptimization));
  92759. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  92760. /**
  92761. * Defines an optimization used to merge meshes with compatible materials
  92762. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92763. */
  92764. var MergeMeshesOptimization = /** @class */ (function (_super) {
  92765. __extends(MergeMeshesOptimization, _super);
  92766. function MergeMeshesOptimization() {
  92767. var _this = _super !== null && _super.apply(this, arguments) || this;
  92768. _this._canBeMerged = function (abstractMesh) {
  92769. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  92770. return false;
  92771. }
  92772. var mesh = abstractMesh;
  92773. if (!mesh.isVisible || !mesh.isEnabled()) {
  92774. return false;
  92775. }
  92776. if (mesh.instances.length > 0) {
  92777. return false;
  92778. }
  92779. if (mesh.skeleton || mesh.hasLODLevels) {
  92780. return false;
  92781. }
  92782. if (mesh.parent) {
  92783. return false;
  92784. }
  92785. return true;
  92786. };
  92787. return _this;
  92788. }
  92789. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  92790. /**
  92791. * Gets or sets a boolean which defines if optimization octree has to be updated
  92792. */
  92793. get: function () {
  92794. return MergeMeshesOptimization._UpdateSelectionTree;
  92795. },
  92796. /**
  92797. * Gets or sets a boolean which defines if optimization octree has to be updated
  92798. */
  92799. set: function (value) {
  92800. MergeMeshesOptimization._UpdateSelectionTree = value;
  92801. },
  92802. enumerable: true,
  92803. configurable: true
  92804. });
  92805. /**
  92806. * Gets a string describing the action executed by the current optimization
  92807. * @return description string
  92808. */
  92809. MergeMeshesOptimization.prototype.getDescription = function () {
  92810. return "Merging similar meshes together";
  92811. };
  92812. /**
  92813. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92814. * @param scene defines the current scene where to apply this optimization
  92815. * @param optimizer defines the current optimizer
  92816. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  92817. * @returns true if everything that can be done was applied
  92818. */
  92819. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  92820. var globalPool = scene.meshes.slice(0);
  92821. var globalLength = globalPool.length;
  92822. for (var index = 0; index < globalLength; index++) {
  92823. var currentPool = new Array();
  92824. var current = globalPool[index];
  92825. // Checks
  92826. if (!this._canBeMerged(current)) {
  92827. continue;
  92828. }
  92829. currentPool.push(current);
  92830. // Find compatible meshes
  92831. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  92832. var otherMesh = globalPool[subIndex];
  92833. if (!this._canBeMerged(otherMesh)) {
  92834. continue;
  92835. }
  92836. if (otherMesh.material !== current.material) {
  92837. continue;
  92838. }
  92839. if (otherMesh.checkCollisions !== current.checkCollisions) {
  92840. continue;
  92841. }
  92842. currentPool.push(otherMesh);
  92843. globalLength--;
  92844. globalPool.splice(subIndex, 1);
  92845. subIndex--;
  92846. }
  92847. if (currentPool.length < 2) {
  92848. continue;
  92849. }
  92850. // Merge meshes
  92851. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  92852. }
  92853. if (updateSelectionTree != undefined) {
  92854. if (updateSelectionTree) {
  92855. scene.createOrUpdateSelectionOctree();
  92856. }
  92857. }
  92858. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  92859. scene.createOrUpdateSelectionOctree();
  92860. }
  92861. return true;
  92862. };
  92863. ;
  92864. MergeMeshesOptimization._UpdateSelectionTree = false;
  92865. return MergeMeshesOptimization;
  92866. }(SceneOptimization));
  92867. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  92868. /**
  92869. * Defines a list of options used by SceneOptimizer
  92870. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92871. */
  92872. var SceneOptimizerOptions = /** @class */ (function () {
  92873. /**
  92874. * Creates a new list of options used by SceneOptimizer
  92875. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  92876. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  92877. */
  92878. function SceneOptimizerOptions(
  92879. /**
  92880. * Defines the target frame rate to reach (60 by default)
  92881. */
  92882. targetFrameRate,
  92883. /**
  92884. * Defines the interval between two checkes (2000ms by default)
  92885. */
  92886. trackerDuration) {
  92887. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  92888. if (trackerDuration === void 0) { trackerDuration = 2000; }
  92889. this.targetFrameRate = targetFrameRate;
  92890. this.trackerDuration = trackerDuration;
  92891. /**
  92892. * Gets the list of optimizations to apply
  92893. */
  92894. this.optimizations = new Array();
  92895. }
  92896. /**
  92897. * Add a new optimization
  92898. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  92899. * @returns the current SceneOptimizerOptions
  92900. */
  92901. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  92902. this.optimizations.push(optimization);
  92903. return this;
  92904. };
  92905. /**
  92906. * Add a new custom optimization
  92907. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  92908. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  92909. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92910. * @returns the current SceneOptimizerOptions
  92911. */
  92912. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  92913. if (priority === void 0) { priority = 0; }
  92914. var optimization = new CustomOptimization(priority);
  92915. optimization.onApply = onApply;
  92916. optimization.onGetDescription = onGetDescription;
  92917. this.optimizations.push(optimization);
  92918. return this;
  92919. };
  92920. /**
  92921. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  92922. * @param targetFrameRate defines the target frame rate (60 by default)
  92923. * @returns a SceneOptimizerOptions object
  92924. */
  92925. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  92926. var result = new SceneOptimizerOptions(targetFrameRate);
  92927. var priority = 0;
  92928. result.addOptimization(new MergeMeshesOptimization(priority));
  92929. result.addOptimization(new ShadowsOptimization(priority));
  92930. result.addOptimization(new LensFlaresOptimization(priority));
  92931. // Next priority
  92932. priority++;
  92933. result.addOptimization(new PostProcessesOptimization(priority));
  92934. result.addOptimization(new ParticlesOptimization(priority));
  92935. // Next priority
  92936. priority++;
  92937. result.addOptimization(new TextureOptimization(priority, 1024));
  92938. return result;
  92939. };
  92940. /**
  92941. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  92942. * @param targetFrameRate defines the target frame rate (60 by default)
  92943. * @returns a SceneOptimizerOptions object
  92944. */
  92945. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  92946. var result = new SceneOptimizerOptions(targetFrameRate);
  92947. var priority = 0;
  92948. result.addOptimization(new MergeMeshesOptimization(priority));
  92949. result.addOptimization(new ShadowsOptimization(priority));
  92950. result.addOptimization(new LensFlaresOptimization(priority));
  92951. // Next priority
  92952. priority++;
  92953. result.addOptimization(new PostProcessesOptimization(priority));
  92954. result.addOptimization(new ParticlesOptimization(priority));
  92955. // Next priority
  92956. priority++;
  92957. result.addOptimization(new TextureOptimization(priority, 512));
  92958. // Next priority
  92959. priority++;
  92960. result.addOptimization(new RenderTargetsOptimization(priority));
  92961. // Next priority
  92962. priority++;
  92963. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  92964. return result;
  92965. };
  92966. /**
  92967. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  92968. * @param targetFrameRate defines the target frame rate (60 by default)
  92969. * @returns a SceneOptimizerOptions object
  92970. */
  92971. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  92972. var result = new SceneOptimizerOptions(targetFrameRate);
  92973. var priority = 0;
  92974. result.addOptimization(new MergeMeshesOptimization(priority));
  92975. result.addOptimization(new ShadowsOptimization(priority));
  92976. result.addOptimization(new LensFlaresOptimization(priority));
  92977. // Next priority
  92978. priority++;
  92979. result.addOptimization(new PostProcessesOptimization(priority));
  92980. result.addOptimization(new ParticlesOptimization(priority));
  92981. // Next priority
  92982. priority++;
  92983. result.addOptimization(new TextureOptimization(priority, 256));
  92984. // Next priority
  92985. priority++;
  92986. result.addOptimization(new RenderTargetsOptimization(priority));
  92987. // Next priority
  92988. priority++;
  92989. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  92990. return result;
  92991. };
  92992. return SceneOptimizerOptions;
  92993. }());
  92994. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  92995. /**
  92996. * Class used to run optimizations in order to reach a target frame rate
  92997. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92998. */
  92999. var SceneOptimizer = /** @class */ (function () {
  93000. /**
  93001. * Creates a new SceneOptimizer
  93002. * @param scene defines the scene to work on
  93003. * @param options defines the options to use with the SceneOptimizer
  93004. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  93005. * @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)
  93006. */
  93007. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  93008. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  93009. if (improvementMode === void 0) { improvementMode = false; }
  93010. var _this = this;
  93011. this._isRunning = false;
  93012. this._currentPriorityLevel = 0;
  93013. this._targetFrameRate = 60;
  93014. this._trackerDuration = 2000;
  93015. this._currentFrameRate = 0;
  93016. this._improvementMode = false;
  93017. /**
  93018. * Defines an observable called when the optimizer reaches the target frame rate
  93019. */
  93020. this.onSuccessObservable = new BABYLON.Observable();
  93021. /**
  93022. * Defines an observable called when the optimizer enables an optimization
  93023. */
  93024. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  93025. /**
  93026. * Defines an observable called when the optimizer is not able to reach the target frame rate
  93027. */
  93028. this.onFailureObservable = new BABYLON.Observable();
  93029. if (!options) {
  93030. this._options = new SceneOptimizerOptions();
  93031. }
  93032. else {
  93033. this._options = options;
  93034. }
  93035. if (this._options.targetFrameRate) {
  93036. this._targetFrameRate = this._options.targetFrameRate;
  93037. }
  93038. if (this._options.trackerDuration) {
  93039. this._trackerDuration = this._options.trackerDuration;
  93040. }
  93041. if (autoGeneratePriorities) {
  93042. var priority = 0;
  93043. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  93044. var optim = _a[_i];
  93045. optim.priority = priority++;
  93046. }
  93047. }
  93048. this._improvementMode = improvementMode;
  93049. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93050. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  93051. _this._sceneDisposeObserver = null;
  93052. _this.dispose();
  93053. });
  93054. }
  93055. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  93056. /**
  93057. * Gets a boolean indicating if the optimizer is in improvement mode
  93058. */
  93059. get: function () {
  93060. return this._improvementMode;
  93061. },
  93062. enumerable: true,
  93063. configurable: true
  93064. });
  93065. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  93066. /**
  93067. * Gets the current priority level (0 at start)
  93068. */
  93069. get: function () {
  93070. return this._currentPriorityLevel;
  93071. },
  93072. enumerable: true,
  93073. configurable: true
  93074. });
  93075. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  93076. /**
  93077. * Gets the current frame rate checked by the SceneOptimizer
  93078. */
  93079. get: function () {
  93080. return this._currentFrameRate;
  93081. },
  93082. enumerable: true,
  93083. configurable: true
  93084. });
  93085. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  93086. /**
  93087. * Gets or sets the current target frame rate (60 by default)
  93088. */
  93089. get: function () {
  93090. return this._targetFrameRate;
  93091. },
  93092. /**
  93093. * Gets or sets the current target frame rate (60 by default)
  93094. */
  93095. set: function (value) {
  93096. this._targetFrameRate = value;
  93097. },
  93098. enumerable: true,
  93099. configurable: true
  93100. });
  93101. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  93102. /**
  93103. * Gets or sets the current interval between two checks (every 2000ms by default)
  93104. */
  93105. get: function () {
  93106. return this._trackerDuration;
  93107. },
  93108. /**
  93109. * Gets or sets the current interval between two checks (every 2000ms by default)
  93110. */
  93111. set: function (value) {
  93112. this._trackerDuration = value;
  93113. },
  93114. enumerable: true,
  93115. configurable: true
  93116. });
  93117. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  93118. /**
  93119. * Gets the list of active optimizations
  93120. */
  93121. get: function () {
  93122. return this._options.optimizations;
  93123. },
  93124. enumerable: true,
  93125. configurable: true
  93126. });
  93127. /**
  93128. * Stops the current optimizer
  93129. */
  93130. SceneOptimizer.prototype.stop = function () {
  93131. this._isRunning = false;
  93132. };
  93133. /**
  93134. * Reset the optimizer to initial step (current priority level = 0)
  93135. */
  93136. SceneOptimizer.prototype.reset = function () {
  93137. this._currentPriorityLevel = 0;
  93138. };
  93139. /**
  93140. * Start the optimizer. By default it will try to reach a specific framerate
  93141. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  93142. */
  93143. SceneOptimizer.prototype.start = function () {
  93144. var _this = this;
  93145. if (this._isRunning) {
  93146. return;
  93147. }
  93148. this._isRunning = true;
  93149. // Let's wait for the scene to be ready before running our check
  93150. this._scene.executeWhenReady(function () {
  93151. setTimeout(function () {
  93152. _this._checkCurrentState();
  93153. }, _this._trackerDuration);
  93154. });
  93155. };
  93156. SceneOptimizer.prototype._checkCurrentState = function () {
  93157. var _this = this;
  93158. if (!this._isRunning) {
  93159. return;
  93160. }
  93161. var scene = this._scene;
  93162. var options = this._options;
  93163. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  93164. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  93165. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  93166. this._isRunning = false;
  93167. this.onSuccessObservable.notifyObservers(this);
  93168. return;
  93169. }
  93170. // Apply current level of optimizations
  93171. var allDone = true;
  93172. var noOptimizationApplied = true;
  93173. for (var index = 0; index < options.optimizations.length; index++) {
  93174. var optimization = options.optimizations[index];
  93175. if (optimization.priority === this._currentPriorityLevel) {
  93176. noOptimizationApplied = false;
  93177. allDone = allDone && optimization.apply(scene, this);
  93178. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  93179. }
  93180. }
  93181. // If no optimization was applied, this is a failure :(
  93182. if (noOptimizationApplied) {
  93183. this._isRunning = false;
  93184. this.onFailureObservable.notifyObservers(this);
  93185. return;
  93186. }
  93187. // If all optimizations were done, move to next level
  93188. if (allDone) {
  93189. this._currentPriorityLevel++;
  93190. }
  93191. // Let's the system running for a specific amount of time before checking FPS
  93192. scene.executeWhenReady(function () {
  93193. setTimeout(function () {
  93194. _this._checkCurrentState();
  93195. }, _this._trackerDuration);
  93196. });
  93197. };
  93198. /**
  93199. * Release all resources
  93200. */
  93201. SceneOptimizer.prototype.dispose = function () {
  93202. this.stop();
  93203. this.onSuccessObservable.clear();
  93204. this.onFailureObservable.clear();
  93205. this.onNewOptimizationAppliedObservable.clear();
  93206. if (this._sceneDisposeObserver) {
  93207. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  93208. }
  93209. };
  93210. /**
  93211. * Helper function to create a SceneOptimizer with one single line of code
  93212. * @param scene defines the scene to work on
  93213. * @param options defines the options to use with the SceneOptimizer
  93214. * @param onSuccess defines a callback to call on success
  93215. * @param onFailure defines a callback to call on failure
  93216. * @returns the new SceneOptimizer object
  93217. */
  93218. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  93219. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  93220. if (onSuccess) {
  93221. optimizer.onSuccessObservable.add(function () {
  93222. onSuccess();
  93223. });
  93224. }
  93225. if (onFailure) {
  93226. optimizer.onFailureObservable.add(function () {
  93227. onFailure();
  93228. });
  93229. }
  93230. optimizer.start();
  93231. return optimizer;
  93232. };
  93233. return SceneOptimizer;
  93234. }());
  93235. BABYLON.SceneOptimizer = SceneOptimizer;
  93236. })(BABYLON || (BABYLON = {}));
  93237. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  93238. var BABYLON;
  93239. (function (BABYLON) {
  93240. var OutlineRenderer = /** @class */ (function () {
  93241. function OutlineRenderer(scene) {
  93242. this.zOffset = 1;
  93243. this._scene = scene;
  93244. }
  93245. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  93246. var _this = this;
  93247. if (useOverlay === void 0) { useOverlay = false; }
  93248. var scene = this._scene;
  93249. var engine = this._scene.getEngine();
  93250. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  93251. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  93252. return;
  93253. }
  93254. var mesh = subMesh.getRenderingMesh();
  93255. var material = subMesh.getMaterial();
  93256. if (!material || !scene.activeCamera) {
  93257. return;
  93258. }
  93259. engine.enableEffect(this._effect);
  93260. // Logarithmic depth
  93261. if (material.useLogarithmicDepth) {
  93262. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  93263. }
  93264. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  93265. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  93266. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  93267. // Bones
  93268. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  93269. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  93270. }
  93271. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  93272. // Alpha test
  93273. if (material && material.needAlphaTesting()) {
  93274. var alphaTexture = material.getAlphaTestTexture();
  93275. if (alphaTexture) {
  93276. this._effect.setTexture("diffuseSampler", alphaTexture);
  93277. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  93278. }
  93279. }
  93280. engine.setZOffset(-this.zOffset);
  93281. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  93282. engine.setZOffset(0);
  93283. };
  93284. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  93285. var defines = [];
  93286. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  93287. var mesh = subMesh.getMesh();
  93288. var material = subMesh.getMaterial();
  93289. if (material) {
  93290. // Alpha test
  93291. if (material.needAlphaTesting()) {
  93292. defines.push("#define ALPHATEST");
  93293. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  93294. attribs.push(BABYLON.VertexBuffer.UVKind);
  93295. defines.push("#define UV1");
  93296. }
  93297. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  93298. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  93299. defines.push("#define UV2");
  93300. }
  93301. }
  93302. //Logarithmic depth
  93303. if (material.useLogarithmicDepth) {
  93304. defines.push("#define LOGARITHMICDEPTH");
  93305. }
  93306. }
  93307. // Bones
  93308. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  93309. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  93310. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  93311. if (mesh.numBoneInfluencers > 4) {
  93312. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  93313. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  93314. }
  93315. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  93316. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  93317. }
  93318. else {
  93319. defines.push("#define NUM_BONE_INFLUENCERS 0");
  93320. }
  93321. // Instances
  93322. if (useInstances) {
  93323. defines.push("#define INSTANCES");
  93324. attribs.push("world0");
  93325. attribs.push("world1");
  93326. attribs.push("world2");
  93327. attribs.push("world3");
  93328. }
  93329. // Get correct effect
  93330. var join = defines.join("\n");
  93331. if (this._cachedDefines !== join) {
  93332. this._cachedDefines = join;
  93333. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  93334. }
  93335. return this._effect.isReady();
  93336. };
  93337. return OutlineRenderer;
  93338. }());
  93339. BABYLON.OutlineRenderer = OutlineRenderer;
  93340. })(BABYLON || (BABYLON = {}));
  93341. //# sourceMappingURL=babylon.outlineRenderer.js.map
  93342. var BABYLON;
  93343. (function (BABYLON) {
  93344. var FaceAdjacencies = /** @class */ (function () {
  93345. function FaceAdjacencies() {
  93346. this.edges = new Array();
  93347. this.edgesConnectedCount = 0;
  93348. }
  93349. return FaceAdjacencies;
  93350. }());
  93351. var EdgesRenderer = /** @class */ (function () {
  93352. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  93353. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  93354. if (epsilon === void 0) { epsilon = 0.95; }
  93355. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  93356. this.edgesWidthScalerForOrthographic = 1000.0;
  93357. this.edgesWidthScalerForPerspective = 50.0;
  93358. this._linesPositions = new Array();
  93359. this._linesNormals = new Array();
  93360. this._linesIndices = new Array();
  93361. this._buffers = {};
  93362. this._checkVerticesInsteadOfIndices = false;
  93363. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  93364. this.isEnabled = true;
  93365. this._source = source;
  93366. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  93367. this._epsilon = epsilon;
  93368. this._prepareRessources();
  93369. this._generateEdgesLines();
  93370. }
  93371. EdgesRenderer.prototype._prepareRessources = function () {
  93372. if (this._lineShader) {
  93373. return;
  93374. }
  93375. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  93376. attributes: ["position", "normal"],
  93377. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  93378. });
  93379. this._lineShader.disableDepthWrite = true;
  93380. this._lineShader.backFaceCulling = false;
  93381. };
  93382. EdgesRenderer.prototype._rebuild = function () {
  93383. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  93384. if (buffer) {
  93385. buffer._rebuild();
  93386. }
  93387. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  93388. if (buffer) {
  93389. buffer._rebuild();
  93390. }
  93391. var scene = this._source.getScene();
  93392. var engine = scene.getEngine();
  93393. this._ib = engine.createIndexBuffer(this._linesIndices);
  93394. };
  93395. EdgesRenderer.prototype.dispose = function () {
  93396. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  93397. if (buffer) {
  93398. buffer.dispose();
  93399. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  93400. }
  93401. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  93402. if (buffer) {
  93403. buffer.dispose();
  93404. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  93405. }
  93406. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  93407. this._lineShader.dispose();
  93408. };
  93409. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  93410. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  93411. return 0;
  93412. }
  93413. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  93414. return 1;
  93415. }
  93416. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  93417. return 2;
  93418. }
  93419. return -1;
  93420. };
  93421. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  93422. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  93423. return 0;
  93424. }
  93425. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  93426. return 1;
  93427. }
  93428. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  93429. return 2;
  93430. }
  93431. return -1;
  93432. };
  93433. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  93434. var needToCreateLine;
  93435. if (edge === undefined) {
  93436. needToCreateLine = true;
  93437. }
  93438. else {
  93439. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  93440. needToCreateLine = dotProduct < this._epsilon;
  93441. }
  93442. if (needToCreateLine) {
  93443. var offset = this._linesPositions.length / 3;
  93444. var normal = p0.subtract(p1);
  93445. normal.normalize();
  93446. // Positions
  93447. this._linesPositions.push(p0.x);
  93448. this._linesPositions.push(p0.y);
  93449. this._linesPositions.push(p0.z);
  93450. this._linesPositions.push(p0.x);
  93451. this._linesPositions.push(p0.y);
  93452. this._linesPositions.push(p0.z);
  93453. this._linesPositions.push(p1.x);
  93454. this._linesPositions.push(p1.y);
  93455. this._linesPositions.push(p1.z);
  93456. this._linesPositions.push(p1.x);
  93457. this._linesPositions.push(p1.y);
  93458. this._linesPositions.push(p1.z);
  93459. // Normals
  93460. this._linesNormals.push(p1.x);
  93461. this._linesNormals.push(p1.y);
  93462. this._linesNormals.push(p1.z);
  93463. this._linesNormals.push(-1);
  93464. this._linesNormals.push(p1.x);
  93465. this._linesNormals.push(p1.y);
  93466. this._linesNormals.push(p1.z);
  93467. this._linesNormals.push(1);
  93468. this._linesNormals.push(p0.x);
  93469. this._linesNormals.push(p0.y);
  93470. this._linesNormals.push(p0.z);
  93471. this._linesNormals.push(-1);
  93472. this._linesNormals.push(p0.x);
  93473. this._linesNormals.push(p0.y);
  93474. this._linesNormals.push(p0.z);
  93475. this._linesNormals.push(1);
  93476. // Indices
  93477. this._linesIndices.push(offset);
  93478. this._linesIndices.push(offset + 1);
  93479. this._linesIndices.push(offset + 2);
  93480. this._linesIndices.push(offset);
  93481. this._linesIndices.push(offset + 2);
  93482. this._linesIndices.push(offset + 3);
  93483. }
  93484. };
  93485. EdgesRenderer.prototype._generateEdgesLines = function () {
  93486. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  93487. var indices = this._source.getIndices();
  93488. if (!indices || !positions) {
  93489. return;
  93490. }
  93491. // First let's find adjacencies
  93492. var adjacencies = new Array();
  93493. var faceNormals = new Array();
  93494. var index;
  93495. var faceAdjacencies;
  93496. // Prepare faces
  93497. for (index = 0; index < indices.length; index += 3) {
  93498. faceAdjacencies = new FaceAdjacencies();
  93499. var p0Index = indices[index];
  93500. var p1Index = indices[index + 1];
  93501. var p2Index = indices[index + 2];
  93502. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  93503. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  93504. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  93505. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  93506. faceNormal.normalize();
  93507. faceNormals.push(faceNormal);
  93508. adjacencies.push(faceAdjacencies);
  93509. }
  93510. // Scan
  93511. for (index = 0; index < adjacencies.length; index++) {
  93512. faceAdjacencies = adjacencies[index];
  93513. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  93514. var otherFaceAdjacencies = adjacencies[otherIndex];
  93515. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  93516. break;
  93517. }
  93518. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  93519. continue;
  93520. }
  93521. var otherP0 = indices[otherIndex * 3];
  93522. var otherP1 = indices[otherIndex * 3 + 1];
  93523. var otherP2 = indices[otherIndex * 3 + 2];
  93524. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  93525. var otherEdgeIndex = 0;
  93526. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  93527. continue;
  93528. }
  93529. switch (edgeIndex) {
  93530. case 0:
  93531. if (this._checkVerticesInsteadOfIndices) {
  93532. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93533. }
  93534. else {
  93535. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  93536. }
  93537. break;
  93538. case 1:
  93539. if (this._checkVerticesInsteadOfIndices) {
  93540. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93541. }
  93542. else {
  93543. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  93544. }
  93545. break;
  93546. case 2:
  93547. if (this._checkVerticesInsteadOfIndices) {
  93548. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93549. }
  93550. else {
  93551. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  93552. }
  93553. break;
  93554. }
  93555. if (otherEdgeIndex === -1) {
  93556. continue;
  93557. }
  93558. faceAdjacencies.edges[edgeIndex] = otherIndex;
  93559. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  93560. faceAdjacencies.edgesConnectedCount++;
  93561. otherFaceAdjacencies.edgesConnectedCount++;
  93562. if (faceAdjacencies.edgesConnectedCount === 3) {
  93563. break;
  93564. }
  93565. }
  93566. }
  93567. }
  93568. // Create lines
  93569. for (index = 0; index < adjacencies.length; index++) {
  93570. // 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
  93571. var current = adjacencies[index];
  93572. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  93573. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  93574. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  93575. }
  93576. // Merge into a single mesh
  93577. var engine = this._source.getScene().getEngine();
  93578. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  93579. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  93580. this._ib = engine.createIndexBuffer(this._linesIndices);
  93581. this._indicesCount = this._linesIndices.length;
  93582. };
  93583. EdgesRenderer.prototype.render = function () {
  93584. var scene = this._source.getScene();
  93585. if (!this._lineShader.isReady() || !scene.activeCamera) {
  93586. return;
  93587. }
  93588. var engine = scene.getEngine();
  93589. this._lineShader._preBind();
  93590. // VBOs
  93591. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  93592. scene.resetCachedMaterial();
  93593. this._lineShader.setColor4("color", this._source.edgesColor);
  93594. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  93595. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  93596. }
  93597. else {
  93598. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  93599. }
  93600. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  93601. this._lineShader.bind(this._source.getWorldMatrix());
  93602. // Draw order
  93603. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  93604. this._lineShader.unbind();
  93605. engine.setDepthWrite(true);
  93606. };
  93607. return EdgesRenderer;
  93608. }());
  93609. BABYLON.EdgesRenderer = EdgesRenderer;
  93610. })(BABYLON || (BABYLON = {}));
  93611. //# sourceMappingURL=babylon.edgesRenderer.js.map
  93612. var __assign = (this && this.__assign) || Object.assign || function(t) {
  93613. for (var s, i = 1, n = arguments.length; i < n; i++) {
  93614. s = arguments[i];
  93615. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  93616. t[p] = s[p];
  93617. }
  93618. return t;
  93619. };
  93620. var BABYLON;
  93621. (function (BABYLON) {
  93622. /**
  93623. * The effect layer Helps adding post process effect blended with the main pass.
  93624. *
  93625. * This can be for instance use to generate glow or higlight effects on the scene.
  93626. *
  93627. * The effect layer class can not be used directly and is intented to inherited from to be
  93628. * customized per effects.
  93629. */
  93630. var EffectLayer = /** @class */ (function () {
  93631. /**
  93632. * Instantiates a new effect Layer and references it in the scene.
  93633. * @param name The name of the layer
  93634. * @param scene The scene to use the layer in
  93635. */
  93636. function EffectLayer(
  93637. /** The Friendly of the effect in the scene */
  93638. name, scene) {
  93639. this._vertexBuffers = {};
  93640. this._maxSize = 0;
  93641. this._mainTextureDesiredSize = { width: 0, height: 0 };
  93642. this._shouldRender = true;
  93643. this._postProcesses = [];
  93644. this._textures = [];
  93645. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  93646. /**
  93647. * The clear color of the texture used to generate the glow map.
  93648. */
  93649. this.neutralColor = new BABYLON.Color4();
  93650. /**
  93651. * Specifies wether the highlight layer is enabled or not.
  93652. */
  93653. this.isEnabled = true;
  93654. /**
  93655. * An event triggered when the effect layer has been disposed.
  93656. */
  93657. this.onDisposeObservable = new BABYLON.Observable();
  93658. /**
  93659. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  93660. */
  93661. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  93662. /**
  93663. * An event triggered when the generated texture is being merged in the scene.
  93664. */
  93665. this.onBeforeComposeObservable = new BABYLON.Observable();
  93666. /**
  93667. * An event triggered when the generated texture has been merged in the scene.
  93668. */
  93669. this.onAfterComposeObservable = new BABYLON.Observable();
  93670. /**
  93671. * An event triggered when the efffect layer changes its size.
  93672. */
  93673. this.onSizeChangedObservable = new BABYLON.Observable();
  93674. this.name = name;
  93675. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93676. this._engine = scene.getEngine();
  93677. this._maxSize = this._engine.getCaps().maxTextureSize;
  93678. this._scene.effectLayers.push(this);
  93679. // Generate Buffers
  93680. this._generateIndexBuffer();
  93681. this._genrateVertexBuffer();
  93682. }
  93683. Object.defineProperty(EffectLayer.prototype, "camera", {
  93684. /**
  93685. * Gets the camera attached to the layer.
  93686. */
  93687. get: function () {
  93688. return this._effectLayerOptions.camera;
  93689. },
  93690. enumerable: true,
  93691. configurable: true
  93692. });
  93693. /**
  93694. * Initializes the effect layer with the required options.
  93695. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  93696. */
  93697. EffectLayer.prototype._init = function (options) {
  93698. // Adapt options
  93699. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  93700. this._setMainTextureSize();
  93701. this._createMainTexture();
  93702. this._createTextureAndPostProcesses();
  93703. this._mergeEffect = this._createMergeEffect();
  93704. };
  93705. /**
  93706. * Generates the index buffer of the full screen quad blending to the main canvas.
  93707. */
  93708. EffectLayer.prototype._generateIndexBuffer = function () {
  93709. // Indices
  93710. var indices = [];
  93711. indices.push(0);
  93712. indices.push(1);
  93713. indices.push(2);
  93714. indices.push(0);
  93715. indices.push(2);
  93716. indices.push(3);
  93717. this._indexBuffer = this._engine.createIndexBuffer(indices);
  93718. };
  93719. /**
  93720. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  93721. */
  93722. EffectLayer.prototype._genrateVertexBuffer = function () {
  93723. // VBO
  93724. var vertices = [];
  93725. vertices.push(1, 1);
  93726. vertices.push(-1, 1);
  93727. vertices.push(-1, -1);
  93728. vertices.push(1, -1);
  93729. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93730. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93731. };
  93732. /**
  93733. * Sets the main texture desired size which is the closest power of two
  93734. * of the engine canvas size.
  93735. */
  93736. EffectLayer.prototype._setMainTextureSize = function () {
  93737. if (this._effectLayerOptions.mainTextureFixedSize) {
  93738. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  93739. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  93740. }
  93741. else {
  93742. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  93743. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  93744. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  93745. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  93746. }
  93747. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  93748. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  93749. };
  93750. /**
  93751. * Creates the main texture for the effect layer.
  93752. */
  93753. EffectLayer.prototype._createMainTexture = function () {
  93754. var _this = this;
  93755. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  93756. width: this._mainTextureDesiredSize.width,
  93757. height: this._mainTextureDesiredSize.height
  93758. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  93759. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  93760. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93761. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93762. this._mainTexture.anisotropicFilteringLevel = 1;
  93763. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93764. this._mainTexture.renderParticles = false;
  93765. this._mainTexture.renderList = null;
  93766. this._mainTexture.ignoreCameraViewport = true;
  93767. // Custom render function
  93768. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  93769. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  93770. var index;
  93771. var engine = _this._scene.getEngine();
  93772. if (depthOnlySubMeshes.length) {
  93773. engine.setColorWrite(false);
  93774. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  93775. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  93776. }
  93777. engine.setColorWrite(true);
  93778. }
  93779. for (index = 0; index < opaqueSubMeshes.length; index++) {
  93780. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  93781. }
  93782. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  93783. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  93784. }
  93785. for (index = 0; index < transparentSubMeshes.length; index++) {
  93786. _this._renderSubMesh(transparentSubMeshes.data[index]);
  93787. }
  93788. };
  93789. this._mainTexture.onClearObservable.add(function (engine) {
  93790. engine.clear(_this.neutralColor, true, true, true);
  93791. });
  93792. };
  93793. /**
  93794. * Checks for the readiness of the element composing the layer.
  93795. * @param subMesh the mesh to check for
  93796. * @param useInstances specify wether or not to use instances to render the mesh
  93797. * @param emissiveTexture the associated emissive texture used to generate the glow
  93798. * @return true if ready otherwise, false
  93799. */
  93800. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  93801. var material = subMesh.getMaterial();
  93802. if (!material) {
  93803. return false;
  93804. }
  93805. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  93806. return false;
  93807. }
  93808. var defines = [];
  93809. var attribs = [BABYLON.VertexBuffer.PositionKind];
  93810. var mesh = subMesh.getMesh();
  93811. var uv1 = false;
  93812. var uv2 = false;
  93813. // Alpha test
  93814. if (material && material.needAlphaTesting()) {
  93815. var alphaTexture = material.getAlphaTestTexture();
  93816. if (alphaTexture) {
  93817. defines.push("#define ALPHATEST");
  93818. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  93819. alphaTexture.coordinatesIndex === 1) {
  93820. defines.push("#define DIFFUSEUV2");
  93821. uv2 = true;
  93822. }
  93823. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  93824. defines.push("#define DIFFUSEUV1");
  93825. uv1 = true;
  93826. }
  93827. }
  93828. }
  93829. // Emissive
  93830. if (emissiveTexture) {
  93831. defines.push("#define EMISSIVE");
  93832. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  93833. emissiveTexture.coordinatesIndex === 1) {
  93834. defines.push("#define EMISSIVEUV2");
  93835. uv2 = true;
  93836. }
  93837. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  93838. defines.push("#define EMISSIVEUV1");
  93839. uv1 = true;
  93840. }
  93841. }
  93842. if (uv1) {
  93843. attribs.push(BABYLON.VertexBuffer.UVKind);
  93844. defines.push("#define UV1");
  93845. }
  93846. if (uv2) {
  93847. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  93848. defines.push("#define UV2");
  93849. }
  93850. // Bones
  93851. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  93852. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  93853. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  93854. if (mesh.numBoneInfluencers > 4) {
  93855. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  93856. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  93857. }
  93858. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  93859. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  93860. }
  93861. else {
  93862. defines.push("#define NUM_BONE_INFLUENCERS 0");
  93863. }
  93864. // Morph targets
  93865. var manager = mesh.morphTargetManager;
  93866. var morphInfluencers = 0;
  93867. if (manager) {
  93868. if (manager.numInfluencers > 0) {
  93869. defines.push("#define MORPHTARGETS");
  93870. morphInfluencers = manager.numInfluencers;
  93871. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  93872. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  93873. }
  93874. }
  93875. // Instances
  93876. if (useInstances) {
  93877. defines.push("#define INSTANCES");
  93878. attribs.push("world0");
  93879. attribs.push("world1");
  93880. attribs.push("world2");
  93881. attribs.push("world3");
  93882. }
  93883. // Get correct effect
  93884. var join = defines.join("\n");
  93885. if (this._cachedDefines !== join) {
  93886. this._cachedDefines = join;
  93887. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  93888. }
  93889. return this._effectLayerMapGenerationEffect.isReady();
  93890. };
  93891. /**
  93892. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  93893. */
  93894. EffectLayer.prototype.render = function () {
  93895. var currentEffect = this._mergeEffect;
  93896. // Check
  93897. if (!currentEffect.isReady())
  93898. return;
  93899. for (var i = 0; i < this._postProcesses.length; i++) {
  93900. if (!this._postProcesses[i].isReady()) {
  93901. return;
  93902. }
  93903. }
  93904. var engine = this._scene.getEngine();
  93905. this.onBeforeComposeObservable.notifyObservers(this);
  93906. // Render
  93907. engine.enableEffect(currentEffect);
  93908. engine.setState(false);
  93909. // VBOs
  93910. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  93911. // Cache
  93912. var previousAlphaMode = engine.getAlphaMode();
  93913. // Go Blend.
  93914. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  93915. // Blends the map on the main canvas.
  93916. this._internalRender(currentEffect);
  93917. // Restore Alpha
  93918. engine.setAlphaMode(previousAlphaMode);
  93919. this.onAfterComposeObservable.notifyObservers(this);
  93920. // Handle size changes.
  93921. var size = this._mainTexture.getSize();
  93922. this._setMainTextureSize();
  93923. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  93924. // Recreate RTT and post processes on size change.
  93925. this.onSizeChangedObservable.notifyObservers(this);
  93926. this._disposeTextureAndPostProcesses();
  93927. this._createMainTexture();
  93928. this._createTextureAndPostProcesses();
  93929. }
  93930. };
  93931. /**
  93932. * Determine if a given mesh will be used in the current effect.
  93933. * @param mesh mesh to test
  93934. * @returns true if the mesh will be used
  93935. */
  93936. EffectLayer.prototype.hasMesh = function (mesh) {
  93937. return true;
  93938. };
  93939. /**
  93940. * Returns true if the layer contains information to display, otherwise false.
  93941. * @returns true if the glow layer should be rendered
  93942. */
  93943. EffectLayer.prototype.shouldRender = function () {
  93944. return this.isEnabled && this._shouldRender;
  93945. };
  93946. /**
  93947. * Returns true if the mesh should render, otherwise false.
  93948. * @param mesh The mesh to render
  93949. * @returns true if it should render otherwise false
  93950. */
  93951. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  93952. return true;
  93953. };
  93954. /**
  93955. * Returns true if the mesh should render, otherwise false.
  93956. * @param mesh The mesh to render
  93957. * @returns true if it should render otherwise false
  93958. */
  93959. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  93960. return true;
  93961. };
  93962. /**
  93963. * Renders the submesh passed in parameter to the generation map.
  93964. */
  93965. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  93966. var _this = this;
  93967. if (!this.shouldRender()) {
  93968. return;
  93969. }
  93970. var material = subMesh.getMaterial();
  93971. var mesh = subMesh.getRenderingMesh();
  93972. var scene = this._scene;
  93973. var engine = scene.getEngine();
  93974. if (!material) {
  93975. return;
  93976. }
  93977. // Do not block in blend mode.
  93978. if (material.needAlphaBlendingForMesh(mesh)) {
  93979. return;
  93980. }
  93981. // Culling
  93982. engine.setState(material.backFaceCulling);
  93983. // Managing instances
  93984. var batch = mesh._getInstancesRenderList(subMesh._id);
  93985. if (batch.mustReturn) {
  93986. return;
  93987. }
  93988. // Early Exit per mesh
  93989. if (!this._shouldRenderMesh(mesh)) {
  93990. return;
  93991. }
  93992. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  93993. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  93994. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  93995. engine.enableEffect(this._effectLayerMapGenerationEffect);
  93996. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  93997. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  93998. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  93999. // Alpha test
  94000. if (material && material.needAlphaTesting()) {
  94001. var alphaTexture = material.getAlphaTestTexture();
  94002. if (alphaTexture) {
  94003. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  94004. var textureMatrix = alphaTexture.getTextureMatrix();
  94005. if (textureMatrix) {
  94006. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  94007. }
  94008. }
  94009. }
  94010. // Glow emissive only
  94011. if (this._emissiveTextureAndColor.texture) {
  94012. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  94013. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  94014. }
  94015. // Bones
  94016. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  94017. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  94018. }
  94019. // Morph targets
  94020. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  94021. // Draw
  94022. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  94023. }
  94024. else {
  94025. // Need to reset refresh rate of the shadowMap
  94026. this._mainTexture.resetRefreshCounter();
  94027. }
  94028. };
  94029. /**
  94030. * Rebuild the required buffers.
  94031. * @hidden Internal use only.
  94032. */
  94033. EffectLayer.prototype._rebuild = function () {
  94034. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94035. if (vb) {
  94036. vb._rebuild();
  94037. }
  94038. this._generateIndexBuffer();
  94039. };
  94040. /**
  94041. * Dispose only the render target textures and post process.
  94042. */
  94043. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  94044. this._mainTexture.dispose();
  94045. for (var i = 0; i < this._postProcesses.length; i++) {
  94046. if (this._postProcesses[i]) {
  94047. this._postProcesses[i].dispose();
  94048. }
  94049. }
  94050. this._postProcesses = [];
  94051. for (var i = 0; i < this._textures.length; i++) {
  94052. if (this._textures[i]) {
  94053. this._textures[i].dispose();
  94054. }
  94055. }
  94056. this._textures = [];
  94057. };
  94058. /**
  94059. * Dispose the highlight layer and free resources.
  94060. */
  94061. EffectLayer.prototype.dispose = function () {
  94062. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94063. if (vertexBuffer) {
  94064. vertexBuffer.dispose();
  94065. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94066. }
  94067. if (this._indexBuffer) {
  94068. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94069. this._indexBuffer = null;
  94070. }
  94071. // Clean textures and post processes
  94072. this._disposeTextureAndPostProcesses();
  94073. // Remove from scene
  94074. var index = this._scene.effectLayers.indexOf(this, 0);
  94075. if (index > -1) {
  94076. this._scene.effectLayers.splice(index, 1);
  94077. }
  94078. // Callback
  94079. this.onDisposeObservable.notifyObservers(this);
  94080. this.onDisposeObservable.clear();
  94081. this.onBeforeRenderMainTextureObservable.clear();
  94082. this.onBeforeComposeObservable.clear();
  94083. this.onAfterComposeObservable.clear();
  94084. this.onSizeChangedObservable.clear();
  94085. };
  94086. /**
  94087. * Gets the class name of the effect layer
  94088. * @returns the string with the class name of the effect layer
  94089. */
  94090. EffectLayer.prototype.getClassName = function () {
  94091. return "EffectLayer";
  94092. };
  94093. /**
  94094. * Creates an effect layer from parsed effect layer data
  94095. * @param parsedEffectLayer defines effect layer data
  94096. * @param scene defines the current scene
  94097. * @param rootUrl defines the root URL containing the effect layer information
  94098. * @returns a parsed effect Layer
  94099. */
  94100. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  94101. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  94102. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  94103. };
  94104. __decorate([
  94105. BABYLON.serialize()
  94106. ], EffectLayer.prototype, "name", void 0);
  94107. __decorate([
  94108. BABYLON.serializeAsColor4()
  94109. ], EffectLayer.prototype, "neutralColor", void 0);
  94110. __decorate([
  94111. BABYLON.serialize()
  94112. ], EffectLayer.prototype, "isEnabled", void 0);
  94113. __decorate([
  94114. BABYLON.serializeAsCameraReference()
  94115. ], EffectLayer.prototype, "camera", null);
  94116. return EffectLayer;
  94117. }());
  94118. BABYLON.EffectLayer = EffectLayer;
  94119. })(BABYLON || (BABYLON = {}));
  94120. //# sourceMappingURL=babylon.effectLayer.js.map
  94121. var BABYLON;
  94122. (function (BABYLON) {
  94123. /**
  94124. * Special Glow Blur post process only blurring the alpha channel
  94125. * It enforces keeping the most luminous color in the color channel.
  94126. */
  94127. var GlowBlurPostProcess = /** @class */ (function (_super) {
  94128. __extends(GlowBlurPostProcess, _super);
  94129. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  94130. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  94131. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  94132. _this.direction = direction;
  94133. _this.kernel = kernel;
  94134. _this.onApplyObservable.add(function (effect) {
  94135. effect.setFloat2("screenSize", _this.width, _this.height);
  94136. effect.setVector2("direction", _this.direction);
  94137. effect.setFloat("blurWidth", _this.kernel);
  94138. });
  94139. return _this;
  94140. }
  94141. return GlowBlurPostProcess;
  94142. }(BABYLON.PostProcess));
  94143. /**
  94144. * The highlight layer Helps adding a glow effect around a mesh.
  94145. *
  94146. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  94147. * glowy meshes to your scene.
  94148. *
  94149. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  94150. */
  94151. var HighlightLayer = /** @class */ (function (_super) {
  94152. __extends(HighlightLayer, _super);
  94153. /**
  94154. * Instantiates a new highlight Layer and references it to the scene..
  94155. * @param name The name of the layer
  94156. * @param scene The scene to use the layer in
  94157. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  94158. */
  94159. function HighlightLayer(name, scene, options) {
  94160. var _this = _super.call(this, name, scene) || this;
  94161. _this.name = name;
  94162. /**
  94163. * Specifies whether or not the inner glow is ACTIVE in the layer.
  94164. */
  94165. _this.innerGlow = true;
  94166. /**
  94167. * Specifies whether or not the outer glow is ACTIVE in the layer.
  94168. */
  94169. _this.outerGlow = true;
  94170. /**
  94171. * An event triggered when the highlight layer is being blurred.
  94172. */
  94173. _this.onBeforeBlurObservable = new BABYLON.Observable();
  94174. /**
  94175. * An event triggered when the highlight layer has been blurred.
  94176. */
  94177. _this.onAfterBlurObservable = new BABYLON.Observable();
  94178. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  94179. _this._meshes = {};
  94180. _this._excludedMeshes = {};
  94181. _this.neutralColor = HighlightLayer.NeutralColor;
  94182. // Warn on stencil
  94183. if (!_this._engine.isStencilEnable) {
  94184. 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 }");
  94185. }
  94186. // Adapt options
  94187. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  94188. // Initialize the layer
  94189. _this._init({
  94190. alphaBlendingMode: _this._options.alphaBlendingMode,
  94191. camera: _this._options.camera,
  94192. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  94193. mainTextureRatio: _this._options.mainTextureRatio
  94194. });
  94195. // Do not render as long as no meshes have been added
  94196. _this._shouldRender = false;
  94197. return _this;
  94198. }
  94199. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  94200. /**
  94201. * Gets the horizontal size of the blur.
  94202. */
  94203. get: function () {
  94204. return this._horizontalBlurPostprocess.kernel;
  94205. },
  94206. /**
  94207. * Specifies the horizontal size of the blur.
  94208. */
  94209. set: function (value) {
  94210. this._horizontalBlurPostprocess.kernel = value;
  94211. },
  94212. enumerable: true,
  94213. configurable: true
  94214. });
  94215. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  94216. /**
  94217. * Gets the vertical size of the blur.
  94218. */
  94219. get: function () {
  94220. return this._verticalBlurPostprocess.kernel;
  94221. },
  94222. /**
  94223. * Specifies the vertical size of the blur.
  94224. */
  94225. set: function (value) {
  94226. this._verticalBlurPostprocess.kernel = value;
  94227. },
  94228. enumerable: true,
  94229. configurable: true
  94230. });
  94231. /**
  94232. * Get the effect name of the layer.
  94233. * @return The effect name
  94234. */
  94235. HighlightLayer.prototype.getEffectName = function () {
  94236. return HighlightLayer.EffectName;
  94237. };
  94238. /**
  94239. * Create the merge effect. This is the shader use to blit the information back
  94240. * to the main canvas at the end of the scene rendering.
  94241. */
  94242. HighlightLayer.prototype._createMergeEffect = function () {
  94243. // Effect
  94244. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  94245. };
  94246. /**
  94247. * Creates the render target textures and post processes used in the highlight layer.
  94248. */
  94249. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  94250. var _this = this;
  94251. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  94252. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  94253. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  94254. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  94255. var textureType = 0;
  94256. if (this._engine.getCaps().textureHalfFloatRender) {
  94257. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94258. }
  94259. else {
  94260. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94261. }
  94262. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  94263. width: blurTextureWidth,
  94264. height: blurTextureHeight
  94265. }, this._scene, false, true, textureType);
  94266. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94267. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94268. this._blurTexture.anisotropicFilteringLevel = 16;
  94269. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  94270. this._blurTexture.renderParticles = false;
  94271. this._blurTexture.ignoreCameraViewport = true;
  94272. this._textures = [this._blurTexture];
  94273. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  94274. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94275. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  94276. effect.setTexture("textureSampler", _this._mainTexture);
  94277. });
  94278. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94279. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  94280. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  94281. });
  94282. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94283. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  94284. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  94285. });
  94286. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  94287. }
  94288. else {
  94289. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  94290. width: blurTextureWidth,
  94291. height: blurTextureHeight
  94292. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94293. this._horizontalBlurPostprocess.width = blurTextureWidth;
  94294. this._horizontalBlurPostprocess.height = blurTextureHeight;
  94295. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  94296. effect.setTexture("textureSampler", _this._mainTexture);
  94297. });
  94298. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  94299. width: blurTextureWidth,
  94300. height: blurTextureHeight
  94301. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94302. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  94303. }
  94304. this._mainTexture.onAfterUnbindObservable.add(function () {
  94305. _this.onBeforeBlurObservable.notifyObservers(_this);
  94306. var internalTexture = _this._blurTexture.getInternalTexture();
  94307. if (internalTexture) {
  94308. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  94309. }
  94310. _this.onAfterBlurObservable.notifyObservers(_this);
  94311. });
  94312. // Prevent autoClear.
  94313. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  94314. };
  94315. /**
  94316. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  94317. */
  94318. HighlightLayer.prototype.needStencil = function () {
  94319. return true;
  94320. };
  94321. /**
  94322. * Checks for the readiness of the element composing the layer.
  94323. * @param subMesh the mesh to check for
  94324. * @param useInstances specify wether or not to use instances to render the mesh
  94325. * @param emissiveTexture the associated emissive texture used to generate the glow
  94326. * @return true if ready otherwise, false
  94327. */
  94328. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  94329. var material = subMesh.getMaterial();
  94330. var mesh = subMesh.getRenderingMesh();
  94331. if (!material || !mesh || !this._meshes) {
  94332. return false;
  94333. }
  94334. var emissiveTexture = null;
  94335. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  94336. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  94337. emissiveTexture = material.emissiveTexture;
  94338. }
  94339. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  94340. };
  94341. /**
  94342. * Implementation specific of rendering the generating effect on the main canvas.
  94343. * @param effect The effect used to render through
  94344. */
  94345. HighlightLayer.prototype._internalRender = function (effect) {
  94346. // Texture
  94347. effect.setTexture("textureSampler", this._blurTexture);
  94348. // Cache
  94349. var engine = this._engine;
  94350. var previousStencilBuffer = engine.getStencilBuffer();
  94351. var previousStencilFunction = engine.getStencilFunction();
  94352. var previousStencilMask = engine.getStencilMask();
  94353. var previousStencilOperationPass = engine.getStencilOperationPass();
  94354. var previousStencilOperationFail = engine.getStencilOperationFail();
  94355. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  94356. var previousStencilReference = engine.getStencilFunctionReference();
  94357. // Stencil operations
  94358. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  94359. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  94360. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  94361. // Draw order
  94362. engine.setStencilMask(0x00);
  94363. engine.setStencilBuffer(true);
  94364. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  94365. // 2 passes inner outer
  94366. if (this.outerGlow) {
  94367. effect.setFloat("offset", 0);
  94368. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  94369. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94370. }
  94371. if (this.innerGlow) {
  94372. effect.setFloat("offset", 1);
  94373. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  94374. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94375. }
  94376. // Restore Cache
  94377. engine.setStencilFunction(previousStencilFunction);
  94378. engine.setStencilMask(previousStencilMask);
  94379. engine.setStencilBuffer(previousStencilBuffer);
  94380. engine.setStencilOperationPass(previousStencilOperationPass);
  94381. engine.setStencilOperationFail(previousStencilOperationFail);
  94382. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  94383. engine.setStencilFunctionReference(previousStencilReference);
  94384. };
  94385. /**
  94386. * Returns true if the layer contains information to display, otherwise false.
  94387. */
  94388. HighlightLayer.prototype.shouldRender = function () {
  94389. if (_super.prototype.shouldRender.call(this)) {
  94390. return this._meshes ? true : false;
  94391. }
  94392. return false;
  94393. };
  94394. /**
  94395. * Returns true if the mesh should render, otherwise false.
  94396. * @param mesh The mesh to render
  94397. * @returns true if it should render otherwise false
  94398. */
  94399. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  94400. // Excluded Mesh
  94401. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  94402. return false;
  94403. }
  94404. ;
  94405. return true;
  94406. };
  94407. /**
  94408. * Sets the required values for both the emissive texture and and the main color.
  94409. */
  94410. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  94411. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  94412. if (highlightLayerMesh) {
  94413. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  94414. }
  94415. else {
  94416. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  94417. }
  94418. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  94419. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  94420. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  94421. }
  94422. else {
  94423. this._emissiveTextureAndColor.texture = null;
  94424. }
  94425. };
  94426. /**
  94427. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  94428. * @param mesh The mesh to exclude from the highlight layer
  94429. */
  94430. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  94431. if (!this._excludedMeshes) {
  94432. return;
  94433. }
  94434. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  94435. if (!meshExcluded) {
  94436. this._excludedMeshes[mesh.uniqueId] = {
  94437. mesh: mesh,
  94438. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  94439. mesh.getEngine().setStencilBuffer(false);
  94440. }),
  94441. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  94442. mesh.getEngine().setStencilBuffer(true);
  94443. }),
  94444. };
  94445. }
  94446. };
  94447. /**
  94448. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  94449. * @param mesh The mesh to highlight
  94450. */
  94451. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  94452. if (!this._excludedMeshes) {
  94453. return;
  94454. }
  94455. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  94456. if (meshExcluded) {
  94457. if (meshExcluded.beforeRender) {
  94458. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  94459. }
  94460. if (meshExcluded.afterRender) {
  94461. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  94462. }
  94463. }
  94464. this._excludedMeshes[mesh.uniqueId] = null;
  94465. };
  94466. /**
  94467. * Determine if a given mesh will be highlighted by the current HighlightLayer
  94468. * @param mesh mesh to test
  94469. * @returns true if the mesh will be highlighted by the current HighlightLayer
  94470. */
  94471. HighlightLayer.prototype.hasMesh = function (mesh) {
  94472. if (!this._meshes) {
  94473. return false;
  94474. }
  94475. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  94476. };
  94477. /**
  94478. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  94479. * @param mesh The mesh to highlight
  94480. * @param color The color of the highlight
  94481. * @param glowEmissiveOnly Extract the glow from the emissive texture
  94482. */
  94483. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  94484. var _this = this;
  94485. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  94486. if (!this._meshes) {
  94487. return;
  94488. }
  94489. var meshHighlight = this._meshes[mesh.uniqueId];
  94490. if (meshHighlight) {
  94491. meshHighlight.color = color;
  94492. }
  94493. else {
  94494. this._meshes[mesh.uniqueId] = {
  94495. mesh: mesh,
  94496. color: color,
  94497. // Lambda required for capture due to Observable this context
  94498. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  94499. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  94500. _this._defaultStencilReference(mesh);
  94501. }
  94502. else {
  94503. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  94504. }
  94505. }),
  94506. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  94507. glowEmissiveOnly: glowEmissiveOnly
  94508. };
  94509. }
  94510. this._shouldRender = true;
  94511. };
  94512. /**
  94513. * Remove a mesh from the highlight layer in order to make it stop glowing.
  94514. * @param mesh The mesh to highlight
  94515. */
  94516. HighlightLayer.prototype.removeMesh = function (mesh) {
  94517. if (!this._meshes) {
  94518. return;
  94519. }
  94520. var meshHighlight = this._meshes[mesh.uniqueId];
  94521. if (meshHighlight) {
  94522. if (meshHighlight.observerHighlight) {
  94523. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  94524. }
  94525. if (meshHighlight.observerDefault) {
  94526. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  94527. }
  94528. delete this._meshes[mesh.uniqueId];
  94529. }
  94530. this._shouldRender = false;
  94531. for (var meshHighlightToCheck in this._meshes) {
  94532. if (this._meshes[meshHighlightToCheck]) {
  94533. this._shouldRender = true;
  94534. break;
  94535. }
  94536. }
  94537. };
  94538. /**
  94539. * Force the stencil to the normal expected value for none glowing parts
  94540. */
  94541. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  94542. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  94543. };
  94544. /**
  94545. * Free any resources and references associated to a mesh.
  94546. * Internal use
  94547. * @param mesh The mesh to free.
  94548. */
  94549. HighlightLayer.prototype._disposeMesh = function (mesh) {
  94550. this.removeMesh(mesh);
  94551. this.removeExcludedMesh(mesh);
  94552. };
  94553. /**
  94554. * Dispose the highlight layer and free resources.
  94555. */
  94556. HighlightLayer.prototype.dispose = function () {
  94557. if (this._meshes) {
  94558. // Clean mesh references
  94559. for (var id in this._meshes) {
  94560. var meshHighlight = this._meshes[id];
  94561. if (meshHighlight && meshHighlight.mesh) {
  94562. if (meshHighlight.observerHighlight) {
  94563. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  94564. }
  94565. if (meshHighlight.observerDefault) {
  94566. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  94567. }
  94568. }
  94569. }
  94570. this._meshes = null;
  94571. }
  94572. if (this._excludedMeshes) {
  94573. for (var id in this._excludedMeshes) {
  94574. var meshHighlight = this._excludedMeshes[id];
  94575. if (meshHighlight) {
  94576. if (meshHighlight.beforeRender) {
  94577. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  94578. }
  94579. if (meshHighlight.afterRender) {
  94580. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  94581. }
  94582. }
  94583. }
  94584. this._excludedMeshes = null;
  94585. }
  94586. _super.prototype.dispose.call(this);
  94587. };
  94588. /**
  94589. * Gets the class name of the effect layer
  94590. * @returns the string with the class name of the effect layer
  94591. */
  94592. HighlightLayer.prototype.getClassName = function () {
  94593. return "HighlightLayer";
  94594. };
  94595. /**
  94596. * Serializes this Highlight layer
  94597. * @returns a serialized Highlight layer object
  94598. */
  94599. HighlightLayer.prototype.serialize = function () {
  94600. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  94601. serializationObject.customType = "BABYLON.HighlightLayer";
  94602. // Highlighted meshes
  94603. serializationObject.meshes = [];
  94604. if (this._meshes) {
  94605. for (var m in this._meshes) {
  94606. var mesh = this._meshes[m];
  94607. if (mesh) {
  94608. serializationObject.meshes.push({
  94609. glowEmissiveOnly: mesh.glowEmissiveOnly,
  94610. color: mesh.color.asArray(),
  94611. meshId: mesh.mesh.id
  94612. });
  94613. }
  94614. }
  94615. }
  94616. // Excluded meshes
  94617. serializationObject.excludedMeshes = [];
  94618. if (this._excludedMeshes) {
  94619. for (var e in this._excludedMeshes) {
  94620. var excludedMesh = this._excludedMeshes[e];
  94621. if (excludedMesh) {
  94622. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  94623. }
  94624. }
  94625. }
  94626. return serializationObject;
  94627. };
  94628. /**
  94629. * Creates a Highlight layer from parsed Highlight layer data
  94630. * @param parsedHightlightLayer defines the Highlight layer data
  94631. * @param scene defines the current scene
  94632. * @param rootUrl defines the root URL containing the Highlight layer information
  94633. * @returns a parsed Highlight layer
  94634. */
  94635. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  94636. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  94637. var index;
  94638. // Excluded meshes
  94639. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  94640. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  94641. if (mesh) {
  94642. hl.addExcludedMesh(mesh);
  94643. }
  94644. }
  94645. // Included meshes
  94646. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  94647. var highlightedMesh = parsedHightlightLayer.meshes[index];
  94648. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  94649. if (mesh) {
  94650. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  94651. }
  94652. }
  94653. return hl;
  94654. };
  94655. /**
  94656. * Effect Name of the highlight layer.
  94657. */
  94658. HighlightLayer.EffectName = "HighlightLayer";
  94659. /**
  94660. * The neutral color used during the preparation of the glow effect.
  94661. * This is black by default as the blend operation is a blend operation.
  94662. */
  94663. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  94664. /**
  94665. * Stencil value used for glowing meshes.
  94666. */
  94667. HighlightLayer.GlowingMeshStencilReference = 0x02;
  94668. /**
  94669. * Stencil value used for the other meshes in the scene.
  94670. */
  94671. HighlightLayer.NormalMeshStencilReference = 0x01;
  94672. __decorate([
  94673. BABYLON.serialize()
  94674. ], HighlightLayer.prototype, "innerGlow", void 0);
  94675. __decorate([
  94676. BABYLON.serialize()
  94677. ], HighlightLayer.prototype, "outerGlow", void 0);
  94678. __decorate([
  94679. BABYLON.serialize()
  94680. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  94681. __decorate([
  94682. BABYLON.serialize()
  94683. ], HighlightLayer.prototype, "blurVerticalSize", null);
  94684. __decorate([
  94685. BABYLON.serialize("options")
  94686. ], HighlightLayer.prototype, "_options", void 0);
  94687. return HighlightLayer;
  94688. }(BABYLON.EffectLayer));
  94689. BABYLON.HighlightLayer = HighlightLayer;
  94690. })(BABYLON || (BABYLON = {}));
  94691. //# sourceMappingURL=babylon.highlightLayer.js.map
  94692. var BABYLON;
  94693. (function (BABYLON) {
  94694. /**
  94695. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  94696. *
  94697. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  94698. * glowy meshes to your scene.
  94699. *
  94700. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  94701. */
  94702. var GlowLayer = /** @class */ (function (_super) {
  94703. __extends(GlowLayer, _super);
  94704. /**
  94705. * Instantiates a new glow Layer and references it to the scene.
  94706. * @param name The name of the layer
  94707. * @param scene The scene to use the layer in
  94708. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  94709. */
  94710. function GlowLayer(name, scene, options) {
  94711. var _this = _super.call(this, name, scene) || this;
  94712. _this._intensity = 1.0;
  94713. _this._includedOnlyMeshes = [];
  94714. _this._excludedMeshes = [];
  94715. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  94716. // Adapt options
  94717. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  94718. // Initialize the layer
  94719. _this._init({
  94720. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  94721. camera: _this._options.camera,
  94722. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  94723. mainTextureRatio: _this._options.mainTextureRatio
  94724. });
  94725. return _this;
  94726. }
  94727. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  94728. /**
  94729. * Gets the kernel size of the blur.
  94730. */
  94731. get: function () {
  94732. return this._horizontalBlurPostprocess1.kernel;
  94733. },
  94734. /**
  94735. * Sets the kernel size of the blur.
  94736. */
  94737. set: function (value) {
  94738. this._horizontalBlurPostprocess1.kernel = value;
  94739. this._verticalBlurPostprocess1.kernel = value;
  94740. this._horizontalBlurPostprocess2.kernel = value;
  94741. this._verticalBlurPostprocess2.kernel = value;
  94742. },
  94743. enumerable: true,
  94744. configurable: true
  94745. });
  94746. Object.defineProperty(GlowLayer.prototype, "intensity", {
  94747. /**
  94748. * Gets the glow intensity.
  94749. */
  94750. get: function () {
  94751. return this._intensity;
  94752. },
  94753. /**
  94754. * Sets the glow intensity.
  94755. */
  94756. set: function (value) {
  94757. this._intensity = value;
  94758. },
  94759. enumerable: true,
  94760. configurable: true
  94761. });
  94762. /**
  94763. * Get the effect name of the layer.
  94764. * @return The effect name
  94765. */
  94766. GlowLayer.prototype.getEffectName = function () {
  94767. return GlowLayer.EffectName;
  94768. };
  94769. /**
  94770. * Create the merge effect. This is the shader use to blit the information back
  94771. * to the main canvas at the end of the scene rendering.
  94772. */
  94773. GlowLayer.prototype._createMergeEffect = function () {
  94774. // Effect
  94775. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  94776. };
  94777. /**
  94778. * Creates the render target textures and post processes used in the glow layer.
  94779. */
  94780. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  94781. var _this = this;
  94782. var blurTextureWidth = this._mainTextureDesiredSize.width;
  94783. var blurTextureHeight = this._mainTextureDesiredSize.height;
  94784. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  94785. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  94786. var textureType = 0;
  94787. if (this._engine.getCaps().textureHalfFloatRender) {
  94788. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94789. }
  94790. else {
  94791. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94792. }
  94793. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  94794. width: blurTextureWidth,
  94795. height: blurTextureHeight
  94796. }, this._scene, false, true, textureType);
  94797. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94798. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94799. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94800. this._blurTexture1.renderParticles = false;
  94801. this._blurTexture1.ignoreCameraViewport = true;
  94802. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  94803. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  94804. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  94805. width: blurTextureWidth2,
  94806. height: blurTextureHeight2
  94807. }, this._scene, false, true, textureType);
  94808. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94809. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94810. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94811. this._blurTexture2.renderParticles = false;
  94812. this._blurTexture2.ignoreCameraViewport = true;
  94813. this._textures = [this._blurTexture1, this._blurTexture2];
  94814. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  94815. width: blurTextureWidth,
  94816. height: blurTextureHeight
  94817. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94818. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  94819. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  94820. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  94821. effect.setTexture("textureSampler", _this._mainTexture);
  94822. });
  94823. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  94824. width: blurTextureWidth,
  94825. height: blurTextureHeight
  94826. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94827. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  94828. width: blurTextureWidth2,
  94829. height: blurTextureHeight2
  94830. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94831. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  94832. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  94833. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  94834. effect.setTexture("textureSampler", _this._blurTexture1);
  94835. });
  94836. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  94837. width: blurTextureWidth2,
  94838. height: blurTextureHeight2
  94839. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94840. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  94841. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  94842. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  94843. this._mainTexture.samples = this._options.mainTextureSamples;
  94844. this._mainTexture.onAfterUnbindObservable.add(function () {
  94845. var internalTexture = _this._blurTexture1.getInternalTexture();
  94846. if (internalTexture) {
  94847. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  94848. internalTexture = _this._blurTexture2.getInternalTexture();
  94849. if (internalTexture) {
  94850. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  94851. }
  94852. }
  94853. });
  94854. // Prevent autoClear.
  94855. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  94856. };
  94857. /**
  94858. * Checks for the readiness of the element composing the layer.
  94859. * @param subMesh the mesh to check for
  94860. * @param useInstances specify wether or not to use instances to render the mesh
  94861. * @param emissiveTexture the associated emissive texture used to generate the glow
  94862. * @return true if ready otherwise, false
  94863. */
  94864. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  94865. var material = subMesh.getMaterial();
  94866. var mesh = subMesh.getRenderingMesh();
  94867. if (!material || !mesh) {
  94868. return false;
  94869. }
  94870. var emissiveTexture = material.emissiveTexture;
  94871. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  94872. };
  94873. /**
  94874. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  94875. */
  94876. GlowLayer.prototype.needStencil = function () {
  94877. return false;
  94878. };
  94879. /**
  94880. * Implementation specific of rendering the generating effect on the main canvas.
  94881. * @param effect The effect used to render through
  94882. */
  94883. GlowLayer.prototype._internalRender = function (effect) {
  94884. // Texture
  94885. effect.setTexture("textureSampler", this._blurTexture1);
  94886. effect.setTexture("textureSampler2", this._blurTexture2);
  94887. effect.setFloat("offset", this._intensity);
  94888. // Cache
  94889. var engine = this._engine;
  94890. var previousStencilBuffer = engine.getStencilBuffer();
  94891. // Draw order
  94892. engine.setStencilBuffer(false);
  94893. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94894. // Draw order
  94895. engine.setStencilBuffer(previousStencilBuffer);
  94896. };
  94897. /**
  94898. * Sets the required values for both the emissive texture and and the main color.
  94899. */
  94900. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  94901. var textureLevel = 1.0;
  94902. if (this.customEmissiveTextureSelector) {
  94903. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  94904. }
  94905. else {
  94906. if (material) {
  94907. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  94908. if (this._emissiveTextureAndColor.texture) {
  94909. textureLevel = this._emissiveTextureAndColor.texture.level;
  94910. }
  94911. }
  94912. else {
  94913. this._emissiveTextureAndColor.texture = null;
  94914. }
  94915. }
  94916. if (this.customEmissiveColorSelector) {
  94917. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  94918. }
  94919. else {
  94920. if (material.emissiveColor) {
  94921. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  94922. }
  94923. else {
  94924. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  94925. }
  94926. }
  94927. };
  94928. /**
  94929. * Returns true if the mesh should render, otherwise false.
  94930. * @param mesh The mesh to render
  94931. * @returns true if it should render otherwise false
  94932. */
  94933. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  94934. return this.hasMesh(mesh);
  94935. };
  94936. /**
  94937. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  94938. * @param mesh The mesh to exclude from the glow layer
  94939. */
  94940. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  94941. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  94942. this._excludedMeshes.push(mesh.uniqueId);
  94943. }
  94944. };
  94945. /**
  94946. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  94947. * @param mesh The mesh to remove
  94948. */
  94949. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  94950. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  94951. if (index !== -1) {
  94952. this._excludedMeshes.splice(index, 1);
  94953. }
  94954. };
  94955. /**
  94956. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  94957. * @param mesh The mesh to include in the glow layer
  94958. */
  94959. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  94960. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  94961. this._includedOnlyMeshes.push(mesh.uniqueId);
  94962. }
  94963. };
  94964. /**
  94965. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  94966. * @param mesh The mesh to remove
  94967. */
  94968. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  94969. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  94970. if (index !== -1) {
  94971. this._includedOnlyMeshes.splice(index, 1);
  94972. }
  94973. };
  94974. /**
  94975. * Determine if a given mesh will be used in the glow layer
  94976. * @param mesh The mesh to test
  94977. * @returns true if the mesh will be highlighted by the current glow layer
  94978. */
  94979. GlowLayer.prototype.hasMesh = function (mesh) {
  94980. // Included Mesh
  94981. if (this._includedOnlyMeshes.length) {
  94982. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  94983. }
  94984. ;
  94985. // Excluded Mesh
  94986. if (this._excludedMeshes.length) {
  94987. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  94988. }
  94989. ;
  94990. return true;
  94991. };
  94992. /**
  94993. * Free any resources and references associated to a mesh.
  94994. * Internal use
  94995. * @param mesh The mesh to free.
  94996. */
  94997. GlowLayer.prototype._disposeMesh = function (mesh) {
  94998. this.removeIncludedOnlyMesh(mesh);
  94999. this.removeExcludedMesh(mesh);
  95000. };
  95001. /**
  95002. * Gets the class name of the effect layer
  95003. * @returns the string with the class name of the effect layer
  95004. */
  95005. GlowLayer.prototype.getClassName = function () {
  95006. return "GlowLayer";
  95007. };
  95008. /**
  95009. * Serializes this glow layer
  95010. * @returns a serialized glow layer object
  95011. */
  95012. GlowLayer.prototype.serialize = function () {
  95013. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  95014. serializationObject.customType = "BABYLON.GlowLayer";
  95015. var index;
  95016. // Included meshes
  95017. serializationObject.includedMeshes = [];
  95018. if (this._includedOnlyMeshes.length) {
  95019. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  95020. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  95021. if (mesh) {
  95022. serializationObject.includedMeshes.push(mesh.id);
  95023. }
  95024. }
  95025. }
  95026. // Excluded meshes
  95027. serializationObject.excludedMeshes = [];
  95028. if (this._excludedMeshes.length) {
  95029. for (index = 0; index < this._excludedMeshes.length; index++) {
  95030. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  95031. if (mesh) {
  95032. serializationObject.excludedMeshes.push(mesh.id);
  95033. }
  95034. }
  95035. }
  95036. return serializationObject;
  95037. };
  95038. /**
  95039. * Creates a Glow Layer from parsed glow layer data
  95040. * @param parsedGlowLayer defines glow layer data
  95041. * @param scene defines the current scene
  95042. * @param rootUrl defines the root URL containing the glow layer information
  95043. * @returns a parsed Glow Layer
  95044. */
  95045. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  95046. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  95047. var index;
  95048. // Excluded meshes
  95049. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  95050. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  95051. if (mesh) {
  95052. gl.addExcludedMesh(mesh);
  95053. }
  95054. }
  95055. // Included meshes
  95056. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  95057. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  95058. if (mesh) {
  95059. gl.addIncludedOnlyMesh(mesh);
  95060. }
  95061. }
  95062. return gl;
  95063. };
  95064. /**
  95065. * Effect Name of the layer.
  95066. */
  95067. GlowLayer.EffectName = "GlowLayer";
  95068. /**
  95069. * The default blur kernel size used for the glow.
  95070. */
  95071. GlowLayer.DefaultBlurKernelSize = 32;
  95072. /**
  95073. * The default texture size ratio used for the glow.
  95074. */
  95075. GlowLayer.DefaultTextureRatio = 0.5;
  95076. __decorate([
  95077. BABYLON.serialize()
  95078. ], GlowLayer.prototype, "blurKernelSize", null);
  95079. __decorate([
  95080. BABYLON.serialize()
  95081. ], GlowLayer.prototype, "intensity", null);
  95082. __decorate([
  95083. BABYLON.serialize("options")
  95084. ], GlowLayer.prototype, "_options", void 0);
  95085. return GlowLayer;
  95086. }(BABYLON.EffectLayer));
  95087. BABYLON.GlowLayer = GlowLayer;
  95088. })(BABYLON || (BABYLON = {}));
  95089. //# sourceMappingURL=babylon.glowLayer.js.map
  95090. var BABYLON;
  95091. (function (BABYLON) {
  95092. /**
  95093. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  95094. */
  95095. var AssetTaskState;
  95096. (function (AssetTaskState) {
  95097. /**
  95098. * Initialization
  95099. */
  95100. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  95101. /**
  95102. * Running
  95103. */
  95104. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  95105. /**
  95106. * Done
  95107. */
  95108. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  95109. /**
  95110. * Error
  95111. */
  95112. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  95113. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  95114. /**
  95115. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  95116. */
  95117. var AbstractAssetTask = /** @class */ (function () {
  95118. /**
  95119. * Creates a new {BABYLON.AssetsManager}
  95120. * @param name defines the name of the task
  95121. */
  95122. function AbstractAssetTask(
  95123. /**
  95124. * Task name
  95125. */ name) {
  95126. this.name = name;
  95127. this._isCompleted = false;
  95128. this._taskState = AssetTaskState.INIT;
  95129. }
  95130. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  95131. /**
  95132. * Get if the task is completed
  95133. */
  95134. get: function () {
  95135. return this._isCompleted;
  95136. },
  95137. enumerable: true,
  95138. configurable: true
  95139. });
  95140. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  95141. /**
  95142. * Gets the current state of the task
  95143. */
  95144. get: function () {
  95145. return this._taskState;
  95146. },
  95147. enumerable: true,
  95148. configurable: true
  95149. });
  95150. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  95151. /**
  95152. * Gets the current error object (if task is in error)
  95153. */
  95154. get: function () {
  95155. return this._errorObject;
  95156. },
  95157. enumerable: true,
  95158. configurable: true
  95159. });
  95160. /**
  95161. * Internal only
  95162. * @hidden
  95163. */
  95164. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  95165. if (this._errorObject) {
  95166. return;
  95167. }
  95168. this._errorObject = {
  95169. message: message,
  95170. exception: exception
  95171. };
  95172. };
  95173. /**
  95174. * Execute the current task
  95175. * @param scene defines the scene where you want your assets to be loaded
  95176. * @param onSuccess is a callback called when the task is successfully executed
  95177. * @param onError is a callback called if an error occurs
  95178. */
  95179. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  95180. var _this = this;
  95181. this._taskState = AssetTaskState.RUNNING;
  95182. this.runTask(scene, function () {
  95183. _this.onDoneCallback(onSuccess, onError);
  95184. }, function (msg, exception) {
  95185. _this.onErrorCallback(onError, msg, exception);
  95186. });
  95187. };
  95188. /**
  95189. * Execute the current task
  95190. * @param scene defines the scene where you want your assets to be loaded
  95191. * @param onSuccess is a callback called when the task is successfully executed
  95192. * @param onError is a callback called if an error occurs
  95193. */
  95194. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95195. throw new Error("runTask is not implemented");
  95196. };
  95197. /**
  95198. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  95199. * This can be used with failed tasks that have the reason for failure fixed.
  95200. */
  95201. AbstractAssetTask.prototype.reset = function () {
  95202. this._taskState = AssetTaskState.INIT;
  95203. };
  95204. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  95205. this._taskState = AssetTaskState.ERROR;
  95206. this._errorObject = {
  95207. message: message,
  95208. exception: exception
  95209. };
  95210. if (this.onError) {
  95211. this.onError(this, message, exception);
  95212. }
  95213. onError();
  95214. };
  95215. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  95216. try {
  95217. this._taskState = AssetTaskState.DONE;
  95218. this._isCompleted = true;
  95219. if (this.onSuccess) {
  95220. this.onSuccess(this);
  95221. }
  95222. onSuccess();
  95223. }
  95224. catch (e) {
  95225. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  95226. }
  95227. };
  95228. return AbstractAssetTask;
  95229. }());
  95230. BABYLON.AbstractAssetTask = AbstractAssetTask;
  95231. /**
  95232. * Class used to share progress information about assets loading
  95233. */
  95234. var AssetsProgressEvent = /** @class */ (function () {
  95235. /**
  95236. * Creates a {BABYLON.AssetsProgressEvent}
  95237. * @param remainingCount defines the number of remaining tasks to process
  95238. * @param totalCount defines the total number of tasks
  95239. * @param task defines the task that was just processed
  95240. */
  95241. function AssetsProgressEvent(remainingCount, totalCount, task) {
  95242. this.remainingCount = remainingCount;
  95243. this.totalCount = totalCount;
  95244. this.task = task;
  95245. }
  95246. return AssetsProgressEvent;
  95247. }());
  95248. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  95249. /**
  95250. * Define a task used by {BABYLON.AssetsManager} to load meshes
  95251. */
  95252. var MeshAssetTask = /** @class */ (function (_super) {
  95253. __extends(MeshAssetTask, _super);
  95254. /**
  95255. * Creates a new {BABYLON.MeshAssetTask}
  95256. * @param name defines the name of the task
  95257. * @param meshesNames defines the list of mesh's names you want to load
  95258. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  95259. * @param sceneFilename defines the filename of the scene to load from
  95260. */
  95261. function MeshAssetTask(
  95262. /**
  95263. * Defines the name of the task
  95264. */
  95265. name,
  95266. /**
  95267. * Defines the list of mesh's names you want to load
  95268. */
  95269. meshesNames,
  95270. /**
  95271. * Defines the root url to use as a base to load your meshes and associated resources
  95272. */
  95273. rootUrl,
  95274. /**
  95275. * Defines the filename of the scene to load from
  95276. */
  95277. sceneFilename) {
  95278. var _this = _super.call(this, name) || this;
  95279. _this.name = name;
  95280. _this.meshesNames = meshesNames;
  95281. _this.rootUrl = rootUrl;
  95282. _this.sceneFilename = sceneFilename;
  95283. return _this;
  95284. }
  95285. /**
  95286. * Execute the current task
  95287. * @param scene defines the scene where you want your assets to be loaded
  95288. * @param onSuccess is a callback called when the task is successfully executed
  95289. * @param onError is a callback called if an error occurs
  95290. */
  95291. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95292. var _this = this;
  95293. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  95294. _this.loadedMeshes = meshes;
  95295. _this.loadedParticleSystems = particleSystems;
  95296. _this.loadedSkeletons = skeletons;
  95297. onSuccess();
  95298. }, null, function (scene, message, exception) {
  95299. onError(message, exception);
  95300. });
  95301. };
  95302. return MeshAssetTask;
  95303. }(AbstractAssetTask));
  95304. BABYLON.MeshAssetTask = MeshAssetTask;
  95305. /**
  95306. * Define a task used by {BABYLON.AssetsManager} to load text content
  95307. */
  95308. var TextFileAssetTask = /** @class */ (function (_super) {
  95309. __extends(TextFileAssetTask, _super);
  95310. /**
  95311. * Creates a new TextFileAssetTask object
  95312. * @param name defines the name of the task
  95313. * @param url defines the location of the file to load
  95314. */
  95315. function TextFileAssetTask(
  95316. /**
  95317. * Defines the name of the task
  95318. */
  95319. name,
  95320. /**
  95321. * Defines the location of the file to load
  95322. */
  95323. url) {
  95324. var _this = _super.call(this, name) || this;
  95325. _this.name = name;
  95326. _this.url = url;
  95327. return _this;
  95328. }
  95329. /**
  95330. * Execute the current task
  95331. * @param scene defines the scene where you want your assets to be loaded
  95332. * @param onSuccess is a callback called when the task is successfully executed
  95333. * @param onError is a callback called if an error occurs
  95334. */
  95335. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95336. var _this = this;
  95337. scene._loadFile(this.url, function (data) {
  95338. _this.text = data;
  95339. onSuccess();
  95340. }, undefined, false, false, function (request, exception) {
  95341. if (request) {
  95342. onError(request.status + " " + request.statusText, exception);
  95343. }
  95344. });
  95345. };
  95346. return TextFileAssetTask;
  95347. }(AbstractAssetTask));
  95348. BABYLON.TextFileAssetTask = TextFileAssetTask;
  95349. /**
  95350. * Define a task used by {BABYLON.AssetsManager} to load binary data
  95351. */
  95352. var BinaryFileAssetTask = /** @class */ (function (_super) {
  95353. __extends(BinaryFileAssetTask, _super);
  95354. /**
  95355. * Creates a new BinaryFileAssetTask object
  95356. * @param name defines the name of the new task
  95357. * @param url defines the location of the file to load
  95358. */
  95359. function BinaryFileAssetTask(
  95360. /**
  95361. * Defines the name of the task
  95362. */
  95363. name,
  95364. /**
  95365. * Defines the location of the file to load
  95366. */
  95367. url) {
  95368. var _this = _super.call(this, name) || this;
  95369. _this.name = name;
  95370. _this.url = url;
  95371. return _this;
  95372. }
  95373. /**
  95374. * Execute the current task
  95375. * @param scene defines the scene where you want your assets to be loaded
  95376. * @param onSuccess is a callback called when the task is successfully executed
  95377. * @param onError is a callback called if an error occurs
  95378. */
  95379. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95380. var _this = this;
  95381. scene._loadFile(this.url, function (data) {
  95382. _this.data = data;
  95383. onSuccess();
  95384. }, undefined, true, true, function (request, exception) {
  95385. if (request) {
  95386. onError(request.status + " " + request.statusText, exception);
  95387. }
  95388. });
  95389. };
  95390. return BinaryFileAssetTask;
  95391. }(AbstractAssetTask));
  95392. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  95393. /**
  95394. * Define a task used by {BABYLON.AssetsManager} to load images
  95395. */
  95396. var ImageAssetTask = /** @class */ (function (_super) {
  95397. __extends(ImageAssetTask, _super);
  95398. /**
  95399. * Creates a new ImageAssetTask
  95400. * @param name defines the name of the task
  95401. * @param url defines the location of the image to load
  95402. */
  95403. function ImageAssetTask(
  95404. /**
  95405. * Defines the name of the task
  95406. */
  95407. name,
  95408. /**
  95409. * Defines the location of the image to load
  95410. */
  95411. url) {
  95412. var _this = _super.call(this, name) || this;
  95413. _this.name = name;
  95414. _this.url = url;
  95415. return _this;
  95416. }
  95417. /**
  95418. * Execute the current task
  95419. * @param scene defines the scene where you want your assets to be loaded
  95420. * @param onSuccess is a callback called when the task is successfully executed
  95421. * @param onError is a callback called if an error occurs
  95422. */
  95423. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95424. var _this = this;
  95425. var img = new Image();
  95426. BABYLON.Tools.SetCorsBehavior(this.url, img);
  95427. img.onload = function () {
  95428. _this.image = img;
  95429. onSuccess();
  95430. };
  95431. img.onerror = function (err) {
  95432. onError("Error loading image", err);
  95433. };
  95434. img.src = this.url;
  95435. };
  95436. return ImageAssetTask;
  95437. }(AbstractAssetTask));
  95438. BABYLON.ImageAssetTask = ImageAssetTask;
  95439. /**
  95440. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  95441. */
  95442. var TextureAssetTask = /** @class */ (function (_super) {
  95443. __extends(TextureAssetTask, _super);
  95444. /**
  95445. * Creates a new TextureAssetTask object
  95446. * @param name defines the name of the task
  95447. * @param url defines the location of the file to load
  95448. * @param noMipmap defines if mipmap should not be generated (default is false)
  95449. * @param invertY defines if texture must be inverted on Y axis (default is false)
  95450. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  95451. */
  95452. function TextureAssetTask(
  95453. /**
  95454. * Defines the name of the task
  95455. */
  95456. name,
  95457. /**
  95458. * Defines the location of the file to load
  95459. */
  95460. url,
  95461. /**
  95462. * Defines if mipmap should not be generated (default is false)
  95463. */
  95464. noMipmap,
  95465. /**
  95466. * Defines if texture must be inverted on Y axis (default is false)
  95467. */
  95468. invertY,
  95469. /**
  95470. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  95471. */
  95472. samplingMode) {
  95473. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95474. var _this = _super.call(this, name) || this;
  95475. _this.name = name;
  95476. _this.url = url;
  95477. _this.noMipmap = noMipmap;
  95478. _this.invertY = invertY;
  95479. _this.samplingMode = samplingMode;
  95480. return _this;
  95481. }
  95482. /**
  95483. * Execute the current task
  95484. * @param scene defines the scene where you want your assets to be loaded
  95485. * @param onSuccess is a callback called when the task is successfully executed
  95486. * @param onError is a callback called if an error occurs
  95487. */
  95488. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95489. var onload = function () {
  95490. onSuccess();
  95491. };
  95492. var onerror = function (message, exception) {
  95493. onError(message, exception);
  95494. };
  95495. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  95496. };
  95497. return TextureAssetTask;
  95498. }(AbstractAssetTask));
  95499. BABYLON.TextureAssetTask = TextureAssetTask;
  95500. /**
  95501. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  95502. */
  95503. var CubeTextureAssetTask = /** @class */ (function (_super) {
  95504. __extends(CubeTextureAssetTask, _super);
  95505. /**
  95506. * Creates a new CubeTextureAssetTask
  95507. * @param name defines the name of the task
  95508. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  95509. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  95510. * @param noMipmap defines if mipmaps should not be generated (default is false)
  95511. * @param files defines the explicit list of files (undefined by default)
  95512. */
  95513. function CubeTextureAssetTask(
  95514. /**
  95515. * Defines the name of the task
  95516. */
  95517. name,
  95518. /**
  95519. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  95520. */
  95521. url,
  95522. /**
  95523. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  95524. */
  95525. extensions,
  95526. /**
  95527. * Defines if mipmaps should not be generated (default is false)
  95528. */
  95529. noMipmap,
  95530. /**
  95531. * Defines the explicit list of files (undefined by default)
  95532. */
  95533. files) {
  95534. var _this = _super.call(this, name) || this;
  95535. _this.name = name;
  95536. _this.url = url;
  95537. _this.extensions = extensions;
  95538. _this.noMipmap = noMipmap;
  95539. _this.files = files;
  95540. return _this;
  95541. }
  95542. /**
  95543. * Execute the current task
  95544. * @param scene defines the scene where you want your assets to be loaded
  95545. * @param onSuccess is a callback called when the task is successfully executed
  95546. * @param onError is a callback called if an error occurs
  95547. */
  95548. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95549. var onload = function () {
  95550. onSuccess();
  95551. };
  95552. var onerror = function (message, exception) {
  95553. onError(message, exception);
  95554. };
  95555. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  95556. };
  95557. return CubeTextureAssetTask;
  95558. }(AbstractAssetTask));
  95559. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  95560. /**
  95561. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  95562. */
  95563. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  95564. __extends(HDRCubeTextureAssetTask, _super);
  95565. /**
  95566. * Creates a new HDRCubeTextureAssetTask object
  95567. * @param name defines the name of the task
  95568. * @param url defines the location of the file to load
  95569. * @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.
  95570. * @param noMipmap defines if mipmaps should not be generated (default is false)
  95571. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  95572. * @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)
  95573. * @param reserved Internal use only
  95574. */
  95575. function HDRCubeTextureAssetTask(
  95576. /**
  95577. * Defines the name of the task
  95578. */
  95579. name,
  95580. /**
  95581. * Defines the location of the file to load
  95582. */
  95583. url,
  95584. /**
  95585. * Defines the desired size (the more it increases the longer the generation will be)
  95586. */
  95587. size,
  95588. /**
  95589. * Defines if mipmaps should not be generated (default is false)
  95590. */
  95591. noMipmap,
  95592. /**
  95593. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  95594. */
  95595. generateHarmonics,
  95596. /**
  95597. * 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)
  95598. */
  95599. gammaSpace,
  95600. /**
  95601. * Internal Use Only
  95602. */
  95603. reserved) {
  95604. if (noMipmap === void 0) { noMipmap = false; }
  95605. if (generateHarmonics === void 0) { generateHarmonics = true; }
  95606. if (gammaSpace === void 0) { gammaSpace = false; }
  95607. if (reserved === void 0) { reserved = false; }
  95608. var _this = _super.call(this, name) || this;
  95609. _this.name = name;
  95610. _this.url = url;
  95611. _this.size = size;
  95612. _this.noMipmap = noMipmap;
  95613. _this.generateHarmonics = generateHarmonics;
  95614. _this.gammaSpace = gammaSpace;
  95615. _this.reserved = reserved;
  95616. return _this;
  95617. }
  95618. /**
  95619. * Execute the current task
  95620. * @param scene defines the scene where you want your assets to be loaded
  95621. * @param onSuccess is a callback called when the task is successfully executed
  95622. * @param onError is a callback called if an error occurs
  95623. */
  95624. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  95625. var onload = function () {
  95626. onSuccess();
  95627. };
  95628. var onerror = function (message, exception) {
  95629. onError(message, exception);
  95630. };
  95631. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  95632. };
  95633. return HDRCubeTextureAssetTask;
  95634. }(AbstractAssetTask));
  95635. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  95636. /**
  95637. * This class can be used to easily import assets into a scene
  95638. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  95639. */
  95640. var AssetsManager = /** @class */ (function () {
  95641. /**
  95642. * Creates a new AssetsManager
  95643. * @param scene defines the scene to work on
  95644. */
  95645. function AssetsManager(scene) {
  95646. this._isLoading = false;
  95647. this._tasks = new Array();
  95648. this._waitingTasksCount = 0;
  95649. this._totalTasksCount = 0;
  95650. /**
  95651. * Observable called when all tasks are processed
  95652. */
  95653. this.onTaskSuccessObservable = new BABYLON.Observable();
  95654. /**
  95655. * Observable called when a task had an error
  95656. */
  95657. this.onTaskErrorObservable = new BABYLON.Observable();
  95658. /**
  95659. * Observable called when a task is successful
  95660. */
  95661. this.onTasksDoneObservable = new BABYLON.Observable();
  95662. /**
  95663. * Observable called when a task is done (whatever the result is)
  95664. */
  95665. this.onProgressObservable = new BABYLON.Observable();
  95666. /**
  95667. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  95668. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  95669. */
  95670. this.useDefaultLoadingScreen = true;
  95671. this._scene = scene;
  95672. }
  95673. /**
  95674. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  95675. * @param taskName defines the name of the new task
  95676. * @param meshesNames defines the name of meshes to load
  95677. * @param rootUrl defines the root url to use to locate files
  95678. * @param sceneFilename defines the filename of the scene file
  95679. * @returns a new {BABYLON.MeshAssetTask} object
  95680. */
  95681. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  95682. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  95683. this._tasks.push(task);
  95684. return task;
  95685. };
  95686. /**
  95687. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  95688. * @param taskName defines the name of the new task
  95689. * @param url defines the url of the file to load
  95690. * @returns a new {BABYLON.TextFileAssetTask} object
  95691. */
  95692. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  95693. var task = new TextFileAssetTask(taskName, url);
  95694. this._tasks.push(task);
  95695. return task;
  95696. };
  95697. /**
  95698. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  95699. * @param taskName defines the name of the new task
  95700. * @param url defines the url of the file to load
  95701. * @returns a new {BABYLON.BinaryFileAssetTask} object
  95702. */
  95703. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  95704. var task = new BinaryFileAssetTask(taskName, url);
  95705. this._tasks.push(task);
  95706. return task;
  95707. };
  95708. /**
  95709. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  95710. * @param taskName defines the name of the new task
  95711. * @param url defines the url of the file to load
  95712. * @returns a new {BABYLON.ImageAssetTask} object
  95713. */
  95714. AssetsManager.prototype.addImageTask = function (taskName, url) {
  95715. var task = new ImageAssetTask(taskName, url);
  95716. this._tasks.push(task);
  95717. return task;
  95718. };
  95719. /**
  95720. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  95721. * @param taskName defines the name of the new task
  95722. * @param url defines the url of the file to load
  95723. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  95724. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  95725. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  95726. * @returns a new {BABYLON.TextureAssetTask} object
  95727. */
  95728. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  95729. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95730. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  95731. this._tasks.push(task);
  95732. return task;
  95733. };
  95734. /**
  95735. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  95736. * @param taskName defines the name of the new task
  95737. * @param url defines the url of the file to load
  95738. * @param extensions defines the extension to use to load the cube map (can be null)
  95739. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  95740. * @param files defines the list of files to load (can be null)
  95741. * @returns a new {BABYLON.CubeTextureAssetTask} object
  95742. */
  95743. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  95744. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  95745. this._tasks.push(task);
  95746. return task;
  95747. };
  95748. /**
  95749. *
  95750. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  95751. * @param taskName defines the name of the new task
  95752. * @param url defines the url of the file to load
  95753. * @param size defines the size you want for the cubemap (can be null)
  95754. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  95755. * @param generateHarmonics defines if you want to automatically generate (true by default)
  95756. * @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)
  95757. * @param reserved Internal use only
  95758. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  95759. */
  95760. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  95761. if (noMipmap === void 0) { noMipmap = false; }
  95762. if (generateHarmonics === void 0) { generateHarmonics = true; }
  95763. if (gammaSpace === void 0) { gammaSpace = false; }
  95764. if (reserved === void 0) { reserved = false; }
  95765. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  95766. this._tasks.push(task);
  95767. return task;
  95768. };
  95769. /**
  95770. * Remove a task from the assets manager.
  95771. * @param task the task to remove
  95772. */
  95773. AssetsManager.prototype.removeTask = function (task) {
  95774. var index = this._tasks.indexOf(task);
  95775. if (index > -1) {
  95776. this._tasks.splice(index, 1);
  95777. }
  95778. };
  95779. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  95780. this._waitingTasksCount--;
  95781. try {
  95782. if (this.onProgress) {
  95783. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  95784. }
  95785. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  95786. }
  95787. catch (e) {
  95788. BABYLON.Tools.Error("Error running progress callbacks.");
  95789. console.log(e);
  95790. }
  95791. if (this._waitingTasksCount === 0) {
  95792. try {
  95793. if (this.onFinish) {
  95794. this.onFinish(this._tasks);
  95795. }
  95796. // Let's remove successfull tasks
  95797. var currentTasks = this._tasks.slice();
  95798. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  95799. var task = currentTasks_1[_i];
  95800. if (task.taskState === AssetTaskState.DONE) {
  95801. var index = this._tasks.indexOf(task);
  95802. if (index > -1) {
  95803. this._tasks.splice(index, 1);
  95804. }
  95805. }
  95806. }
  95807. this.onTasksDoneObservable.notifyObservers(this._tasks);
  95808. }
  95809. catch (e) {
  95810. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  95811. console.log(e);
  95812. }
  95813. this._isLoading = false;
  95814. this._scene.getEngine().hideLoadingUI();
  95815. }
  95816. };
  95817. AssetsManager.prototype._runTask = function (task) {
  95818. var _this = this;
  95819. var done = function () {
  95820. try {
  95821. if (_this.onTaskSuccess) {
  95822. _this.onTaskSuccess(task);
  95823. }
  95824. _this.onTaskSuccessObservable.notifyObservers(task);
  95825. _this._decreaseWaitingTasksCount(task);
  95826. }
  95827. catch (e) {
  95828. error("Error executing task success callbacks", e);
  95829. }
  95830. };
  95831. var error = function (message, exception) {
  95832. task._setErrorObject(message, exception);
  95833. if (_this.onTaskError) {
  95834. _this.onTaskError(task);
  95835. }
  95836. _this.onTaskErrorObservable.notifyObservers(task);
  95837. _this._decreaseWaitingTasksCount(task);
  95838. };
  95839. task.run(this._scene, done, error);
  95840. };
  95841. /**
  95842. * Reset the {BABYLON.AssetsManager} and remove all tasks
  95843. * @return the current instance of the {BABYLON.AssetsManager}
  95844. */
  95845. AssetsManager.prototype.reset = function () {
  95846. this._isLoading = false;
  95847. this._tasks = new Array();
  95848. return this;
  95849. };
  95850. /**
  95851. * Start the loading process
  95852. * @return the current instance of the {BABYLON.AssetsManager}
  95853. */
  95854. AssetsManager.prototype.load = function () {
  95855. if (this._isLoading) {
  95856. return this;
  95857. }
  95858. this._isLoading = true;
  95859. this._waitingTasksCount = this._tasks.length;
  95860. this._totalTasksCount = this._tasks.length;
  95861. if (this._waitingTasksCount === 0) {
  95862. this._isLoading = false;
  95863. if (this.onFinish) {
  95864. this.onFinish(this._tasks);
  95865. }
  95866. this.onTasksDoneObservable.notifyObservers(this._tasks);
  95867. return this;
  95868. }
  95869. if (this.useDefaultLoadingScreen) {
  95870. this._scene.getEngine().displayLoadingUI();
  95871. }
  95872. for (var index = 0; index < this._tasks.length; index++) {
  95873. var task = this._tasks[index];
  95874. if (task.taskState === AssetTaskState.INIT) {
  95875. this._runTask(task);
  95876. }
  95877. }
  95878. return this;
  95879. };
  95880. return AssetsManager;
  95881. }());
  95882. BABYLON.AssetsManager = AssetsManager;
  95883. })(BABYLON || (BABYLON = {}));
  95884. //# sourceMappingURL=babylon.assetsManager.js.map
  95885. var BABYLON;
  95886. (function (BABYLON) {
  95887. var serializedGeometries = [];
  95888. var serializeGeometry = function (geometry, serializationGeometries) {
  95889. if (serializedGeometries[geometry.id]) {
  95890. return;
  95891. }
  95892. if (geometry.doNotSerialize) {
  95893. return;
  95894. }
  95895. if (geometry instanceof BABYLON.BoxGeometry) {
  95896. serializationGeometries.boxes.push(geometry.serialize());
  95897. }
  95898. else if (geometry instanceof BABYLON.SphereGeometry) {
  95899. serializationGeometries.spheres.push(geometry.serialize());
  95900. }
  95901. else if (geometry instanceof BABYLON.CylinderGeometry) {
  95902. serializationGeometries.cylinders.push(geometry.serialize());
  95903. }
  95904. else if (geometry instanceof BABYLON.TorusGeometry) {
  95905. serializationGeometries.toruses.push(geometry.serialize());
  95906. }
  95907. else if (geometry instanceof BABYLON.GroundGeometry) {
  95908. serializationGeometries.grounds.push(geometry.serialize());
  95909. }
  95910. else if (geometry instanceof BABYLON.Plane) {
  95911. serializationGeometries.planes.push(geometry.serialize());
  95912. }
  95913. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  95914. serializationGeometries.torusKnots.push(geometry.serialize());
  95915. }
  95916. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  95917. throw new Error("Unknown primitive type");
  95918. }
  95919. else {
  95920. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  95921. }
  95922. serializedGeometries[geometry.id] = true;
  95923. };
  95924. var serializeMesh = function (mesh, serializationScene) {
  95925. var serializationObject = {};
  95926. // Geometry
  95927. var geometry = mesh._geometry;
  95928. if (geometry) {
  95929. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  95930. // 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
  95931. serializeGeometry(geometry, serializationScene.geometries);
  95932. }
  95933. }
  95934. // Custom
  95935. if (mesh.serialize) {
  95936. mesh.serialize(serializationObject);
  95937. }
  95938. return serializationObject;
  95939. };
  95940. var finalizeSingleMesh = function (mesh, serializationObject) {
  95941. //only works if the mesh is already loaded
  95942. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  95943. //serialize material
  95944. if (mesh.material) {
  95945. if (mesh.material instanceof BABYLON.MultiMaterial) {
  95946. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  95947. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  95948. serializationObject.multiMaterials.push(mesh.material.serialize());
  95949. }
  95950. }
  95951. else {
  95952. serializationObject.materials = serializationObject.materials || [];
  95953. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  95954. serializationObject.materials.push(mesh.material.serialize());
  95955. }
  95956. }
  95957. }
  95958. //serialize geometry
  95959. var geometry = mesh._geometry;
  95960. if (geometry) {
  95961. if (!serializationObject.geometries) {
  95962. serializationObject.geometries = {};
  95963. serializationObject.geometries.boxes = [];
  95964. serializationObject.geometries.spheres = [];
  95965. serializationObject.geometries.cylinders = [];
  95966. serializationObject.geometries.toruses = [];
  95967. serializationObject.geometries.grounds = [];
  95968. serializationObject.geometries.planes = [];
  95969. serializationObject.geometries.torusKnots = [];
  95970. serializationObject.geometries.vertexData = [];
  95971. }
  95972. serializeGeometry(geometry, serializationObject.geometries);
  95973. }
  95974. // Skeletons
  95975. if (mesh.skeleton) {
  95976. serializationObject.skeletons = serializationObject.skeletons || [];
  95977. serializationObject.skeletons.push(mesh.skeleton.serialize());
  95978. }
  95979. //serialize the actual mesh
  95980. serializationObject.meshes = serializationObject.meshes || [];
  95981. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  95982. }
  95983. };
  95984. var SceneSerializer = /** @class */ (function () {
  95985. function SceneSerializer() {
  95986. }
  95987. SceneSerializer.ClearCache = function () {
  95988. serializedGeometries = [];
  95989. };
  95990. SceneSerializer.Serialize = function (scene) {
  95991. var serializationObject = {};
  95992. SceneSerializer.ClearCache();
  95993. // Scene
  95994. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  95995. serializationObject.autoClear = scene.autoClear;
  95996. serializationObject.clearColor = scene.clearColor.asArray();
  95997. serializationObject.ambientColor = scene.ambientColor.asArray();
  95998. serializationObject.gravity = scene.gravity.asArray();
  95999. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  96000. serializationObject.workerCollisions = scene.workerCollisions;
  96001. // Fog
  96002. if (scene.fogMode && scene.fogMode !== 0) {
  96003. serializationObject.fogMode = scene.fogMode;
  96004. serializationObject.fogColor = scene.fogColor.asArray();
  96005. serializationObject.fogStart = scene.fogStart;
  96006. serializationObject.fogEnd = scene.fogEnd;
  96007. serializationObject.fogDensity = scene.fogDensity;
  96008. }
  96009. //Physics
  96010. if (scene.isPhysicsEnabled()) {
  96011. var physicEngine = scene.getPhysicsEngine();
  96012. if (physicEngine) {
  96013. serializationObject.physicsEnabled = true;
  96014. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  96015. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  96016. }
  96017. }
  96018. // Metadata
  96019. if (scene.metadata) {
  96020. serializationObject.metadata = scene.metadata;
  96021. }
  96022. // Morph targets
  96023. serializationObject.morphTargetManagers = [];
  96024. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  96025. var abstractMesh = _a[_i];
  96026. var manager = abstractMesh.morphTargetManager;
  96027. if (manager) {
  96028. serializationObject.morphTargetManagers.push(manager.serialize());
  96029. }
  96030. }
  96031. // Lights
  96032. serializationObject.lights = [];
  96033. var index;
  96034. var light;
  96035. for (index = 0; index < scene.lights.length; index++) {
  96036. light = scene.lights[index];
  96037. if (!light.doNotSerialize) {
  96038. serializationObject.lights.push(light.serialize());
  96039. }
  96040. }
  96041. // Cameras
  96042. serializationObject.cameras = [];
  96043. for (index = 0; index < scene.cameras.length; index++) {
  96044. var camera = scene.cameras[index];
  96045. if (!camera.doNotSerialize) {
  96046. serializationObject.cameras.push(camera.serialize());
  96047. }
  96048. }
  96049. if (scene.activeCamera) {
  96050. serializationObject.activeCameraID = scene.activeCamera.id;
  96051. }
  96052. // Animations
  96053. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  96054. // Materials
  96055. serializationObject.materials = [];
  96056. serializationObject.multiMaterials = [];
  96057. var material;
  96058. for (index = 0; index < scene.materials.length; index++) {
  96059. material = scene.materials[index];
  96060. if (!material.doNotSerialize) {
  96061. serializationObject.materials.push(material.serialize());
  96062. }
  96063. }
  96064. // MultiMaterials
  96065. serializationObject.multiMaterials = [];
  96066. for (index = 0; index < scene.multiMaterials.length; index++) {
  96067. var multiMaterial = scene.multiMaterials[index];
  96068. serializationObject.multiMaterials.push(multiMaterial.serialize());
  96069. }
  96070. // Environment texture
  96071. if (scene.environmentTexture) {
  96072. serializationObject.environmentTexture = scene.environmentTexture.name;
  96073. }
  96074. // Skeletons
  96075. serializationObject.skeletons = [];
  96076. for (index = 0; index < scene.skeletons.length; index++) {
  96077. var skeleton = scene.skeletons[index];
  96078. if (!skeleton.doNotSerialize) {
  96079. serializationObject.skeletons.push(skeleton.serialize());
  96080. }
  96081. }
  96082. // Transform nodes
  96083. serializationObject.transformNodes = [];
  96084. for (index = 0; index < scene.transformNodes.length; index++) {
  96085. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  96086. }
  96087. // Geometries
  96088. serializationObject.geometries = {};
  96089. serializationObject.geometries.boxes = [];
  96090. serializationObject.geometries.spheres = [];
  96091. serializationObject.geometries.cylinders = [];
  96092. serializationObject.geometries.toruses = [];
  96093. serializationObject.geometries.grounds = [];
  96094. serializationObject.geometries.planes = [];
  96095. serializationObject.geometries.torusKnots = [];
  96096. serializationObject.geometries.vertexData = [];
  96097. serializedGeometries = [];
  96098. var geometries = scene.getGeometries();
  96099. for (index = 0; index < geometries.length; index++) {
  96100. var geometry = geometries[index];
  96101. if (geometry.isReady()) {
  96102. serializeGeometry(geometry, serializationObject.geometries);
  96103. }
  96104. }
  96105. // Meshes
  96106. serializationObject.meshes = [];
  96107. for (index = 0; index < scene.meshes.length; index++) {
  96108. var abstractMesh = scene.meshes[index];
  96109. if (abstractMesh instanceof BABYLON.Mesh) {
  96110. var mesh = abstractMesh;
  96111. if (!mesh.doNotSerialize) {
  96112. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  96113. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  96114. }
  96115. }
  96116. }
  96117. }
  96118. // Particles Systems
  96119. serializationObject.particleSystems = [];
  96120. for (index = 0; index < scene.particleSystems.length; index++) {
  96121. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  96122. }
  96123. // Lens flares
  96124. serializationObject.lensFlareSystems = [];
  96125. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  96126. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  96127. }
  96128. // Shadows
  96129. serializationObject.shadowGenerators = [];
  96130. for (index = 0; index < scene.lights.length; index++) {
  96131. light = scene.lights[index];
  96132. var shadowGenerator = light.getShadowGenerator();
  96133. if (shadowGenerator) {
  96134. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  96135. }
  96136. }
  96137. // Action Manager
  96138. if (scene.actionManager) {
  96139. serializationObject.actions = scene.actionManager.serialize("scene");
  96140. }
  96141. // Audio
  96142. serializationObject.sounds = [];
  96143. for (index = 0; index < scene.soundTracks.length; index++) {
  96144. var soundtrack = scene.soundTracks[index];
  96145. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  96146. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  96147. }
  96148. }
  96149. // Effect layers
  96150. serializationObject.effectLayers = [];
  96151. for (index = 0; index < scene.effectLayers.length; index++) {
  96152. var layer = scene.effectLayers[index];
  96153. if (layer.serialize) {
  96154. serializationObject.effectLayers.push(layer.serialize());
  96155. }
  96156. }
  96157. return serializationObject;
  96158. };
  96159. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  96160. if (withParents === void 0) { withParents = false; }
  96161. if (withChildren === void 0) { withChildren = false; }
  96162. var serializationObject = {};
  96163. SceneSerializer.ClearCache();
  96164. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  96165. if (withParents || withChildren) {
  96166. //deliberate for loop! not for each, appended should be processed as well.
  96167. for (var i = 0; i < toSerialize.length; ++i) {
  96168. if (withChildren) {
  96169. toSerialize[i].getDescendants().forEach(function (node) {
  96170. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  96171. toSerialize.push(node);
  96172. }
  96173. });
  96174. }
  96175. //make sure the array doesn't contain the object already
  96176. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  96177. toSerialize.push(toSerialize[i].parent);
  96178. }
  96179. }
  96180. }
  96181. toSerialize.forEach(function (mesh) {
  96182. finalizeSingleMesh(mesh, serializationObject);
  96183. });
  96184. return serializationObject;
  96185. };
  96186. return SceneSerializer;
  96187. }());
  96188. BABYLON.SceneSerializer = SceneSerializer;
  96189. })(BABYLON || (BABYLON = {}));
  96190. //# sourceMappingURL=babylon.sceneSerializer.js.map
  96191. var BABYLON;
  96192. (function (BABYLON) {
  96193. var ReflectionProbe = /** @class */ (function () {
  96194. function ReflectionProbe(name, size, scene, generateMipMaps) {
  96195. if (generateMipMaps === void 0) { generateMipMaps = true; }
  96196. var _this = this;
  96197. this.name = name;
  96198. this._viewMatrix = BABYLON.Matrix.Identity();
  96199. this._target = BABYLON.Vector3.Zero();
  96200. this._add = BABYLON.Vector3.Zero();
  96201. this._invertYAxis = false;
  96202. this.position = BABYLON.Vector3.Zero();
  96203. this._scene = scene;
  96204. this._scene.reflectionProbes.push(this);
  96205. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  96206. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  96207. switch (faceIndex) {
  96208. case 0:
  96209. _this._add.copyFromFloats(1, 0, 0);
  96210. break;
  96211. case 1:
  96212. _this._add.copyFromFloats(-1, 0, 0);
  96213. break;
  96214. case 2:
  96215. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  96216. break;
  96217. case 3:
  96218. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  96219. break;
  96220. case 4:
  96221. _this._add.copyFromFloats(0, 0, 1);
  96222. break;
  96223. case 5:
  96224. _this._add.copyFromFloats(0, 0, -1);
  96225. break;
  96226. }
  96227. if (_this._attachedMesh) {
  96228. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  96229. }
  96230. _this.position.addToRef(_this._add, _this._target);
  96231. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  96232. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  96233. scene._forcedViewPosition = _this.position;
  96234. });
  96235. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  96236. scene._forcedViewPosition = null;
  96237. scene.updateTransformMatrix(true);
  96238. });
  96239. if (scene.activeCamera) {
  96240. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  96241. }
  96242. }
  96243. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  96244. get: function () {
  96245. return this._renderTargetTexture.samples;
  96246. },
  96247. set: function (value) {
  96248. this._renderTargetTexture.samples = value;
  96249. },
  96250. enumerable: true,
  96251. configurable: true
  96252. });
  96253. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  96254. get: function () {
  96255. return this._renderTargetTexture.refreshRate;
  96256. },
  96257. set: function (value) {
  96258. this._renderTargetTexture.refreshRate = value;
  96259. },
  96260. enumerable: true,
  96261. configurable: true
  96262. });
  96263. ReflectionProbe.prototype.getScene = function () {
  96264. return this._scene;
  96265. };
  96266. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  96267. get: function () {
  96268. return this._renderTargetTexture;
  96269. },
  96270. enumerable: true,
  96271. configurable: true
  96272. });
  96273. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  96274. get: function () {
  96275. return this._renderTargetTexture.renderList;
  96276. },
  96277. enumerable: true,
  96278. configurable: true
  96279. });
  96280. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  96281. this._attachedMesh = mesh;
  96282. };
  96283. /**
  96284. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  96285. *
  96286. * @param renderingGroupId The rendering group id corresponding to its index
  96287. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  96288. */
  96289. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  96290. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  96291. };
  96292. ReflectionProbe.prototype.dispose = function () {
  96293. var index = this._scene.reflectionProbes.indexOf(this);
  96294. if (index !== -1) {
  96295. // Remove from the scene if found
  96296. this._scene.reflectionProbes.splice(index, 1);
  96297. }
  96298. if (this._renderTargetTexture) {
  96299. this._renderTargetTexture.dispose();
  96300. this._renderTargetTexture = null;
  96301. }
  96302. };
  96303. return ReflectionProbe;
  96304. }());
  96305. BABYLON.ReflectionProbe = ReflectionProbe;
  96306. })(BABYLON || (BABYLON = {}));
  96307. //# sourceMappingURL=babylon.reflectionProbe.js.map
  96308. var BABYLON;
  96309. (function (BABYLON) {
  96310. var Layer = /** @class */ (function () {
  96311. function Layer(name, imgUrl, scene, isBackground, color) {
  96312. this.name = name;
  96313. this.scale = new BABYLON.Vector2(1, 1);
  96314. this.offset = new BABYLON.Vector2(0, 0);
  96315. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  96316. this.layerMask = 0x0FFFFFFF;
  96317. this._vertexBuffers = {};
  96318. // Events
  96319. /**
  96320. * An event triggered when the layer is disposed.
  96321. */
  96322. this.onDisposeObservable = new BABYLON.Observable();
  96323. /**
  96324. * An event triggered before rendering the scene
  96325. */
  96326. this.onBeforeRenderObservable = new BABYLON.Observable();
  96327. /**
  96328. * An event triggered after rendering the scene
  96329. */
  96330. this.onAfterRenderObservable = new BABYLON.Observable();
  96331. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  96332. this.isBackground = isBackground === undefined ? true : isBackground;
  96333. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  96334. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  96335. this._scene.layers.push(this);
  96336. var engine = this._scene.getEngine();
  96337. // VBO
  96338. var vertices = [];
  96339. vertices.push(1, 1);
  96340. vertices.push(-1, 1);
  96341. vertices.push(-1, -1);
  96342. vertices.push(1, -1);
  96343. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  96344. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  96345. this._createIndexBuffer();
  96346. // Effects
  96347. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  96348. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  96349. }
  96350. Object.defineProperty(Layer.prototype, "onDispose", {
  96351. set: function (callback) {
  96352. if (this._onDisposeObserver) {
  96353. this.onDisposeObservable.remove(this._onDisposeObserver);
  96354. }
  96355. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  96356. },
  96357. enumerable: true,
  96358. configurable: true
  96359. });
  96360. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  96361. set: function (callback) {
  96362. if (this._onBeforeRenderObserver) {
  96363. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  96364. }
  96365. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  96366. },
  96367. enumerable: true,
  96368. configurable: true
  96369. });
  96370. Object.defineProperty(Layer.prototype, "onAfterRender", {
  96371. set: function (callback) {
  96372. if (this._onAfterRenderObserver) {
  96373. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96374. }
  96375. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  96376. },
  96377. enumerable: true,
  96378. configurable: true
  96379. });
  96380. Layer.prototype._createIndexBuffer = function () {
  96381. var engine = this._scene.getEngine();
  96382. // Indices
  96383. var indices = [];
  96384. indices.push(0);
  96385. indices.push(1);
  96386. indices.push(2);
  96387. indices.push(0);
  96388. indices.push(2);
  96389. indices.push(3);
  96390. this._indexBuffer = engine.createIndexBuffer(indices);
  96391. };
  96392. Layer.prototype._rebuild = function () {
  96393. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96394. if (vb) {
  96395. vb._rebuild();
  96396. }
  96397. this._createIndexBuffer();
  96398. };
  96399. Layer.prototype.render = function () {
  96400. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  96401. // Check
  96402. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  96403. return;
  96404. var engine = this._scene.getEngine();
  96405. this.onBeforeRenderObservable.notifyObservers(this);
  96406. // Render
  96407. engine.enableEffect(currentEffect);
  96408. engine.setState(false);
  96409. // Texture
  96410. currentEffect.setTexture("textureSampler", this.texture);
  96411. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  96412. // Color
  96413. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  96414. // Scale / offset
  96415. currentEffect.setVector2("offset", this.offset);
  96416. currentEffect.setVector2("scale", this.scale);
  96417. // VBOs
  96418. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  96419. // Draw order
  96420. if (!this.alphaTest) {
  96421. engine.setAlphaMode(this.alphaBlendingMode);
  96422. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96423. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  96424. }
  96425. else {
  96426. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96427. }
  96428. this.onAfterRenderObservable.notifyObservers(this);
  96429. };
  96430. Layer.prototype.dispose = function () {
  96431. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96432. if (vertexBuffer) {
  96433. vertexBuffer.dispose();
  96434. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  96435. }
  96436. if (this._indexBuffer) {
  96437. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  96438. this._indexBuffer = null;
  96439. }
  96440. if (this.texture) {
  96441. this.texture.dispose();
  96442. this.texture = null;
  96443. }
  96444. // Remove from scene
  96445. var index = this._scene.layers.indexOf(this);
  96446. this._scene.layers.splice(index, 1);
  96447. // Callback
  96448. this.onDisposeObservable.notifyObservers(this);
  96449. this.onDisposeObservable.clear();
  96450. this.onAfterRenderObservable.clear();
  96451. this.onBeforeRenderObservable.clear();
  96452. };
  96453. return Layer;
  96454. }());
  96455. BABYLON.Layer = Layer;
  96456. })(BABYLON || (BABYLON = {}));
  96457. //# sourceMappingURL=babylon.layer.js.map
  96458. var BABYLON;
  96459. (function (BABYLON) {
  96460. var TextureTools = /** @class */ (function () {
  96461. function TextureTools() {
  96462. }
  96463. /**
  96464. * Uses the GPU to create a copy texture rescaled at a given size
  96465. * @param texture Texture to copy from
  96466. * @param width Desired width
  96467. * @param height Desired height
  96468. * @return Generated texture
  96469. */
  96470. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  96471. if (useBilinearMode === void 0) { useBilinearMode = true; }
  96472. var scene = texture.getScene();
  96473. var engine = scene.getEngine();
  96474. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  96475. rtt.wrapU = texture.wrapU;
  96476. rtt.wrapV = texture.wrapV;
  96477. rtt.uOffset = texture.uOffset;
  96478. rtt.vOffset = texture.vOffset;
  96479. rtt.uScale = texture.uScale;
  96480. rtt.vScale = texture.vScale;
  96481. rtt.uAng = texture.uAng;
  96482. rtt.vAng = texture.vAng;
  96483. rtt.wAng = texture.wAng;
  96484. rtt.coordinatesIndex = texture.coordinatesIndex;
  96485. rtt.level = texture.level;
  96486. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  96487. rtt._texture.isReady = false;
  96488. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96489. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96490. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  96491. passPostProcess.getEffect().executeWhenCompiled(function () {
  96492. passPostProcess.onApply = function (effect) {
  96493. effect.setTexture("textureSampler", texture);
  96494. };
  96495. var internalTexture = rtt.getInternalTexture();
  96496. if (internalTexture) {
  96497. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  96498. engine.unBindFramebuffer(internalTexture);
  96499. rtt.disposeFramebufferObjects();
  96500. passPostProcess.dispose();
  96501. internalTexture.isReady = true;
  96502. }
  96503. });
  96504. return rtt;
  96505. };
  96506. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  96507. if (!scene._environmentBRDFTexture) {
  96508. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96509. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96510. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96511. scene._environmentBRDFTexture = texture;
  96512. }
  96513. return scene._environmentBRDFTexture;
  96514. };
  96515. TextureTools._environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/eud9fvn27rf9evPPwFz+v22S7fGZ/n7/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wLZtS4Df7Kst+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=";
  96516. return TextureTools;
  96517. }());
  96518. BABYLON.TextureTools = TextureTools;
  96519. })(BABYLON || (BABYLON = {}));
  96520. //# sourceMappingURL=babylon.textureTools.js.map
  96521. var BABYLON;
  96522. (function (BABYLON) {
  96523. var FramingBehavior = /** @class */ (function () {
  96524. function FramingBehavior() {
  96525. this._mode = FramingBehavior.FitFrustumSidesMode;
  96526. this._radiusScale = 1.0;
  96527. this._positionScale = 0.5;
  96528. this._defaultElevation = 0.3;
  96529. this._elevationReturnTime = 1500;
  96530. this._elevationReturnWaitTime = 1000;
  96531. this._zoomStopsAnimation = false;
  96532. this._framingTime = 1500;
  96533. this._isPointerDown = false;
  96534. this._lastInteractionTime = -Infinity;
  96535. // Framing control
  96536. this._animatables = new Array();
  96537. this._betaIsAnimating = false;
  96538. }
  96539. Object.defineProperty(FramingBehavior.prototype, "name", {
  96540. get: function () {
  96541. return "Framing";
  96542. },
  96543. enumerable: true,
  96544. configurable: true
  96545. });
  96546. Object.defineProperty(FramingBehavior.prototype, "mode", {
  96547. /**
  96548. * Gets current mode used by the behavior.
  96549. */
  96550. get: function () {
  96551. return this._mode;
  96552. },
  96553. /**
  96554. * Sets the current mode used by the behavior
  96555. */
  96556. set: function (mode) {
  96557. this._mode = mode;
  96558. },
  96559. enumerable: true,
  96560. configurable: true
  96561. });
  96562. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  96563. /**
  96564. * Gets the scale applied to the radius
  96565. */
  96566. get: function () {
  96567. return this._radiusScale;
  96568. },
  96569. /**
  96570. * Sets the scale applied to the radius (1 by default)
  96571. */
  96572. set: function (radius) {
  96573. this._radiusScale = radius;
  96574. },
  96575. enumerable: true,
  96576. configurable: true
  96577. });
  96578. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  96579. /**
  96580. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  96581. */
  96582. get: function () {
  96583. return this._positionScale;
  96584. },
  96585. /**
  96586. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  96587. */
  96588. set: function (scale) {
  96589. this._positionScale = scale;
  96590. },
  96591. enumerable: true,
  96592. configurable: true
  96593. });
  96594. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  96595. /**
  96596. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  96597. * behaviour is triggered, in radians.
  96598. */
  96599. get: function () {
  96600. return this._defaultElevation;
  96601. },
  96602. /**
  96603. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  96604. * behaviour is triggered, in radians.
  96605. */
  96606. set: function (elevation) {
  96607. this._defaultElevation = elevation;
  96608. },
  96609. enumerable: true,
  96610. configurable: true
  96611. });
  96612. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  96613. /**
  96614. * Gets the time (in milliseconds) taken to return to the default beta position.
  96615. * Negative value indicates camera should not return to default.
  96616. */
  96617. get: function () {
  96618. return this._elevationReturnTime;
  96619. },
  96620. /**
  96621. * Sets the time (in milliseconds) taken to return to the default beta position.
  96622. * Negative value indicates camera should not return to default.
  96623. */
  96624. set: function (speed) {
  96625. this._elevationReturnTime = speed;
  96626. },
  96627. enumerable: true,
  96628. configurable: true
  96629. });
  96630. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  96631. /**
  96632. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  96633. */
  96634. get: function () {
  96635. return this._elevationReturnWaitTime;
  96636. },
  96637. /**
  96638. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  96639. */
  96640. set: function (time) {
  96641. this._elevationReturnWaitTime = time;
  96642. },
  96643. enumerable: true,
  96644. configurable: true
  96645. });
  96646. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  96647. /**
  96648. * Gets the flag that indicates if user zooming should stop animation.
  96649. */
  96650. get: function () {
  96651. return this._zoomStopsAnimation;
  96652. },
  96653. /**
  96654. * Sets the flag that indicates if user zooming should stop animation.
  96655. */
  96656. set: function (flag) {
  96657. this._zoomStopsAnimation = flag;
  96658. },
  96659. enumerable: true,
  96660. configurable: true
  96661. });
  96662. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  96663. /**
  96664. * Gets the transition time when framing the mesh, in milliseconds
  96665. */
  96666. get: function () {
  96667. return this._framingTime;
  96668. },
  96669. /**
  96670. * Sets the transition time when framing the mesh, in milliseconds
  96671. */
  96672. set: function (time) {
  96673. this._framingTime = time;
  96674. },
  96675. enumerable: true,
  96676. configurable: true
  96677. });
  96678. FramingBehavior.prototype.init = function () {
  96679. // Do notihng
  96680. };
  96681. FramingBehavior.prototype.attach = function (camera) {
  96682. var _this = this;
  96683. this._attachedCamera = camera;
  96684. var scene = this._attachedCamera.getScene();
  96685. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  96686. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  96687. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  96688. _this._isPointerDown = true;
  96689. return;
  96690. }
  96691. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  96692. _this._isPointerDown = false;
  96693. }
  96694. });
  96695. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  96696. if (mesh) {
  96697. _this.zoomOnMesh(mesh);
  96698. }
  96699. });
  96700. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  96701. // Stop the animation if there is user interaction and the animation should stop for this interaction
  96702. _this._applyUserInteraction();
  96703. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  96704. // back to the default position after a given timeout
  96705. _this._maintainCameraAboveGround();
  96706. });
  96707. };
  96708. FramingBehavior.prototype.detach = function () {
  96709. if (!this._attachedCamera) {
  96710. return;
  96711. }
  96712. var scene = this._attachedCamera.getScene();
  96713. if (this._onPrePointerObservableObserver) {
  96714. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  96715. }
  96716. if (this._onAfterCheckInputsObserver) {
  96717. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  96718. }
  96719. if (this._onMeshTargetChangedObserver) {
  96720. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  96721. }
  96722. this._attachedCamera = null;
  96723. };
  96724. /**
  96725. * Targets the given mesh and updates zoom level accordingly.
  96726. * @param mesh The mesh to target.
  96727. * @param radius Optional. If a cached radius position already exists, overrides default.
  96728. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96729. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96730. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96731. */
  96732. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  96733. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96734. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96735. mesh.computeWorldMatrix(true);
  96736. var boundingBox = mesh.getBoundingInfo().boundingBox;
  96737. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  96738. };
  96739. /**
  96740. * Targets the given mesh with its children and updates zoom level accordingly.
  96741. * @param mesh The mesh to target.
  96742. * @param radius Optional. If a cached radius position already exists, overrides default.
  96743. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96744. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96745. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96746. */
  96747. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  96748. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96749. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96750. mesh.computeWorldMatrix(true);
  96751. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  96752. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  96753. };
  96754. /**
  96755. * Targets the given meshes with their children and updates zoom level accordingly.
  96756. * @param meshes The mesh to target.
  96757. * @param radius Optional. If a cached radius position already exists, overrides default.
  96758. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96759. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96760. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96761. */
  96762. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  96763. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96764. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96765. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  96766. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  96767. for (var i = 0; i < meshes.length; i++) {
  96768. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  96769. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  96770. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  96771. }
  96772. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  96773. };
  96774. /**
  96775. * Targets the given mesh and updates zoom level accordingly.
  96776. * @param mesh The mesh to target.
  96777. * @param radius Optional. If a cached radius position already exists, overrides default.
  96778. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96779. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96780. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96781. */
  96782. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  96783. var _this = this;
  96784. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96785. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96786. var zoomTarget;
  96787. if (!this._attachedCamera) {
  96788. return;
  96789. }
  96790. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  96791. var bottom = minimumWorld.y;
  96792. var top = maximumWorld.y;
  96793. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  96794. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  96795. if (focusOnOriginXZ) {
  96796. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  96797. }
  96798. else {
  96799. var centerWorld = minimumWorld.add(radiusWorld);
  96800. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  96801. }
  96802. if (!this._vectorTransition) {
  96803. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  96804. }
  96805. this._betaIsAnimating = true;
  96806. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  96807. if (animatable) {
  96808. this._animatables.push(animatable);
  96809. }
  96810. // sets the radius and lower radius bounds
  96811. // Small delta ensures camera is not always at lower zoom limit.
  96812. var radius = 0;
  96813. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  96814. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  96815. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  96816. radius = position;
  96817. }
  96818. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  96819. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  96820. if (this._attachedCamera.lowerRadiusLimit === null) {
  96821. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  96822. }
  96823. }
  96824. // Set sensibilities
  96825. var extend = maximumWorld.subtract(minimumWorld).length();
  96826. this._attachedCamera.panningSensibility = 5000 / extend;
  96827. this._attachedCamera.wheelPrecision = 100 / radius;
  96828. // transition to new radius
  96829. if (!this._radiusTransition) {
  96830. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  96831. }
  96832. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  96833. _this.stopAllAnimations();
  96834. if (onAnimationEnd) {
  96835. onAnimationEnd();
  96836. }
  96837. if (_this._attachedCamera) {
  96838. _this._attachedCamera.storeState();
  96839. }
  96840. });
  96841. if (animatable) {
  96842. this._animatables.push(animatable);
  96843. }
  96844. };
  96845. /**
  96846. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  96847. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  96848. * frustum width.
  96849. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  96850. * to fully enclose the mesh in the viewing frustum.
  96851. */
  96852. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  96853. var size = maximumWorld.subtract(minimumWorld);
  96854. var boxVectorGlobalDiagonal = size.length();
  96855. var frustumSlope = this._getFrustumSlope();
  96856. // Formula for setting distance
  96857. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  96858. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  96859. // Horizon distance
  96860. var radius = radiusWithoutFraming * this._radiusScale;
  96861. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  96862. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  96863. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  96864. var camera = this._attachedCamera;
  96865. if (!camera) {
  96866. return 0;
  96867. }
  96868. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  96869. // Don't exceed the requested limit
  96870. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  96871. }
  96872. // Don't exceed the upper radius limit
  96873. if (camera.upperRadiusLimit) {
  96874. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  96875. }
  96876. return distance;
  96877. };
  96878. /**
  96879. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  96880. * is automatically returned to its default position (expected to be above ground plane).
  96881. */
  96882. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  96883. var _this = this;
  96884. if (this._elevationReturnTime < 0) {
  96885. return;
  96886. }
  96887. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  96888. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  96889. var limitBeta = Math.PI * 0.5;
  96890. // Bring the camera back up if below the ground plane
  96891. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  96892. this._betaIsAnimating = true;
  96893. //Transition to new position
  96894. this.stopAllAnimations();
  96895. if (!this._betaTransition) {
  96896. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  96897. }
  96898. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  96899. _this._clearAnimationLocks();
  96900. _this.stopAllAnimations();
  96901. });
  96902. if (animatabe) {
  96903. this._animatables.push(animatabe);
  96904. }
  96905. }
  96906. };
  96907. /**
  96908. * Returns the frustum slope based on the canvas ratio and camera FOV
  96909. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  96910. */
  96911. FramingBehavior.prototype._getFrustumSlope = function () {
  96912. // Calculate the viewport ratio
  96913. // Aspect Ratio is Height/Width.
  96914. var camera = this._attachedCamera;
  96915. if (!camera) {
  96916. return BABYLON.Vector2.Zero();
  96917. }
  96918. var engine = camera.getScene().getEngine();
  96919. var aspectRatio = engine.getAspectRatio(camera);
  96920. // Camera FOV is the vertical field of view (top-bottom) in radians.
  96921. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  96922. var frustumSlopeY = Math.tan(camera.fov / 2);
  96923. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  96924. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  96925. // along the forward vector.
  96926. var frustumSlopeX = frustumSlopeY * aspectRatio;
  96927. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  96928. };
  96929. /**
  96930. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  96931. */
  96932. FramingBehavior.prototype._clearAnimationLocks = function () {
  96933. this._betaIsAnimating = false;
  96934. };
  96935. /**
  96936. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  96937. */
  96938. FramingBehavior.prototype._applyUserInteraction = function () {
  96939. if (this.isUserIsMoving) {
  96940. this._lastInteractionTime = BABYLON.Tools.Now;
  96941. this.stopAllAnimations();
  96942. this._clearAnimationLocks();
  96943. }
  96944. };
  96945. /**
  96946. * Stops and removes all animations that have been applied to the camera
  96947. */
  96948. FramingBehavior.prototype.stopAllAnimations = function () {
  96949. if (this._attachedCamera) {
  96950. this._attachedCamera.animations = [];
  96951. }
  96952. while (this._animatables.length) {
  96953. if (this._animatables[0]) {
  96954. this._animatables[0].onAnimationEnd = null;
  96955. this._animatables[0].stop();
  96956. }
  96957. this._animatables.shift();
  96958. }
  96959. };
  96960. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  96961. /**
  96962. * Gets a value indicating if the user is moving the camera
  96963. */
  96964. get: function () {
  96965. if (!this._attachedCamera) {
  96966. return false;
  96967. }
  96968. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  96969. this._attachedCamera.inertialBetaOffset !== 0 ||
  96970. this._attachedCamera.inertialRadiusOffset !== 0 ||
  96971. this._attachedCamera.inertialPanningX !== 0 ||
  96972. this._attachedCamera.inertialPanningY !== 0 ||
  96973. this._isPointerDown;
  96974. },
  96975. enumerable: true,
  96976. configurable: true
  96977. });
  96978. /**
  96979. * The easing function used by animations
  96980. */
  96981. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  96982. /**
  96983. * The easing mode used by animations
  96984. */
  96985. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  96986. // Statics
  96987. /**
  96988. * The camera can move all the way towards the mesh.
  96989. */
  96990. FramingBehavior.IgnoreBoundsSizeMode = 0;
  96991. /**
  96992. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  96993. */
  96994. FramingBehavior.FitFrustumSidesMode = 1;
  96995. return FramingBehavior;
  96996. }());
  96997. BABYLON.FramingBehavior = FramingBehavior;
  96998. })(BABYLON || (BABYLON = {}));
  96999. //# sourceMappingURL=babylon.framingBehavior.js.map
  97000. var BABYLON;
  97001. (function (BABYLON) {
  97002. /**
  97003. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  97004. */
  97005. var BouncingBehavior = /** @class */ (function () {
  97006. function BouncingBehavior() {
  97007. /**
  97008. * The duration of the animation, in milliseconds
  97009. */
  97010. this.transitionDuration = 450;
  97011. /**
  97012. * Length of the distance animated by the transition when lower radius is reached
  97013. */
  97014. this.lowerRadiusTransitionRange = 2;
  97015. /**
  97016. * Length of the distance animated by the transition when upper radius is reached
  97017. */
  97018. this.upperRadiusTransitionRange = -2;
  97019. this._autoTransitionRange = false;
  97020. // Animations
  97021. this._radiusIsAnimating = false;
  97022. this._radiusBounceTransition = null;
  97023. this._animatables = new Array();
  97024. }
  97025. Object.defineProperty(BouncingBehavior.prototype, "name", {
  97026. get: function () {
  97027. return "Bouncing";
  97028. },
  97029. enumerable: true,
  97030. configurable: true
  97031. });
  97032. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  97033. /**
  97034. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  97035. */
  97036. get: function () {
  97037. return this._autoTransitionRange;
  97038. },
  97039. /**
  97040. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  97041. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  97042. */
  97043. set: function (value) {
  97044. var _this = this;
  97045. if (this._autoTransitionRange === value) {
  97046. return;
  97047. }
  97048. this._autoTransitionRange = value;
  97049. var camera = this._attachedCamera;
  97050. if (!camera) {
  97051. return;
  97052. }
  97053. if (value) {
  97054. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  97055. if (!mesh) {
  97056. return;
  97057. }
  97058. mesh.computeWorldMatrix(true);
  97059. var diagonal = mesh.getBoundingInfo().diagonalLength;
  97060. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  97061. _this.upperRadiusTransitionRange = diagonal * 0.05;
  97062. });
  97063. }
  97064. else if (this._onMeshTargetChangedObserver) {
  97065. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  97066. }
  97067. },
  97068. enumerable: true,
  97069. configurable: true
  97070. });
  97071. BouncingBehavior.prototype.init = function () {
  97072. // Do notihng
  97073. };
  97074. BouncingBehavior.prototype.attach = function (camera) {
  97075. var _this = this;
  97076. this._attachedCamera = camera;
  97077. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  97078. if (!_this._attachedCamera) {
  97079. return;
  97080. }
  97081. // Add the bounce animation to the lower radius limit
  97082. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  97083. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  97084. }
  97085. // Add the bounce animation to the upper radius limit
  97086. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  97087. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  97088. }
  97089. });
  97090. };
  97091. BouncingBehavior.prototype.detach = function () {
  97092. if (!this._attachedCamera) {
  97093. return;
  97094. }
  97095. if (this._onAfterCheckInputsObserver) {
  97096. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  97097. }
  97098. if (this._onMeshTargetChangedObserver) {
  97099. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  97100. }
  97101. this._attachedCamera = null;
  97102. };
  97103. /**
  97104. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  97105. * @param radiusLimit The limit to check against.
  97106. * @return Bool to indicate if at limit.
  97107. */
  97108. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  97109. if (!this._attachedCamera) {
  97110. return false;
  97111. }
  97112. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  97113. return true;
  97114. }
  97115. return false;
  97116. };
  97117. /**
  97118. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  97119. * @param radiusDelta The delta by which to animate to. Can be negative.
  97120. */
  97121. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  97122. var _this = this;
  97123. if (!this._attachedCamera) {
  97124. return;
  97125. }
  97126. if (!this._radiusBounceTransition) {
  97127. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  97128. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  97129. }
  97130. // Prevent zoom until bounce has completed
  97131. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  97132. this._attachedCamera.wheelPrecision = Infinity;
  97133. this._attachedCamera.inertialRadiusOffset = 0;
  97134. // Animate to the radius limit
  97135. this.stopAllAnimations();
  97136. this._radiusIsAnimating = true;
  97137. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  97138. if (animatable) {
  97139. this._animatables.push(animatable);
  97140. }
  97141. };
  97142. /**
  97143. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  97144. */
  97145. BouncingBehavior.prototype._clearAnimationLocks = function () {
  97146. this._radiusIsAnimating = false;
  97147. if (this._attachedCamera) {
  97148. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  97149. }
  97150. };
  97151. /**
  97152. * Stops and removes all animations that have been applied to the camera
  97153. */
  97154. BouncingBehavior.prototype.stopAllAnimations = function () {
  97155. if (this._attachedCamera) {
  97156. this._attachedCamera.animations = [];
  97157. }
  97158. while (this._animatables.length) {
  97159. this._animatables[0].onAnimationEnd = null;
  97160. this._animatables[0].stop();
  97161. this._animatables.shift();
  97162. }
  97163. };
  97164. /**
  97165. * The easing function used by animations
  97166. */
  97167. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  97168. /**
  97169. * The easing mode used by animations
  97170. */
  97171. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  97172. return BouncingBehavior;
  97173. }());
  97174. BABYLON.BouncingBehavior = BouncingBehavior;
  97175. })(BABYLON || (BABYLON = {}));
  97176. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  97177. var BABYLON;
  97178. (function (BABYLON) {
  97179. var AutoRotationBehavior = /** @class */ (function () {
  97180. function AutoRotationBehavior() {
  97181. this._zoomStopsAnimation = false;
  97182. this._idleRotationSpeed = 0.05;
  97183. this._idleRotationWaitTime = 2000;
  97184. this._idleRotationSpinupTime = 2000;
  97185. this._isPointerDown = false;
  97186. this._lastFrameTime = null;
  97187. this._lastInteractionTime = -Infinity;
  97188. this._cameraRotationSpeed = 0;
  97189. this._lastFrameRadius = 0;
  97190. }
  97191. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  97192. get: function () {
  97193. return "AutoRotation";
  97194. },
  97195. enumerable: true,
  97196. configurable: true
  97197. });
  97198. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  97199. /**
  97200. * Gets the flag that indicates if user zooming should stop animation.
  97201. */
  97202. get: function () {
  97203. return this._zoomStopsAnimation;
  97204. },
  97205. /**
  97206. * Sets the flag that indicates if user zooming should stop animation.
  97207. */
  97208. set: function (flag) {
  97209. this._zoomStopsAnimation = flag;
  97210. },
  97211. enumerable: true,
  97212. configurable: true
  97213. });
  97214. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  97215. /**
  97216. * Gets the default speed at which the camera rotates around the model.
  97217. */
  97218. get: function () {
  97219. return this._idleRotationSpeed;
  97220. },
  97221. /**
  97222. * Sets the default speed at which the camera rotates around the model.
  97223. */
  97224. set: function (speed) {
  97225. this._idleRotationSpeed = speed;
  97226. },
  97227. enumerable: true,
  97228. configurable: true
  97229. });
  97230. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  97231. /**
  97232. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  97233. */
  97234. get: function () {
  97235. return this._idleRotationWaitTime;
  97236. },
  97237. /**
  97238. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  97239. */
  97240. set: function (time) {
  97241. this._idleRotationWaitTime = time;
  97242. },
  97243. enumerable: true,
  97244. configurable: true
  97245. });
  97246. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  97247. /**
  97248. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  97249. */
  97250. get: function () {
  97251. return this._idleRotationSpinupTime;
  97252. },
  97253. /**
  97254. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  97255. */
  97256. set: function (time) {
  97257. this._idleRotationSpinupTime = time;
  97258. },
  97259. enumerable: true,
  97260. configurable: true
  97261. });
  97262. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  97263. /**
  97264. * Gets a value indicating if the camera is currently rotating because of this behavior
  97265. */
  97266. get: function () {
  97267. return Math.abs(this._cameraRotationSpeed) > 0;
  97268. },
  97269. enumerable: true,
  97270. configurable: true
  97271. });
  97272. AutoRotationBehavior.prototype.init = function () {
  97273. // Do notihng
  97274. };
  97275. AutoRotationBehavior.prototype.attach = function (camera) {
  97276. var _this = this;
  97277. this._attachedCamera = camera;
  97278. var scene = this._attachedCamera.getScene();
  97279. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  97280. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  97281. _this._isPointerDown = true;
  97282. return;
  97283. }
  97284. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  97285. _this._isPointerDown = false;
  97286. }
  97287. });
  97288. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  97289. var now = BABYLON.Tools.Now;
  97290. var dt = 0;
  97291. if (_this._lastFrameTime != null) {
  97292. dt = now - _this._lastFrameTime;
  97293. }
  97294. _this._lastFrameTime = now;
  97295. // Stop the animation if there is user interaction and the animation should stop for this interaction
  97296. _this._applyUserInteraction();
  97297. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  97298. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  97299. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  97300. // Step camera rotation by rotation speed
  97301. if (_this._attachedCamera) {
  97302. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  97303. }
  97304. });
  97305. };
  97306. AutoRotationBehavior.prototype.detach = function () {
  97307. if (!this._attachedCamera) {
  97308. return;
  97309. }
  97310. var scene = this._attachedCamera.getScene();
  97311. if (this._onPrePointerObservableObserver) {
  97312. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  97313. }
  97314. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  97315. this._attachedCamera = null;
  97316. };
  97317. /**
  97318. * Returns true if user is scrolling.
  97319. * @return true if user is scrolling.
  97320. */
  97321. AutoRotationBehavior.prototype._userIsZooming = function () {
  97322. if (!this._attachedCamera) {
  97323. return false;
  97324. }
  97325. return this._attachedCamera.inertialRadiusOffset !== 0;
  97326. };
  97327. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  97328. if (!this._attachedCamera) {
  97329. return false;
  97330. }
  97331. var zoomHasHitLimit = false;
  97332. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  97333. zoomHasHitLimit = true;
  97334. }
  97335. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  97336. this._lastFrameRadius = this._attachedCamera.radius;
  97337. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  97338. };
  97339. /**
  97340. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  97341. */
  97342. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  97343. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  97344. this._lastInteractionTime = BABYLON.Tools.Now;
  97345. }
  97346. };
  97347. // Tools
  97348. AutoRotationBehavior.prototype._userIsMoving = function () {
  97349. if (!this._attachedCamera) {
  97350. return false;
  97351. }
  97352. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  97353. this._attachedCamera.inertialBetaOffset !== 0 ||
  97354. this._attachedCamera.inertialRadiusOffset !== 0 ||
  97355. this._attachedCamera.inertialPanningX !== 0 ||
  97356. this._attachedCamera.inertialPanningY !== 0 ||
  97357. this._isPointerDown;
  97358. };
  97359. return AutoRotationBehavior;
  97360. }());
  97361. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  97362. })(BABYLON || (BABYLON = {}));
  97363. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  97364. var BABYLON;
  97365. (function (BABYLON) {
  97366. var NullEngineOptions = /** @class */ (function () {
  97367. function NullEngineOptions() {
  97368. this.renderWidth = 512;
  97369. this.renderHeight = 256;
  97370. this.textureSize = 512;
  97371. this.deterministicLockstep = false;
  97372. this.lockstepMaxSteps = 4;
  97373. }
  97374. return NullEngineOptions;
  97375. }());
  97376. BABYLON.NullEngineOptions = NullEngineOptions;
  97377. /**
  97378. * The null engine class provides support for headless version of babylon.js.
  97379. * This can be used in server side scenario or for testing purposes
  97380. */
  97381. var NullEngine = /** @class */ (function (_super) {
  97382. __extends(NullEngine, _super);
  97383. function NullEngine(options) {
  97384. if (options === void 0) { options = new NullEngineOptions(); }
  97385. var _this = _super.call(this, null) || this;
  97386. if (options.deterministicLockstep === undefined) {
  97387. options.deterministicLockstep = false;
  97388. }
  97389. if (options.lockstepMaxSteps === undefined) {
  97390. options.lockstepMaxSteps = 4;
  97391. }
  97392. _this._options = options;
  97393. // Init caps
  97394. // We consider we are on a webgl1 capable device
  97395. _this._caps = new BABYLON.EngineCapabilities();
  97396. _this._caps.maxTexturesImageUnits = 16;
  97397. _this._caps.maxVertexTextureImageUnits = 16;
  97398. _this._caps.maxTextureSize = 512;
  97399. _this._caps.maxCubemapTextureSize = 512;
  97400. _this._caps.maxRenderTextureSize = 512;
  97401. _this._caps.maxVertexAttribs = 16;
  97402. _this._caps.maxVaryingVectors = 16;
  97403. _this._caps.maxFragmentUniformVectors = 16;
  97404. _this._caps.maxVertexUniformVectors = 16;
  97405. // Extensions
  97406. _this._caps.standardDerivatives = false;
  97407. _this._caps.astc = null;
  97408. _this._caps.s3tc = null;
  97409. _this._caps.pvrtc = null;
  97410. _this._caps.etc1 = null;
  97411. _this._caps.etc2 = null;
  97412. _this._caps.textureAnisotropicFilterExtension = null;
  97413. _this._caps.maxAnisotropy = 0;
  97414. _this._caps.uintIndices = false;
  97415. _this._caps.fragmentDepthSupported = false;
  97416. _this._caps.highPrecisionShaderSupported = true;
  97417. _this._caps.colorBufferFloat = false;
  97418. _this._caps.textureFloat = false;
  97419. _this._caps.textureFloatLinearFiltering = false;
  97420. _this._caps.textureFloatRender = false;
  97421. _this._caps.textureHalfFloat = false;
  97422. _this._caps.textureHalfFloatLinearFiltering = false;
  97423. _this._caps.textureHalfFloatRender = false;
  97424. _this._caps.textureLOD = false;
  97425. _this._caps.drawBuffersExtension = false;
  97426. _this._caps.depthTextureExtension = false;
  97427. _this._caps.vertexArrayObject = false;
  97428. _this._caps.instancedArrays = false;
  97429. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  97430. // Wrappers
  97431. if (typeof URL === "undefined") {
  97432. URL = {
  97433. createObjectURL: function () { },
  97434. revokeObjectURL: function () { }
  97435. };
  97436. }
  97437. if (typeof Blob === "undefined") {
  97438. Blob = function () { };
  97439. }
  97440. return _this;
  97441. }
  97442. NullEngine.prototype.isDeterministicLockStep = function () {
  97443. return this._options.deterministicLockstep;
  97444. };
  97445. NullEngine.prototype.getLockstepMaxSteps = function () {
  97446. return this._options.lockstepMaxSteps;
  97447. };
  97448. NullEngine.prototype.getHardwareScalingLevel = function () {
  97449. return 1.0;
  97450. };
  97451. NullEngine.prototype.createVertexBuffer = function (vertices) {
  97452. return {
  97453. capacity: 0,
  97454. references: 1,
  97455. is32Bits: false
  97456. };
  97457. };
  97458. NullEngine.prototype.createIndexBuffer = function (indices) {
  97459. return {
  97460. capacity: 0,
  97461. references: 1,
  97462. is32Bits: false
  97463. };
  97464. };
  97465. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  97466. if (stencil === void 0) { stencil = false; }
  97467. };
  97468. NullEngine.prototype.getRenderWidth = function (useScreen) {
  97469. if (useScreen === void 0) { useScreen = false; }
  97470. if (!useScreen && this._currentRenderTarget) {
  97471. return this._currentRenderTarget.width;
  97472. }
  97473. return this._options.renderWidth;
  97474. };
  97475. NullEngine.prototype.getRenderHeight = function (useScreen) {
  97476. if (useScreen === void 0) { useScreen = false; }
  97477. if (!useScreen && this._currentRenderTarget) {
  97478. return this._currentRenderTarget.height;
  97479. }
  97480. return this._options.renderHeight;
  97481. };
  97482. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  97483. this._cachedViewport = viewport;
  97484. };
  97485. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  97486. return {
  97487. transformFeedback: null,
  97488. __SPECTOR_rebuildProgram: null
  97489. };
  97490. };
  97491. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  97492. return [];
  97493. };
  97494. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  97495. return [];
  97496. };
  97497. NullEngine.prototype.bindSamplers = function (effect) {
  97498. this._currentEffect = null;
  97499. };
  97500. NullEngine.prototype.enableEffect = function (effect) {
  97501. this._currentEffect = effect;
  97502. if (effect.onBind) {
  97503. effect.onBind(effect);
  97504. }
  97505. effect.onBindObservable.notifyObservers(effect);
  97506. };
  97507. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  97508. if (zOffset === void 0) { zOffset = 0; }
  97509. if (reverseSide === void 0) { reverseSide = false; }
  97510. };
  97511. NullEngine.prototype.setIntArray = function (uniform, array) {
  97512. };
  97513. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  97514. };
  97515. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  97516. };
  97517. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  97518. };
  97519. NullEngine.prototype.setFloatArray = function (uniform, array) {
  97520. };
  97521. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  97522. };
  97523. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  97524. };
  97525. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  97526. };
  97527. NullEngine.prototype.setArray = function (uniform, array) {
  97528. };
  97529. NullEngine.prototype.setArray2 = function (uniform, array) {
  97530. };
  97531. NullEngine.prototype.setArray3 = function (uniform, array) {
  97532. };
  97533. NullEngine.prototype.setArray4 = function (uniform, array) {
  97534. };
  97535. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  97536. };
  97537. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  97538. };
  97539. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  97540. };
  97541. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  97542. };
  97543. NullEngine.prototype.setFloat = function (uniform, value) {
  97544. };
  97545. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  97546. };
  97547. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  97548. };
  97549. NullEngine.prototype.setBool = function (uniform, bool) {
  97550. };
  97551. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  97552. };
  97553. NullEngine.prototype.setColor3 = function (uniform, color3) {
  97554. };
  97555. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  97556. };
  97557. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  97558. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  97559. if (this._alphaMode === mode) {
  97560. return;
  97561. }
  97562. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  97563. if (!noDepthWriteChange) {
  97564. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  97565. }
  97566. this._alphaMode = mode;
  97567. };
  97568. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  97569. };
  97570. NullEngine.prototype.wipeCaches = function (bruteForce) {
  97571. if (this.preventCacheWipeBetweenFrames) {
  97572. return;
  97573. }
  97574. this.resetTextureCache();
  97575. this._currentEffect = null;
  97576. if (bruteForce) {
  97577. this._currentProgram = null;
  97578. this._stencilState.reset();
  97579. this._depthCullingState.reset();
  97580. this._alphaState.reset();
  97581. }
  97582. this._cachedVertexBuffers = null;
  97583. this._cachedIndexBuffer = null;
  97584. this._cachedEffectForVertexBuffers = null;
  97585. };
  97586. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  97587. };
  97588. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  97589. };
  97590. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  97591. };
  97592. NullEngine.prototype._createTexture = function () {
  97593. return {};
  97594. };
  97595. NullEngine.prototype._releaseTexture = function (texture) {
  97596. };
  97597. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  97598. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  97599. if (onLoad === void 0) { onLoad = null; }
  97600. if (onError === void 0) { onError = null; }
  97601. if (buffer === void 0) { buffer = null; }
  97602. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  97603. var url = String(urlArg);
  97604. texture.url = url;
  97605. texture.generateMipMaps = !noMipmap;
  97606. texture.samplingMode = samplingMode;
  97607. texture.invertY = invertY;
  97608. texture.baseWidth = this._options.textureSize;
  97609. texture.baseHeight = this._options.textureSize;
  97610. texture.width = this._options.textureSize;
  97611. texture.height = this._options.textureSize;
  97612. if (format) {
  97613. texture.format = format;
  97614. }
  97615. texture.isReady = true;
  97616. if (onLoad) {
  97617. onLoad();
  97618. }
  97619. this._internalTexturesCache.push(texture);
  97620. return texture;
  97621. };
  97622. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  97623. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  97624. if (options !== undefined && typeof options === "object") {
  97625. fullOptions.generateMipMaps = options.generateMipMaps;
  97626. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  97627. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  97628. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  97629. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  97630. }
  97631. else {
  97632. fullOptions.generateMipMaps = options;
  97633. fullOptions.generateDepthBuffer = true;
  97634. fullOptions.generateStencilBuffer = false;
  97635. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97636. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  97637. }
  97638. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  97639. var width = size.width || size;
  97640. var height = size.height || size;
  97641. texture._depthStencilBuffer = {};
  97642. texture._framebuffer = {};
  97643. texture.baseWidth = width;
  97644. texture.baseHeight = height;
  97645. texture.width = width;
  97646. texture.height = height;
  97647. texture.isReady = true;
  97648. texture.samples = 1;
  97649. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  97650. texture.samplingMode = fullOptions.samplingMode;
  97651. texture.type = fullOptions.type;
  97652. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  97653. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  97654. this._internalTexturesCache.push(texture);
  97655. return texture;
  97656. };
  97657. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  97658. texture.samplingMode = samplingMode;
  97659. };
  97660. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  97661. if (this._currentRenderTarget) {
  97662. this.unBindFramebuffer(this._currentRenderTarget);
  97663. }
  97664. this._currentRenderTarget = texture;
  97665. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  97666. if (this._cachedViewport && !forceFullscreenViewport) {
  97667. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  97668. }
  97669. };
  97670. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  97671. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  97672. this._currentRenderTarget = null;
  97673. if (onBeforeUnbind) {
  97674. if (texture._MSAAFramebuffer) {
  97675. this._currentFramebuffer = texture._framebuffer;
  97676. }
  97677. onBeforeUnbind();
  97678. }
  97679. this._currentFramebuffer = null;
  97680. };
  97681. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  97682. var vbo = {
  97683. capacity: 1,
  97684. references: 1,
  97685. is32Bits: false
  97686. };
  97687. return vbo;
  97688. };
  97689. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  97690. if (offset === void 0) { offset = 0; }
  97691. };
  97692. /**
  97693. * Updates a dynamic vertex buffer.
  97694. * @param vertexBuffer the vertex buffer to update
  97695. * @param data the data used to update the vertex buffer
  97696. * @param byteOffset the byte offset of the data (optional)
  97697. * @param byteLength the byte length of the data (optional)
  97698. */
  97699. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  97700. };
  97701. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  97702. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  97703. this._boundTexturesCache[this._activeChannel] = texture;
  97704. }
  97705. };
  97706. NullEngine.prototype._bindTexture = function (channel, texture) {
  97707. if (channel < 0) {
  97708. return;
  97709. }
  97710. this._bindTextureDirectly(0, texture);
  97711. };
  97712. NullEngine.prototype._releaseBuffer = function (buffer) {
  97713. buffer.references--;
  97714. if (buffer.references === 0) {
  97715. return true;
  97716. }
  97717. return false;
  97718. };
  97719. NullEngine.prototype.releaseEffects = function () {
  97720. };
  97721. return NullEngine;
  97722. }(BABYLON.Engine));
  97723. BABYLON.NullEngine = NullEngine;
  97724. })(BABYLON || (BABYLON = {}));
  97725. //# sourceMappingURL=babylon.nullEngine.js.map
  97726. var BABYLON;
  97727. (function (BABYLON) {
  97728. /**
  97729. * This class can be used to get instrumentation data from a Babylon engine
  97730. */
  97731. var EngineInstrumentation = /** @class */ (function () {
  97732. function EngineInstrumentation(engine) {
  97733. this.engine = engine;
  97734. this._captureGPUFrameTime = false;
  97735. this._gpuFrameTime = new BABYLON.PerfCounter();
  97736. this._captureShaderCompilationTime = false;
  97737. this._shaderCompilationTime = new BABYLON.PerfCounter();
  97738. // Observers
  97739. this._onBeginFrameObserver = null;
  97740. this._onEndFrameObserver = null;
  97741. this._onBeforeShaderCompilationObserver = null;
  97742. this._onAfterShaderCompilationObserver = null;
  97743. }
  97744. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  97745. // Properties
  97746. /**
  97747. * Gets the perf counter used for GPU frame time
  97748. */
  97749. get: function () {
  97750. return this._gpuFrameTime;
  97751. },
  97752. enumerable: true,
  97753. configurable: true
  97754. });
  97755. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  97756. /**
  97757. * Gets the GPU frame time capture status
  97758. */
  97759. get: function () {
  97760. return this._captureGPUFrameTime;
  97761. },
  97762. /**
  97763. * Enable or disable the GPU frame time capture
  97764. */
  97765. set: function (value) {
  97766. var _this = this;
  97767. if (value === this._captureGPUFrameTime) {
  97768. return;
  97769. }
  97770. this._captureGPUFrameTime = value;
  97771. if (value) {
  97772. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  97773. if (!_this._gpuFrameTimeToken) {
  97774. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  97775. }
  97776. });
  97777. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  97778. if (!_this._gpuFrameTimeToken) {
  97779. return;
  97780. }
  97781. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  97782. if (time > -1) {
  97783. _this._gpuFrameTimeToken = null;
  97784. _this._gpuFrameTime.fetchNewFrame();
  97785. _this._gpuFrameTime.addCount(time, true);
  97786. }
  97787. });
  97788. }
  97789. else {
  97790. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  97791. this._onBeginFrameObserver = null;
  97792. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  97793. this._onEndFrameObserver = null;
  97794. }
  97795. },
  97796. enumerable: true,
  97797. configurable: true
  97798. });
  97799. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  97800. /**
  97801. * Gets the perf counter used for shader compilation time
  97802. */
  97803. get: function () {
  97804. return this._shaderCompilationTime;
  97805. },
  97806. enumerable: true,
  97807. configurable: true
  97808. });
  97809. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  97810. /**
  97811. * Gets the shader compilation time capture status
  97812. */
  97813. get: function () {
  97814. return this._captureShaderCompilationTime;
  97815. },
  97816. /**
  97817. * Enable or disable the shader compilation time capture
  97818. */
  97819. set: function (value) {
  97820. var _this = this;
  97821. if (value === this._captureShaderCompilationTime) {
  97822. return;
  97823. }
  97824. this._captureShaderCompilationTime = value;
  97825. if (value) {
  97826. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  97827. _this._shaderCompilationTime.fetchNewFrame();
  97828. _this._shaderCompilationTime.beginMonitoring();
  97829. });
  97830. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  97831. _this._shaderCompilationTime.endMonitoring();
  97832. });
  97833. }
  97834. else {
  97835. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  97836. this._onBeforeShaderCompilationObserver = null;
  97837. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  97838. this._onAfterShaderCompilationObserver = null;
  97839. }
  97840. },
  97841. enumerable: true,
  97842. configurable: true
  97843. });
  97844. EngineInstrumentation.prototype.dispose = function () {
  97845. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  97846. this._onBeginFrameObserver = null;
  97847. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  97848. this._onEndFrameObserver = null;
  97849. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  97850. this._onBeforeShaderCompilationObserver = null;
  97851. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  97852. this._onAfterShaderCompilationObserver = null;
  97853. this.engine = null;
  97854. };
  97855. return EngineInstrumentation;
  97856. }());
  97857. BABYLON.EngineInstrumentation = EngineInstrumentation;
  97858. })(BABYLON || (BABYLON = {}));
  97859. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  97860. var BABYLON;
  97861. (function (BABYLON) {
  97862. /**
  97863. * This class can be used to get instrumentation data from a Babylon engine
  97864. */
  97865. var SceneInstrumentation = /** @class */ (function () {
  97866. function SceneInstrumentation(scene) {
  97867. var _this = this;
  97868. this.scene = scene;
  97869. this._captureActiveMeshesEvaluationTime = false;
  97870. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  97871. this._captureRenderTargetsRenderTime = false;
  97872. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  97873. this._captureFrameTime = false;
  97874. this._frameTime = new BABYLON.PerfCounter();
  97875. this._captureRenderTime = false;
  97876. this._renderTime = new BABYLON.PerfCounter();
  97877. this._captureInterFrameTime = false;
  97878. this._interFrameTime = new BABYLON.PerfCounter();
  97879. this._captureParticlesRenderTime = false;
  97880. this._particlesRenderTime = new BABYLON.PerfCounter();
  97881. this._captureSpritesRenderTime = false;
  97882. this._spritesRenderTime = new BABYLON.PerfCounter();
  97883. this._capturePhysicsTime = false;
  97884. this._physicsTime = new BABYLON.PerfCounter();
  97885. this._captureAnimationsTime = false;
  97886. this._animationsTime = new BABYLON.PerfCounter();
  97887. // Observers
  97888. this._onBeforeActiveMeshesEvaluationObserver = null;
  97889. this._onAfterActiveMeshesEvaluationObserver = null;
  97890. this._onBeforeRenderTargetsRenderObserver = null;
  97891. this._onAfterRenderTargetsRenderObserver = null;
  97892. this._onAfterRenderObserver = null;
  97893. this._onBeforeDrawPhaseObserver = null;
  97894. this._onAfterDrawPhaseObserver = null;
  97895. this._onBeforeAnimationsObserver = null;
  97896. this._onBeforeParticlesRenderingObserver = null;
  97897. this._onAfterParticlesRenderingObserver = null;
  97898. this._onBeforeSpritesRenderingObserver = null;
  97899. this._onAfterSpritesRenderingObserver = null;
  97900. this._onBeforePhysicsObserver = null;
  97901. this._onAfterPhysicsObserver = null;
  97902. this._onAfterAnimationsObserver = null;
  97903. // Before render
  97904. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  97905. if (_this._captureActiveMeshesEvaluationTime) {
  97906. _this._activeMeshesEvaluationTime.fetchNewFrame();
  97907. }
  97908. if (_this._captureRenderTargetsRenderTime) {
  97909. _this._renderTargetsRenderTime.fetchNewFrame();
  97910. }
  97911. if (_this._captureFrameTime) {
  97912. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  97913. _this._frameTime.beginMonitoring();
  97914. }
  97915. if (_this._captureInterFrameTime) {
  97916. _this._interFrameTime.endMonitoring();
  97917. }
  97918. if (_this._captureParticlesRenderTime) {
  97919. _this._particlesRenderTime.fetchNewFrame();
  97920. }
  97921. if (_this._captureSpritesRenderTime) {
  97922. _this._spritesRenderTime.fetchNewFrame();
  97923. }
  97924. if (_this._captureAnimationsTime) {
  97925. _this._animationsTime.beginMonitoring();
  97926. }
  97927. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  97928. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  97929. });
  97930. // After render
  97931. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  97932. if (_this._captureFrameTime) {
  97933. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  97934. _this._frameTime.endMonitoring();
  97935. }
  97936. if (_this._captureRenderTime) {
  97937. _this._renderTime.endMonitoring(false);
  97938. }
  97939. if (_this._captureInterFrameTime) {
  97940. _this._interFrameTime.beginMonitoring();
  97941. }
  97942. });
  97943. }
  97944. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  97945. // Properties
  97946. /**
  97947. * Gets the perf counter used for active meshes evaluation time
  97948. */
  97949. get: function () {
  97950. return this._activeMeshesEvaluationTime;
  97951. },
  97952. enumerable: true,
  97953. configurable: true
  97954. });
  97955. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  97956. /**
  97957. * Gets the active meshes evaluation time capture status
  97958. */
  97959. get: function () {
  97960. return this._captureActiveMeshesEvaluationTime;
  97961. },
  97962. /**
  97963. * Enable or disable the active meshes evaluation time capture
  97964. */
  97965. set: function (value) {
  97966. var _this = this;
  97967. if (value === this._captureActiveMeshesEvaluationTime) {
  97968. return;
  97969. }
  97970. this._captureActiveMeshesEvaluationTime = value;
  97971. if (value) {
  97972. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  97973. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  97974. _this._activeMeshesEvaluationTime.beginMonitoring();
  97975. });
  97976. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  97977. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  97978. _this._activeMeshesEvaluationTime.endMonitoring();
  97979. });
  97980. }
  97981. else {
  97982. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  97983. this._onBeforeActiveMeshesEvaluationObserver = null;
  97984. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  97985. this._onAfterActiveMeshesEvaluationObserver = null;
  97986. }
  97987. },
  97988. enumerable: true,
  97989. configurable: true
  97990. });
  97991. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  97992. /**
  97993. * Gets the perf counter used for render targets render time
  97994. */
  97995. get: function () {
  97996. return this._renderTargetsRenderTime;
  97997. },
  97998. enumerable: true,
  97999. configurable: true
  98000. });
  98001. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  98002. /**
  98003. * Gets the render targets render time capture status
  98004. */
  98005. get: function () {
  98006. return this._captureRenderTargetsRenderTime;
  98007. },
  98008. /**
  98009. * Enable or disable the render targets render time capture
  98010. */
  98011. set: function (value) {
  98012. var _this = this;
  98013. if (value === this._captureRenderTargetsRenderTime) {
  98014. return;
  98015. }
  98016. this._captureRenderTargetsRenderTime = value;
  98017. if (value) {
  98018. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  98019. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  98020. _this._renderTargetsRenderTime.beginMonitoring();
  98021. });
  98022. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  98023. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  98024. _this._renderTargetsRenderTime.endMonitoring(false);
  98025. });
  98026. }
  98027. else {
  98028. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  98029. this._onBeforeRenderTargetsRenderObserver = null;
  98030. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  98031. this._onAfterRenderTargetsRenderObserver = null;
  98032. }
  98033. },
  98034. enumerable: true,
  98035. configurable: true
  98036. });
  98037. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  98038. /**
  98039. * Gets the perf counter used for particles render time
  98040. */
  98041. get: function () {
  98042. return this._particlesRenderTime;
  98043. },
  98044. enumerable: true,
  98045. configurable: true
  98046. });
  98047. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  98048. /**
  98049. * Gets the particles render time capture status
  98050. */
  98051. get: function () {
  98052. return this._captureParticlesRenderTime;
  98053. },
  98054. /**
  98055. * Enable or disable the particles render time capture
  98056. */
  98057. set: function (value) {
  98058. var _this = this;
  98059. if (value === this._captureParticlesRenderTime) {
  98060. return;
  98061. }
  98062. this._captureParticlesRenderTime = value;
  98063. if (value) {
  98064. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  98065. BABYLON.Tools.StartPerformanceCounter("Particles");
  98066. _this._particlesRenderTime.beginMonitoring();
  98067. });
  98068. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  98069. BABYLON.Tools.EndPerformanceCounter("Particles");
  98070. _this._particlesRenderTime.endMonitoring(false);
  98071. });
  98072. }
  98073. else {
  98074. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  98075. this._onBeforeParticlesRenderingObserver = null;
  98076. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  98077. this._onAfterParticlesRenderingObserver = null;
  98078. }
  98079. },
  98080. enumerable: true,
  98081. configurable: true
  98082. });
  98083. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  98084. /**
  98085. * Gets the perf counter used for sprites render time
  98086. */
  98087. get: function () {
  98088. return this._spritesRenderTime;
  98089. },
  98090. enumerable: true,
  98091. configurable: true
  98092. });
  98093. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  98094. /**
  98095. * Gets the sprites render time capture status
  98096. */
  98097. get: function () {
  98098. return this._captureSpritesRenderTime;
  98099. },
  98100. /**
  98101. * Enable or disable the sprites render time capture
  98102. */
  98103. set: function (value) {
  98104. var _this = this;
  98105. if (value === this._captureSpritesRenderTime) {
  98106. return;
  98107. }
  98108. this._captureSpritesRenderTime = value;
  98109. if (value) {
  98110. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  98111. BABYLON.Tools.StartPerformanceCounter("Sprites");
  98112. _this._spritesRenderTime.beginMonitoring();
  98113. });
  98114. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  98115. BABYLON.Tools.EndPerformanceCounter("Sprites");
  98116. _this._spritesRenderTime.endMonitoring(false);
  98117. });
  98118. }
  98119. else {
  98120. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  98121. this._onBeforeSpritesRenderingObserver = null;
  98122. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  98123. this._onAfterSpritesRenderingObserver = null;
  98124. }
  98125. },
  98126. enumerable: true,
  98127. configurable: true
  98128. });
  98129. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  98130. /**
  98131. * Gets the perf counter used for physics time
  98132. */
  98133. get: function () {
  98134. return this._physicsTime;
  98135. },
  98136. enumerable: true,
  98137. configurable: true
  98138. });
  98139. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  98140. /**
  98141. * Gets the physics time capture status
  98142. */
  98143. get: function () {
  98144. return this._capturePhysicsTime;
  98145. },
  98146. /**
  98147. * Enable or disable the physics time capture
  98148. */
  98149. set: function (value) {
  98150. var _this = this;
  98151. if (value === this._capturePhysicsTime) {
  98152. return;
  98153. }
  98154. this._capturePhysicsTime = value;
  98155. if (value) {
  98156. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  98157. BABYLON.Tools.StartPerformanceCounter("Physics");
  98158. _this._physicsTime.beginMonitoring();
  98159. });
  98160. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  98161. BABYLON.Tools.EndPerformanceCounter("Physics");
  98162. _this._physicsTime.endMonitoring();
  98163. });
  98164. }
  98165. else {
  98166. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  98167. this._onBeforePhysicsObserver = null;
  98168. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  98169. this._onAfterPhysicsObserver = null;
  98170. }
  98171. },
  98172. enumerable: true,
  98173. configurable: true
  98174. });
  98175. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  98176. /**
  98177. * Gets the perf counter used for animations time
  98178. */
  98179. get: function () {
  98180. return this._animationsTime;
  98181. },
  98182. enumerable: true,
  98183. configurable: true
  98184. });
  98185. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  98186. /**
  98187. * Gets the animations time capture status
  98188. */
  98189. get: function () {
  98190. return this._captureAnimationsTime;
  98191. },
  98192. /**
  98193. * Enable or disable the animations time capture
  98194. */
  98195. set: function (value) {
  98196. var _this = this;
  98197. if (value === this._captureAnimationsTime) {
  98198. return;
  98199. }
  98200. this._captureAnimationsTime = value;
  98201. if (value) {
  98202. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  98203. _this._animationsTime.endMonitoring();
  98204. });
  98205. }
  98206. else {
  98207. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  98208. this._onAfterAnimationsObserver = null;
  98209. }
  98210. },
  98211. enumerable: true,
  98212. configurable: true
  98213. });
  98214. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  98215. /**
  98216. * Gets the perf counter used for frame time capture
  98217. */
  98218. get: function () {
  98219. return this._frameTime;
  98220. },
  98221. enumerable: true,
  98222. configurable: true
  98223. });
  98224. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  98225. /**
  98226. * Gets the frame time capture status
  98227. */
  98228. get: function () {
  98229. return this._captureFrameTime;
  98230. },
  98231. /**
  98232. * Enable or disable the frame time capture
  98233. */
  98234. set: function (value) {
  98235. this._captureFrameTime = value;
  98236. },
  98237. enumerable: true,
  98238. configurable: true
  98239. });
  98240. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  98241. /**
  98242. * Gets the perf counter used for inter-frames time capture
  98243. */
  98244. get: function () {
  98245. return this._interFrameTime;
  98246. },
  98247. enumerable: true,
  98248. configurable: true
  98249. });
  98250. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  98251. /**
  98252. * Gets the inter-frames time capture status
  98253. */
  98254. get: function () {
  98255. return this._captureInterFrameTime;
  98256. },
  98257. /**
  98258. * Enable or disable the inter-frames time capture
  98259. */
  98260. set: function (value) {
  98261. this._captureInterFrameTime = value;
  98262. },
  98263. enumerable: true,
  98264. configurable: true
  98265. });
  98266. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  98267. /**
  98268. * Gets the perf counter used for render time capture
  98269. */
  98270. get: function () {
  98271. return this._renderTime;
  98272. },
  98273. enumerable: true,
  98274. configurable: true
  98275. });
  98276. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  98277. /**
  98278. * Gets the render time capture status
  98279. */
  98280. get: function () {
  98281. return this._captureRenderTime;
  98282. },
  98283. /**
  98284. * Enable or disable the render time capture
  98285. */
  98286. set: function (value) {
  98287. var _this = this;
  98288. if (value === this._captureRenderTime) {
  98289. return;
  98290. }
  98291. this._captureRenderTime = value;
  98292. if (value) {
  98293. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  98294. _this._renderTime.beginMonitoring();
  98295. BABYLON.Tools.StartPerformanceCounter("Main render");
  98296. });
  98297. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  98298. _this._renderTime.endMonitoring(false);
  98299. BABYLON.Tools.EndPerformanceCounter("Main render");
  98300. });
  98301. }
  98302. else {
  98303. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  98304. this._onBeforeDrawPhaseObserver = null;
  98305. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  98306. this._onAfterDrawPhaseObserver = null;
  98307. }
  98308. },
  98309. enumerable: true,
  98310. configurable: true
  98311. });
  98312. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  98313. /**
  98314. * Gets the perf counter used for draw calls
  98315. */
  98316. get: function () {
  98317. return this.scene.getEngine()._drawCalls;
  98318. },
  98319. enumerable: true,
  98320. configurable: true
  98321. });
  98322. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  98323. /**
  98324. * Gets the perf counter used for texture collisions
  98325. */
  98326. get: function () {
  98327. return this.scene.getEngine()._textureCollisions;
  98328. },
  98329. enumerable: true,
  98330. configurable: true
  98331. });
  98332. SceneInstrumentation.prototype.dispose = function () {
  98333. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  98334. this._onAfterRenderObserver = null;
  98335. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  98336. this._onBeforeActiveMeshesEvaluationObserver = null;
  98337. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  98338. this._onAfterActiveMeshesEvaluationObserver = null;
  98339. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  98340. this._onBeforeRenderTargetsRenderObserver = null;
  98341. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  98342. this._onAfterRenderTargetsRenderObserver = null;
  98343. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  98344. this._onBeforeAnimationsObserver = null;
  98345. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  98346. this._onBeforeParticlesRenderingObserver = null;
  98347. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  98348. this._onAfterParticlesRenderingObserver = null;
  98349. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  98350. this._onBeforeSpritesRenderingObserver = null;
  98351. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  98352. this._onAfterSpritesRenderingObserver = null;
  98353. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  98354. this._onBeforeDrawPhaseObserver = null;
  98355. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  98356. this._onAfterDrawPhaseObserver = null;
  98357. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  98358. this._onBeforePhysicsObserver = null;
  98359. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  98360. this._onAfterPhysicsObserver = null;
  98361. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  98362. this._onAfterAnimationsObserver = null;
  98363. this.scene = null;
  98364. };
  98365. return SceneInstrumentation;
  98366. }());
  98367. BABYLON.SceneInstrumentation = SceneInstrumentation;
  98368. })(BABYLON || (BABYLON = {}));
  98369. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  98370. var BABYLON;
  98371. (function (BABYLON) {
  98372. /**
  98373. * @hidden
  98374. **/
  98375. var _TimeToken = /** @class */ (function () {
  98376. function _TimeToken() {
  98377. this._timeElapsedQueryEnded = false;
  98378. }
  98379. return _TimeToken;
  98380. }());
  98381. BABYLON._TimeToken = _TimeToken;
  98382. })(BABYLON || (BABYLON = {}));
  98383. //# sourceMappingURL=babylon.timeToken.js.map
  98384. var BABYLON;
  98385. (function (BABYLON) {
  98386. /**
  98387. * Background material defines definition.
  98388. * @hidden Mainly internal Use
  98389. */
  98390. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  98391. __extends(BackgroundMaterialDefines, _super);
  98392. /**
  98393. * Constructor of the defines.
  98394. */
  98395. function BackgroundMaterialDefines() {
  98396. var _this = _super.call(this) || this;
  98397. /**
  98398. * True if the diffuse texture is in use.
  98399. */
  98400. _this.DIFFUSE = false;
  98401. /**
  98402. * The direct UV channel to use.
  98403. */
  98404. _this.DIFFUSEDIRECTUV = 0;
  98405. /**
  98406. * True if the diffuse texture is in gamma space.
  98407. */
  98408. _this.GAMMADIFFUSE = false;
  98409. /**
  98410. * True if the diffuse texture has opacity in the alpha channel.
  98411. */
  98412. _this.DIFFUSEHASALPHA = false;
  98413. /**
  98414. * True if you want the material to fade to transparent at grazing angle.
  98415. */
  98416. _this.OPACITYFRESNEL = false;
  98417. /**
  98418. * True if an extra blur needs to be added in the reflection.
  98419. */
  98420. _this.REFLECTIONBLUR = false;
  98421. /**
  98422. * True if you want the material to fade to reflection at grazing angle.
  98423. */
  98424. _this.REFLECTIONFRESNEL = false;
  98425. /**
  98426. * True if you want the material to falloff as far as you move away from the scene center.
  98427. */
  98428. _this.REFLECTIONFALLOFF = false;
  98429. /**
  98430. * False if the current Webgl implementation does not support the texture lod extension.
  98431. */
  98432. _this.TEXTURELODSUPPORT = false;
  98433. /**
  98434. * True to ensure the data are premultiplied.
  98435. */
  98436. _this.PREMULTIPLYALPHA = false;
  98437. /**
  98438. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  98439. */
  98440. _this.USERGBCOLOR = false;
  98441. /**
  98442. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  98443. * stays aligned with the desired configuration.
  98444. */
  98445. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  98446. /**
  98447. * True to add noise in order to reduce the banding effect.
  98448. */
  98449. _this.NOISE = false;
  98450. /**
  98451. * is the reflection texture in BGR color scheme?
  98452. * Mainly used to solve a bug in ios10 video tag
  98453. */
  98454. _this.REFLECTIONBGR = false;
  98455. _this.IMAGEPROCESSING = false;
  98456. _this.VIGNETTE = false;
  98457. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  98458. _this.VIGNETTEBLENDMODEOPAQUE = false;
  98459. _this.TONEMAPPING = false;
  98460. _this.CONTRAST = false;
  98461. _this.COLORCURVES = false;
  98462. _this.COLORGRADING = false;
  98463. _this.COLORGRADING3D = false;
  98464. _this.SAMPLER3DGREENDEPTH = false;
  98465. _this.SAMPLER3DBGRMAP = false;
  98466. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  98467. _this.EXPOSURE = false;
  98468. // Reflection.
  98469. _this.REFLECTION = false;
  98470. _this.REFLECTIONMAP_3D = false;
  98471. _this.REFLECTIONMAP_SPHERICAL = false;
  98472. _this.REFLECTIONMAP_PLANAR = false;
  98473. _this.REFLECTIONMAP_CUBIC = false;
  98474. _this.REFLECTIONMAP_PROJECTION = false;
  98475. _this.REFLECTIONMAP_SKYBOX = false;
  98476. _this.REFLECTIONMAP_EXPLICIT = false;
  98477. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  98478. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  98479. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  98480. _this.INVERTCUBICMAP = false;
  98481. _this.REFLECTIONMAP_OPPOSITEZ = false;
  98482. _this.LODINREFLECTIONALPHA = false;
  98483. _this.GAMMAREFLECTION = false;
  98484. _this.RGBDREFLECTION = false;
  98485. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  98486. // Default BJS.
  98487. _this.MAINUV1 = false;
  98488. _this.MAINUV2 = false;
  98489. _this.UV1 = false;
  98490. _this.UV2 = false;
  98491. _this.CLIPPLANE = false;
  98492. _this.POINTSIZE = false;
  98493. _this.FOG = false;
  98494. _this.NORMAL = false;
  98495. _this.NUM_BONE_INFLUENCERS = 0;
  98496. _this.BonesPerMesh = 0;
  98497. _this.INSTANCES = false;
  98498. _this.SHADOWFLOAT = false;
  98499. _this.rebuild();
  98500. return _this;
  98501. }
  98502. return BackgroundMaterialDefines;
  98503. }(BABYLON.MaterialDefines));
  98504. /**
  98505. * Background material used to create an efficient environement around your scene.
  98506. */
  98507. var BackgroundMaterial = /** @class */ (function (_super) {
  98508. __extends(BackgroundMaterial, _super);
  98509. /**
  98510. * Instantiates a Background Material in the given scene
  98511. * @param name The friendly name of the material
  98512. * @param scene The scene to add the material to
  98513. */
  98514. function BackgroundMaterial(name, scene) {
  98515. var _this = _super.call(this, name, scene) || this;
  98516. /**
  98517. * Key light Color (multiply against the environement texture)
  98518. */
  98519. _this.primaryColor = BABYLON.Color3.White();
  98520. _this._primaryColorShadowLevel = 0;
  98521. _this._primaryColorHighlightLevel = 0;
  98522. /**
  98523. * Reflection Texture used in the material.
  98524. * Should be author in a specific way for the best result (refer to the documentation).
  98525. */
  98526. _this.reflectionTexture = null;
  98527. /**
  98528. * Reflection Texture level of blur.
  98529. *
  98530. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  98531. * texture twice.
  98532. */
  98533. _this.reflectionBlur = 0;
  98534. /**
  98535. * Diffuse Texture used in the material.
  98536. * Should be author in a specific way for the best result (refer to the documentation).
  98537. */
  98538. _this.diffuseTexture = null;
  98539. _this._shadowLights = null;
  98540. /**
  98541. * Specify the list of lights casting shadow on the material.
  98542. * All scene shadow lights will be included if null.
  98543. */
  98544. _this.shadowLights = null;
  98545. /**
  98546. * Helps adjusting the shadow to a softer level if required.
  98547. * 0 means black shadows and 1 means no shadows.
  98548. */
  98549. _this.shadowLevel = 0;
  98550. /**
  98551. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  98552. * It is usually zero but might be interesting to modify according to your setup.
  98553. */
  98554. _this.sceneCenter = BABYLON.Vector3.Zero();
  98555. /**
  98556. * This helps specifying that the material is falling off to the sky box at grazing angle.
  98557. * This helps ensuring a nice transition when the camera goes under the ground.
  98558. */
  98559. _this.opacityFresnel = true;
  98560. /**
  98561. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  98562. * This helps adding a mirror texture on the ground.
  98563. */
  98564. _this.reflectionFresnel = false;
  98565. /**
  98566. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  98567. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  98568. */
  98569. _this.reflectionFalloffDistance = 0.0;
  98570. /**
  98571. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  98572. */
  98573. _this.reflectionAmount = 1.0;
  98574. /**
  98575. * This specifies the weight of the reflection at grazing angle.
  98576. */
  98577. _this.reflectionReflectance0 = 0.05;
  98578. /**
  98579. * This specifies the weight of the reflection at a perpendicular point of view.
  98580. */
  98581. _this.reflectionReflectance90 = 0.5;
  98582. /**
  98583. * Helps to directly use the maps channels instead of their level.
  98584. */
  98585. _this.useRGBColor = true;
  98586. /**
  98587. * This helps reducing the banding effect that could occur on the background.
  98588. */
  98589. _this.enableNoise = false;
  98590. _this._fovMultiplier = 1.0;
  98591. /**
  98592. * Enable the FOV adjustment feature controlled by fovMultiplier.
  98593. */
  98594. _this.useEquirectangularFOV = false;
  98595. _this._maxSimultaneousLights = 4;
  98596. /**
  98597. * Number of Simultaneous lights allowed on the material.
  98598. */
  98599. _this.maxSimultaneousLights = 4;
  98600. /**
  98601. * Keep track of the image processing observer to allow dispose and replace.
  98602. */
  98603. _this._imageProcessingObserver = null;
  98604. /**
  98605. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  98606. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  98607. */
  98608. _this.switchToBGR = false;
  98609. // Temp values kept as cache in the material.
  98610. _this._renderTargets = new BABYLON.SmartArray(16);
  98611. _this._reflectionControls = BABYLON.Vector4.Zero();
  98612. _this._white = BABYLON.Color3.White();
  98613. _this._primaryShadowColor = BABYLON.Color3.Black();
  98614. _this._primaryHighlightColor = BABYLON.Color3.Black();
  98615. // Setup the default processing configuration to the scene.
  98616. _this._attachImageProcessingConfiguration(null);
  98617. _this.getRenderTargetTextures = function () {
  98618. _this._renderTargets.reset();
  98619. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  98620. _this._renderTargets.push(_this._diffuseTexture);
  98621. }
  98622. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  98623. _this._renderTargets.push(_this._reflectionTexture);
  98624. }
  98625. return _this._renderTargets;
  98626. };
  98627. return _this;
  98628. }
  98629. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  98630. /**
  98631. * Experimental Internal Use Only.
  98632. *
  98633. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  98634. * This acts as a helper to set the primary color to a more "human friendly" value.
  98635. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  98636. * output color as close as possible from the chosen value.
  98637. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  98638. * part of lighting setup.)
  98639. */
  98640. get: function () {
  98641. return this.__perceptualColor;
  98642. },
  98643. set: function (value) {
  98644. this.__perceptualColor = value;
  98645. this._computePrimaryColorFromPerceptualColor();
  98646. this._markAllSubMeshesAsLightsDirty();
  98647. },
  98648. enumerable: true,
  98649. configurable: true
  98650. });
  98651. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  98652. /**
  98653. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  98654. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  98655. */
  98656. get: function () {
  98657. return this._primaryColorShadowLevel;
  98658. },
  98659. set: function (value) {
  98660. this._primaryColorShadowLevel = value;
  98661. this._computePrimaryColors();
  98662. this._markAllSubMeshesAsLightsDirty();
  98663. },
  98664. enumerable: true,
  98665. configurable: true
  98666. });
  98667. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  98668. /**
  98669. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  98670. * The primary color is used at the level chosen to define what the white area would look.
  98671. */
  98672. get: function () {
  98673. return this._primaryColorHighlightLevel;
  98674. },
  98675. set: function (value) {
  98676. this._primaryColorHighlightLevel = value;
  98677. this._computePrimaryColors();
  98678. this._markAllSubMeshesAsLightsDirty();
  98679. },
  98680. enumerable: true,
  98681. configurable: true
  98682. });
  98683. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  98684. /**
  98685. * Sets the reflection reflectance fresnel values according to the default standard
  98686. * empirically know to work well :-)
  98687. */
  98688. set: function (value) {
  98689. var reflectionWeight = value;
  98690. if (reflectionWeight < 0.5) {
  98691. reflectionWeight = reflectionWeight * 2.0;
  98692. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  98693. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  98694. }
  98695. else {
  98696. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  98697. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  98698. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  98699. }
  98700. },
  98701. enumerable: true,
  98702. configurable: true
  98703. });
  98704. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  98705. /**
  98706. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  98707. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  98708. * Recommended to be keep at 1.0 except for special cases.
  98709. */
  98710. get: function () {
  98711. return this._fovMultiplier;
  98712. },
  98713. set: function (value) {
  98714. if (isNaN(value)) {
  98715. value = 1.0;
  98716. }
  98717. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  98718. },
  98719. enumerable: true,
  98720. configurable: true
  98721. });
  98722. /**
  98723. * Attaches a new image processing configuration to the PBR Material.
  98724. * @param configuration (if null the scene configuration will be use)
  98725. */
  98726. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  98727. var _this = this;
  98728. if (configuration === this._imageProcessingConfiguration) {
  98729. return;
  98730. }
  98731. // Detaches observer.
  98732. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  98733. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  98734. }
  98735. // Pick the scene configuration if needed.
  98736. if (!configuration) {
  98737. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  98738. }
  98739. else {
  98740. this._imageProcessingConfiguration = configuration;
  98741. }
  98742. // Attaches observer.
  98743. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  98744. _this._computePrimaryColorFromPerceptualColor();
  98745. _this._markAllSubMeshesAsImageProcessingDirty();
  98746. });
  98747. };
  98748. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  98749. /**
  98750. * Gets the image processing configuration used either in this material.
  98751. */
  98752. get: function () {
  98753. return this._imageProcessingConfiguration;
  98754. },
  98755. /**
  98756. * Sets the Default image processing configuration used either in the this material.
  98757. *
  98758. * If sets to null, the scene one is in use.
  98759. */
  98760. set: function (value) {
  98761. this._attachImageProcessingConfiguration(value);
  98762. // Ensure the effect will be rebuilt.
  98763. this._markAllSubMeshesAsTexturesDirty();
  98764. },
  98765. enumerable: true,
  98766. configurable: true
  98767. });
  98768. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  98769. /**
  98770. * Gets wether the color curves effect is enabled.
  98771. */
  98772. get: function () {
  98773. return this.imageProcessingConfiguration.colorCurvesEnabled;
  98774. },
  98775. /**
  98776. * Sets wether the color curves effect is enabled.
  98777. */
  98778. set: function (value) {
  98779. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  98780. },
  98781. enumerable: true,
  98782. configurable: true
  98783. });
  98784. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  98785. /**
  98786. * Gets wether the color grading effect is enabled.
  98787. */
  98788. get: function () {
  98789. return this.imageProcessingConfiguration.colorGradingEnabled;
  98790. },
  98791. /**
  98792. * Gets wether the color grading effect is enabled.
  98793. */
  98794. set: function (value) {
  98795. this.imageProcessingConfiguration.colorGradingEnabled = value;
  98796. },
  98797. enumerable: true,
  98798. configurable: true
  98799. });
  98800. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  98801. /**
  98802. * Gets wether tonemapping is enabled or not.
  98803. */
  98804. get: function () {
  98805. return this._imageProcessingConfiguration.toneMappingEnabled;
  98806. },
  98807. /**
  98808. * Sets wether tonemapping is enabled or not
  98809. */
  98810. set: function (value) {
  98811. this._imageProcessingConfiguration.toneMappingEnabled = value;
  98812. },
  98813. enumerable: true,
  98814. configurable: true
  98815. });
  98816. ;
  98817. ;
  98818. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  98819. /**
  98820. * The camera exposure used on this material.
  98821. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  98822. * This corresponds to a photographic exposure.
  98823. */
  98824. get: function () {
  98825. return this._imageProcessingConfiguration.exposure;
  98826. },
  98827. /**
  98828. * The camera exposure used on this material.
  98829. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  98830. * This corresponds to a photographic exposure.
  98831. */
  98832. set: function (value) {
  98833. this._imageProcessingConfiguration.exposure = value;
  98834. },
  98835. enumerable: true,
  98836. configurable: true
  98837. });
  98838. ;
  98839. ;
  98840. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  98841. /**
  98842. * Gets The camera contrast used on this material.
  98843. */
  98844. get: function () {
  98845. return this._imageProcessingConfiguration.contrast;
  98846. },
  98847. /**
  98848. * Sets The camera contrast used on this material.
  98849. */
  98850. set: function (value) {
  98851. this._imageProcessingConfiguration.contrast = value;
  98852. },
  98853. enumerable: true,
  98854. configurable: true
  98855. });
  98856. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  98857. /**
  98858. * Gets the Color Grading 2D Lookup Texture.
  98859. */
  98860. get: function () {
  98861. return this._imageProcessingConfiguration.colorGradingTexture;
  98862. },
  98863. /**
  98864. * Sets the Color Grading 2D Lookup Texture.
  98865. */
  98866. set: function (value) {
  98867. this.imageProcessingConfiguration.colorGradingTexture = value;
  98868. },
  98869. enumerable: true,
  98870. configurable: true
  98871. });
  98872. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  98873. /**
  98874. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  98875. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  98876. * 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;
  98877. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  98878. */
  98879. get: function () {
  98880. return this.imageProcessingConfiguration.colorCurves;
  98881. },
  98882. /**
  98883. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  98884. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  98885. * 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;
  98886. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  98887. */
  98888. set: function (value) {
  98889. this.imageProcessingConfiguration.colorCurves = value;
  98890. },
  98891. enumerable: true,
  98892. configurable: true
  98893. });
  98894. /**
  98895. * The entire material has been created in order to prevent overdraw.
  98896. * @returns false
  98897. */
  98898. BackgroundMaterial.prototype.needAlphaTesting = function () {
  98899. return true;
  98900. };
  98901. /**
  98902. * The entire material has been created in order to prevent overdraw.
  98903. * @returns true if blending is enable
  98904. */
  98905. BackgroundMaterial.prototype.needAlphaBlending = function () {
  98906. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  98907. };
  98908. /**
  98909. * Checks wether the material is ready to be rendered for a given mesh.
  98910. * @param mesh The mesh to render
  98911. * @param subMesh The submesh to check against
  98912. * @param useInstances Specify wether or not the material is used with instances
  98913. * @returns true if all the dependencies are ready (Textures, Effects...)
  98914. */
  98915. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  98916. var _this = this;
  98917. if (useInstances === void 0) { useInstances = false; }
  98918. if (subMesh.effect && this.isFrozen) {
  98919. if (this._wasPreviouslyReady) {
  98920. return true;
  98921. }
  98922. }
  98923. if (!subMesh._materialDefines) {
  98924. subMesh._materialDefines = new BackgroundMaterialDefines();
  98925. }
  98926. var scene = this.getScene();
  98927. var defines = subMesh._materialDefines;
  98928. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  98929. if (defines._renderId === scene.getRenderId()) {
  98930. return true;
  98931. }
  98932. }
  98933. var engine = scene.getEngine();
  98934. // Lights
  98935. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  98936. defines._needNormals = true;
  98937. // Textures
  98938. if (defines._areTexturesDirty) {
  98939. defines._needUVs = false;
  98940. if (scene.texturesEnabled) {
  98941. if (scene.getEngine().getCaps().textureLOD) {
  98942. defines.TEXTURELODSUPPORT = true;
  98943. }
  98944. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  98945. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  98946. return false;
  98947. }
  98948. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  98949. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  98950. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  98951. defines.OPACITYFRESNEL = this._opacityFresnel;
  98952. }
  98953. else {
  98954. defines.DIFFUSE = false;
  98955. defines.DIFFUSEHASALPHA = false;
  98956. defines.GAMMADIFFUSE = false;
  98957. defines.OPACITYFRESNEL = false;
  98958. }
  98959. var reflectionTexture = this._reflectionTexture;
  98960. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  98961. if (!reflectionTexture.isReadyOrNotBlocking()) {
  98962. return false;
  98963. }
  98964. defines.REFLECTION = true;
  98965. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  98966. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  98967. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  98968. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  98969. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  98970. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  98971. defines.REFLECTIONBGR = this.switchToBGR;
  98972. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  98973. defines.INVERTCUBICMAP = true;
  98974. }
  98975. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  98976. switch (reflectionTexture.coordinatesMode) {
  98977. case BABYLON.Texture.EXPLICIT_MODE:
  98978. defines.REFLECTIONMAP_EXPLICIT = true;
  98979. break;
  98980. case BABYLON.Texture.PLANAR_MODE:
  98981. defines.REFLECTIONMAP_PLANAR = true;
  98982. break;
  98983. case BABYLON.Texture.PROJECTION_MODE:
  98984. defines.REFLECTIONMAP_PROJECTION = true;
  98985. break;
  98986. case BABYLON.Texture.SKYBOX_MODE:
  98987. defines.REFLECTIONMAP_SKYBOX = true;
  98988. break;
  98989. case BABYLON.Texture.SPHERICAL_MODE:
  98990. defines.REFLECTIONMAP_SPHERICAL = true;
  98991. break;
  98992. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  98993. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  98994. break;
  98995. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  98996. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  98997. break;
  98998. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  98999. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  99000. break;
  99001. case BABYLON.Texture.CUBIC_MODE:
  99002. case BABYLON.Texture.INVCUBIC_MODE:
  99003. default:
  99004. defines.REFLECTIONMAP_CUBIC = true;
  99005. break;
  99006. }
  99007. if (this.reflectionFresnel) {
  99008. defines.REFLECTIONFRESNEL = true;
  99009. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  99010. this._reflectionControls.x = this.reflectionAmount;
  99011. this._reflectionControls.y = this.reflectionReflectance0;
  99012. this._reflectionControls.z = this.reflectionReflectance90;
  99013. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  99014. }
  99015. else {
  99016. defines.REFLECTIONFRESNEL = false;
  99017. defines.REFLECTIONFALLOFF = false;
  99018. }
  99019. }
  99020. else {
  99021. defines.REFLECTION = false;
  99022. defines.REFLECTIONFRESNEL = false;
  99023. defines.REFLECTIONFALLOFF = false;
  99024. defines.REFLECTIONBLUR = false;
  99025. defines.REFLECTIONMAP_3D = false;
  99026. defines.REFLECTIONMAP_SPHERICAL = false;
  99027. defines.REFLECTIONMAP_PLANAR = false;
  99028. defines.REFLECTIONMAP_CUBIC = false;
  99029. defines.REFLECTIONMAP_PROJECTION = false;
  99030. defines.REFLECTIONMAP_SKYBOX = false;
  99031. defines.REFLECTIONMAP_EXPLICIT = false;
  99032. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  99033. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  99034. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  99035. defines.INVERTCUBICMAP = false;
  99036. defines.REFLECTIONMAP_OPPOSITEZ = false;
  99037. defines.LODINREFLECTIONALPHA = false;
  99038. defines.GAMMAREFLECTION = false;
  99039. defines.RGBDREFLECTION = false;
  99040. }
  99041. }
  99042. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  99043. defines.USERGBCOLOR = this._useRGBColor;
  99044. defines.NOISE = this._enableNoise;
  99045. }
  99046. if (defines._areLightsDirty) {
  99047. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  99048. }
  99049. if (defines._areImageProcessingDirty) {
  99050. if (!this._imageProcessingConfiguration.isReady()) {
  99051. return false;
  99052. }
  99053. this._imageProcessingConfiguration.prepareDefines(defines);
  99054. }
  99055. // Misc.
  99056. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  99057. // Values that need to be evaluated on every frame
  99058. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  99059. // Attribs
  99060. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  99061. if (mesh) {
  99062. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  99063. mesh.createNormals(true);
  99064. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  99065. }
  99066. }
  99067. }
  99068. // Get correct effect
  99069. if (defines.isDirty) {
  99070. defines.markAsProcessed();
  99071. scene.resetCachedMaterial();
  99072. // Fallbacks
  99073. var fallbacks = new BABYLON.EffectFallbacks();
  99074. if (defines.FOG) {
  99075. fallbacks.addFallback(0, "FOG");
  99076. }
  99077. if (defines.POINTSIZE) {
  99078. fallbacks.addFallback(1, "POINTSIZE");
  99079. }
  99080. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  99081. if (defines.NUM_BONE_INFLUENCERS > 0) {
  99082. fallbacks.addCPUSkinningFallback(0, mesh);
  99083. }
  99084. //Attributes
  99085. var attribs = [BABYLON.VertexBuffer.PositionKind];
  99086. if (defines.NORMAL) {
  99087. attribs.push(BABYLON.VertexBuffer.NormalKind);
  99088. }
  99089. if (defines.UV1) {
  99090. attribs.push(BABYLON.VertexBuffer.UVKind);
  99091. }
  99092. if (defines.UV2) {
  99093. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  99094. }
  99095. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  99096. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  99097. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  99098. "vFogInfos", "vFogColor", "pointSize",
  99099. "vClipPlane", "mBones",
  99100. "vPrimaryColor", "vPrimaryColorShadow",
  99101. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  99102. "shadowLevel", "alpha",
  99103. "vBackgroundCenter", "vReflectionControl",
  99104. "vDiffuseInfos", "diffuseMatrix",
  99105. ];
  99106. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  99107. var uniformBuffers = ["Material", "Scene"];
  99108. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  99109. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  99110. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  99111. uniformsNames: uniforms,
  99112. uniformBuffersNames: uniformBuffers,
  99113. samplers: samplers,
  99114. defines: defines,
  99115. maxSimultaneousLights: this._maxSimultaneousLights
  99116. });
  99117. var onCompiled = function (effect) {
  99118. if (_this.onCompiled) {
  99119. _this.onCompiled(effect);
  99120. }
  99121. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  99122. };
  99123. var join = defines.toString();
  99124. subMesh.setEffect(scene.getEngine().createEffect("background", {
  99125. attributes: attribs,
  99126. uniformsNames: uniforms,
  99127. uniformBuffersNames: uniformBuffers,
  99128. samplers: samplers,
  99129. defines: join,
  99130. fallbacks: fallbacks,
  99131. onCompiled: onCompiled,
  99132. onError: this.onError,
  99133. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  99134. }, engine), defines);
  99135. this.buildUniformLayout();
  99136. }
  99137. if (!subMesh.effect || !subMesh.effect.isReady()) {
  99138. return false;
  99139. }
  99140. defines._renderId = scene.getRenderId();
  99141. this._wasPreviouslyReady = true;
  99142. return true;
  99143. };
  99144. /**
  99145. * Compute the primary color according to the chosen perceptual color.
  99146. */
  99147. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  99148. if (!this.__perceptualColor) {
  99149. return;
  99150. }
  99151. this._primaryColor.copyFrom(this.__perceptualColor);
  99152. // Revert gamma space.
  99153. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  99154. // Revert image processing configuration.
  99155. if (this._imageProcessingConfiguration) {
  99156. // Revert Exposure.
  99157. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  99158. }
  99159. this._computePrimaryColors();
  99160. };
  99161. /**
  99162. * Compute the highlights and shadow colors according to their chosen levels.
  99163. */
  99164. BackgroundMaterial.prototype._computePrimaryColors = function () {
  99165. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  99166. return;
  99167. }
  99168. // Find the highlight color based on the configuration.
  99169. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  99170. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  99171. // Find the shadow color based on the configuration.
  99172. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  99173. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  99174. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  99175. };
  99176. /**
  99177. * Build the uniform buffer used in the material.
  99178. */
  99179. BackgroundMaterial.prototype.buildUniformLayout = function () {
  99180. // Order is important !
  99181. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  99182. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  99183. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  99184. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  99185. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  99186. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  99187. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  99188. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  99189. this._uniformBuffer.addUniform("pointSize", 1);
  99190. this._uniformBuffer.addUniform("shadowLevel", 1);
  99191. this._uniformBuffer.addUniform("alpha", 1);
  99192. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  99193. this._uniformBuffer.addUniform("vReflectionControl", 4);
  99194. this._uniformBuffer.create();
  99195. };
  99196. /**
  99197. * Unbind the material.
  99198. */
  99199. BackgroundMaterial.prototype.unbind = function () {
  99200. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  99201. this._uniformBuffer.setTexture("diffuseSampler", null);
  99202. }
  99203. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  99204. this._uniformBuffer.setTexture("reflectionSampler", null);
  99205. }
  99206. _super.prototype.unbind.call(this);
  99207. };
  99208. /**
  99209. * Bind only the world matrix to the material.
  99210. * @param world The world matrix to bind.
  99211. */
  99212. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  99213. this._activeEffect.setMatrix("world", world);
  99214. };
  99215. /**
  99216. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  99217. * @param world The world matrix to bind.
  99218. * @param subMesh The submesh to bind for.
  99219. */
  99220. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  99221. var scene = this.getScene();
  99222. var defines = subMesh._materialDefines;
  99223. if (!defines) {
  99224. return;
  99225. }
  99226. var effect = subMesh.effect;
  99227. if (!effect) {
  99228. return;
  99229. }
  99230. this._activeEffect = effect;
  99231. // Matrices
  99232. this.bindOnlyWorldMatrix(world);
  99233. // Bones
  99234. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  99235. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  99236. if (mustRebind) {
  99237. this._uniformBuffer.bindToEffect(effect, "Material");
  99238. this.bindViewProjection(effect);
  99239. var reflectionTexture = this._reflectionTexture;
  99240. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  99241. // Texture uniforms
  99242. if (scene.texturesEnabled) {
  99243. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99244. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  99245. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  99246. }
  99247. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99248. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  99249. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  99250. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  99251. }
  99252. }
  99253. if (this.shadowLevel > 0) {
  99254. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  99255. }
  99256. this._uniformBuffer.updateFloat("alpha", this.alpha);
  99257. // Point size
  99258. if (this.pointsCloud) {
  99259. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  99260. }
  99261. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  99262. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  99263. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  99264. }
  99265. else {
  99266. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  99267. }
  99268. }
  99269. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  99270. // Textures
  99271. if (scene.texturesEnabled) {
  99272. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99273. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  99274. }
  99275. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99276. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  99277. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  99278. }
  99279. else if (!defines.REFLECTIONBLUR) {
  99280. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  99281. }
  99282. else {
  99283. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  99284. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  99285. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  99286. }
  99287. if (defines.REFLECTIONFRESNEL) {
  99288. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  99289. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  99290. }
  99291. }
  99292. }
  99293. // Clip plane
  99294. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  99295. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  99296. }
  99297. if (mustRebind || !this.isFrozen) {
  99298. if (scene.lightsEnabled) {
  99299. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  99300. }
  99301. // View
  99302. this.bindView(effect);
  99303. // Fog
  99304. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  99305. // image processing
  99306. this._imageProcessingConfiguration.bind(this._activeEffect);
  99307. }
  99308. this._uniformBuffer.update();
  99309. this._afterBind(mesh);
  99310. };
  99311. /**
  99312. * Dispose the material.
  99313. * @param forceDisposeEffect Force disposal of the associated effect.
  99314. * @param forceDisposeTextures Force disposal of the associated textures.
  99315. */
  99316. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  99317. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  99318. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  99319. if (forceDisposeTextures) {
  99320. if (this.diffuseTexture) {
  99321. this.diffuseTexture.dispose();
  99322. }
  99323. if (this.reflectionTexture) {
  99324. this.reflectionTexture.dispose();
  99325. }
  99326. }
  99327. this._renderTargets.dispose();
  99328. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  99329. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  99330. }
  99331. _super.prototype.dispose.call(this, forceDisposeEffect);
  99332. };
  99333. /**
  99334. * Clones the material.
  99335. * @param name The cloned name.
  99336. * @returns The cloned material.
  99337. */
  99338. BackgroundMaterial.prototype.clone = function (name) {
  99339. var _this = this;
  99340. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  99341. };
  99342. /**
  99343. * Serializes the current material to its JSON representation.
  99344. * @returns The JSON representation.
  99345. */
  99346. BackgroundMaterial.prototype.serialize = function () {
  99347. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  99348. serializationObject.customType = "BABYLON.BackgroundMaterial";
  99349. return serializationObject;
  99350. };
  99351. /**
  99352. * Gets the class name of the material
  99353. * @returns "BackgroundMaterial"
  99354. */
  99355. BackgroundMaterial.prototype.getClassName = function () {
  99356. return "BackgroundMaterial";
  99357. };
  99358. /**
  99359. * Parse a JSON input to create back a background material.
  99360. * @param source The JSON data to parse
  99361. * @param scene The scene to create the parsed material in
  99362. * @param rootUrl The root url of the assets the material depends upon
  99363. * @returns the instantiated BackgroundMaterial.
  99364. */
  99365. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  99366. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  99367. };
  99368. /**
  99369. * Standard reflectance value at parallel view angle.
  99370. */
  99371. BackgroundMaterial.StandardReflectance0 = 0.05;
  99372. /**
  99373. * Standard reflectance value at grazing angle.
  99374. */
  99375. BackgroundMaterial.StandardReflectance90 = 0.5;
  99376. __decorate([
  99377. BABYLON.serializeAsColor3()
  99378. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  99379. __decorate([
  99380. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  99381. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  99382. __decorate([
  99383. BABYLON.serializeAsColor3()
  99384. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  99385. __decorate([
  99386. BABYLON.serialize()
  99387. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  99388. __decorate([
  99389. BABYLON.serialize()
  99390. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  99391. __decorate([
  99392. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  99393. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  99394. __decorate([
  99395. BABYLON.serializeAsTexture()
  99396. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  99397. __decorate([
  99398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99399. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  99400. __decorate([
  99401. BABYLON.serialize()
  99402. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  99403. __decorate([
  99404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99405. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  99406. __decorate([
  99407. BABYLON.serializeAsTexture()
  99408. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  99409. __decorate([
  99410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99411. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  99412. __decorate([
  99413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99414. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  99415. __decorate([
  99416. BABYLON.serialize()
  99417. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  99418. __decorate([
  99419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99420. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  99421. __decorate([
  99422. BABYLON.serializeAsVector3()
  99423. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  99424. __decorate([
  99425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99426. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  99427. __decorate([
  99428. BABYLON.serialize()
  99429. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  99430. __decorate([
  99431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99432. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  99433. __decorate([
  99434. BABYLON.serialize()
  99435. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  99436. __decorate([
  99437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99438. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  99439. __decorate([
  99440. BABYLON.serialize()
  99441. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  99442. __decorate([
  99443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99444. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  99445. __decorate([
  99446. BABYLON.serialize()
  99447. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  99448. __decorate([
  99449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99450. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  99451. __decorate([
  99452. BABYLON.serialize()
  99453. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  99454. __decorate([
  99455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99456. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  99457. __decorate([
  99458. BABYLON.serialize()
  99459. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  99460. __decorate([
  99461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99462. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  99463. __decorate([
  99464. BABYLON.serialize()
  99465. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  99466. __decorate([
  99467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99468. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  99469. __decorate([
  99470. BABYLON.serialize()
  99471. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  99472. __decorate([
  99473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99474. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  99475. __decorate([
  99476. BABYLON.serialize()
  99477. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  99478. __decorate([
  99479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99480. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  99481. __decorate([
  99482. BABYLON.serializeAsImageProcessingConfiguration()
  99483. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  99484. return BackgroundMaterial;
  99485. }(BABYLON.PushMaterial));
  99486. BABYLON.BackgroundMaterial = BackgroundMaterial;
  99487. })(BABYLON || (BABYLON = {}));
  99488. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  99489. var __assign = (this && this.__assign) || Object.assign || function(t) {
  99490. for (var s, i = 1, n = arguments.length; i < n; i++) {
  99491. s = arguments[i];
  99492. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  99493. t[p] = s[p];
  99494. }
  99495. return t;
  99496. };
  99497. var BABYLON;
  99498. (function (BABYLON) {
  99499. /**
  99500. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  99501. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  99502. * It also helps with the default setup of your imageProcessing configuration.
  99503. */
  99504. var EnvironmentHelper = /** @class */ (function () {
  99505. /**
  99506. * constructor
  99507. * @param options
  99508. * @param scene The scene to add the material to
  99509. */
  99510. function EnvironmentHelper(options, scene) {
  99511. var _this = this;
  99512. this._errorHandler = function (message, exception) {
  99513. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  99514. };
  99515. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  99516. this._scene = scene;
  99517. this.onErrorObservable = new BABYLON.Observable();
  99518. this._setupBackground();
  99519. this._setupImageProcessing();
  99520. }
  99521. /**
  99522. * Creates the default options for the helper.
  99523. */
  99524. EnvironmentHelper._getDefaultOptions = function () {
  99525. return {
  99526. createGround: true,
  99527. groundSize: 15,
  99528. groundTexture: this._groundTextureCDNUrl,
  99529. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  99530. groundOpacity: 0.9,
  99531. enableGroundShadow: true,
  99532. groundShadowLevel: 0.5,
  99533. enableGroundMirror: false,
  99534. groundMirrorSizeRatio: 0.3,
  99535. groundMirrorBlurKernel: 64,
  99536. groundMirrorAmount: 1,
  99537. groundMirrorFresnelWeight: 1,
  99538. groundMirrorFallOffDistance: 0,
  99539. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  99540. groundYBias: 0.00001,
  99541. createSkybox: true,
  99542. skyboxSize: 20,
  99543. skyboxTexture: this._skyboxTextureCDNUrl,
  99544. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  99545. backgroundYRotation: 0,
  99546. sizeAuto: true,
  99547. rootPosition: BABYLON.Vector3.Zero(),
  99548. setupImageProcessing: true,
  99549. environmentTexture: this._environmentTextureCDNUrl,
  99550. cameraExposure: 0.8,
  99551. cameraContrast: 1.2,
  99552. toneMappingEnabled: true,
  99553. };
  99554. };
  99555. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  99556. /**
  99557. * Gets the root mesh created by the helper.
  99558. */
  99559. get: function () {
  99560. return this._rootMesh;
  99561. },
  99562. enumerable: true,
  99563. configurable: true
  99564. });
  99565. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  99566. /**
  99567. * Gets the skybox created by the helper.
  99568. */
  99569. get: function () {
  99570. return this._skybox;
  99571. },
  99572. enumerable: true,
  99573. configurable: true
  99574. });
  99575. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  99576. /**
  99577. * Gets the skybox texture created by the helper.
  99578. */
  99579. get: function () {
  99580. return this._skyboxTexture;
  99581. },
  99582. enumerable: true,
  99583. configurable: true
  99584. });
  99585. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  99586. /**
  99587. * Gets the skybox material created by the helper.
  99588. */
  99589. get: function () {
  99590. return this._skyboxMaterial;
  99591. },
  99592. enumerable: true,
  99593. configurable: true
  99594. });
  99595. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  99596. /**
  99597. * Gets the ground mesh created by the helper.
  99598. */
  99599. get: function () {
  99600. return this._ground;
  99601. },
  99602. enumerable: true,
  99603. configurable: true
  99604. });
  99605. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  99606. /**
  99607. * Gets the ground texture created by the helper.
  99608. */
  99609. get: function () {
  99610. return this._groundTexture;
  99611. },
  99612. enumerable: true,
  99613. configurable: true
  99614. });
  99615. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  99616. /**
  99617. * Gets the ground mirror created by the helper.
  99618. */
  99619. get: function () {
  99620. return this._groundMirror;
  99621. },
  99622. enumerable: true,
  99623. configurable: true
  99624. });
  99625. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  99626. /**
  99627. * Gets the ground mirror render list to helps pushing the meshes
  99628. * you wish in the ground reflection.
  99629. */
  99630. get: function () {
  99631. if (this._groundMirror) {
  99632. return this._groundMirror.renderList;
  99633. }
  99634. return null;
  99635. },
  99636. enumerable: true,
  99637. configurable: true
  99638. });
  99639. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  99640. /**
  99641. * Gets the ground material created by the helper.
  99642. */
  99643. get: function () {
  99644. return this._groundMaterial;
  99645. },
  99646. enumerable: true,
  99647. configurable: true
  99648. });
  99649. /**
  99650. * Updates the background according to the new options
  99651. * @param options
  99652. */
  99653. EnvironmentHelper.prototype.updateOptions = function (options) {
  99654. var newOptions = __assign({}, this._options, options);
  99655. if (this._ground && !newOptions.createGround) {
  99656. this._ground.dispose();
  99657. this._ground = null;
  99658. }
  99659. if (this._groundMaterial && !newOptions.createGround) {
  99660. this._groundMaterial.dispose();
  99661. this._groundMaterial = null;
  99662. }
  99663. if (this._groundTexture) {
  99664. if (this._options.groundTexture != newOptions.groundTexture) {
  99665. this._groundTexture.dispose();
  99666. this._groundTexture = null;
  99667. }
  99668. }
  99669. if (this._skybox && !newOptions.createSkybox) {
  99670. this._skybox.dispose();
  99671. this._skybox = null;
  99672. }
  99673. if (this._skyboxMaterial && !newOptions.createSkybox) {
  99674. this._skyboxMaterial.dispose();
  99675. this._skyboxMaterial = null;
  99676. }
  99677. if (this._skyboxTexture) {
  99678. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  99679. this._skyboxTexture.dispose();
  99680. this._skyboxTexture = null;
  99681. }
  99682. }
  99683. if (this._groundMirror && !newOptions.enableGroundMirror) {
  99684. this._groundMirror.dispose();
  99685. this._groundMirror = null;
  99686. }
  99687. if (this._scene.environmentTexture) {
  99688. if (this._options.environmentTexture != newOptions.environmentTexture) {
  99689. this._scene.environmentTexture.dispose();
  99690. }
  99691. }
  99692. this._options = newOptions;
  99693. this._setupBackground();
  99694. this._setupImageProcessing();
  99695. };
  99696. /**
  99697. * Sets the primary color of all the available elements.
  99698. * @param color the main color to affect to the ground and the background
  99699. */
  99700. EnvironmentHelper.prototype.setMainColor = function (color) {
  99701. if (this.groundMaterial) {
  99702. this.groundMaterial.primaryColor = color;
  99703. }
  99704. if (this.skyboxMaterial) {
  99705. this.skyboxMaterial.primaryColor = color;
  99706. }
  99707. if (this.groundMirror) {
  99708. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  99709. }
  99710. };
  99711. /**
  99712. * Setup the image processing according to the specified options.
  99713. */
  99714. EnvironmentHelper.prototype._setupImageProcessing = function () {
  99715. if (this._options.setupImageProcessing) {
  99716. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  99717. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  99718. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  99719. this._setupEnvironmentTexture();
  99720. }
  99721. };
  99722. /**
  99723. * Setup the environment texture according to the specified options.
  99724. */
  99725. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  99726. if (this._scene.environmentTexture) {
  99727. return;
  99728. }
  99729. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  99730. this._scene.environmentTexture = this._options.environmentTexture;
  99731. return;
  99732. }
  99733. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  99734. this._scene.environmentTexture = environmentTexture;
  99735. };
  99736. /**
  99737. * Setup the background according to the specified options.
  99738. */
  99739. EnvironmentHelper.prototype._setupBackground = function () {
  99740. if (!this._rootMesh) {
  99741. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  99742. }
  99743. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  99744. var sceneSize = this._getSceneSize();
  99745. if (this._options.createGround) {
  99746. this._setupGround(sceneSize);
  99747. this._setupGroundMaterial();
  99748. this._setupGroundDiffuseTexture();
  99749. if (this._options.enableGroundMirror) {
  99750. this._setupGroundMirrorTexture(sceneSize);
  99751. }
  99752. this._setupMirrorInGroundMaterial();
  99753. }
  99754. if (this._options.createSkybox) {
  99755. this._setupSkybox(sceneSize);
  99756. this._setupSkyboxMaterial();
  99757. this._setupSkyboxReflectionTexture();
  99758. }
  99759. this._rootMesh.position.x = sceneSize.rootPosition.x;
  99760. this._rootMesh.position.z = sceneSize.rootPosition.z;
  99761. this._rootMesh.position.y = sceneSize.rootPosition.y;
  99762. };
  99763. /**
  99764. * Get the scene sizes according to the setup.
  99765. */
  99766. EnvironmentHelper.prototype._getSceneSize = function () {
  99767. var _this = this;
  99768. var groundSize = this._options.groundSize;
  99769. var skyboxSize = this._options.skyboxSize;
  99770. var rootPosition = this._options.rootPosition;
  99771. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  99772. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  99773. }
  99774. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  99775. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  99776. });
  99777. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  99778. if (this._options.sizeAuto) {
  99779. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  99780. this._scene.activeCamera.upperRadiusLimit) {
  99781. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  99782. skyboxSize = groundSize;
  99783. }
  99784. var sceneDiagonalLenght = sceneDiagonal.length();
  99785. if (sceneDiagonalLenght > groundSize) {
  99786. groundSize = sceneDiagonalLenght * 2;
  99787. skyboxSize = groundSize;
  99788. }
  99789. // 10 % bigger.
  99790. groundSize *= 1.1;
  99791. skyboxSize *= 1.5;
  99792. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  99793. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  99794. }
  99795. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  99796. };
  99797. /**
  99798. * Setup the ground according to the specified options.
  99799. */
  99800. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  99801. var _this = this;
  99802. if (!this._ground) {
  99803. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  99804. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  99805. this._ground.parent = this._rootMesh;
  99806. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  99807. }
  99808. this._ground.receiveShadows = this._options.enableGroundShadow;
  99809. };
  99810. /**
  99811. * Setup the ground material according to the specified options.
  99812. */
  99813. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  99814. if (!this._groundMaterial) {
  99815. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  99816. }
  99817. this._groundMaterial.alpha = this._options.groundOpacity;
  99818. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  99819. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  99820. this._groundMaterial.primaryColor = this._options.groundColor;
  99821. this._groundMaterial.useRGBColor = false;
  99822. this._groundMaterial.enableNoise = true;
  99823. if (this._ground) {
  99824. this._ground.material = this._groundMaterial;
  99825. }
  99826. };
  99827. /**
  99828. * Setup the ground diffuse texture according to the specified options.
  99829. */
  99830. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  99831. if (!this._groundMaterial) {
  99832. return;
  99833. }
  99834. if (this._groundTexture) {
  99835. return;
  99836. }
  99837. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  99838. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  99839. return;
  99840. }
  99841. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  99842. diffuseTexture.gammaSpace = false;
  99843. diffuseTexture.hasAlpha = true;
  99844. this._groundMaterial.diffuseTexture = diffuseTexture;
  99845. };
  99846. /**
  99847. * Setup the ground mirror texture according to the specified options.
  99848. */
  99849. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  99850. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99851. if (!this._groundMirror) {
  99852. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  99853. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  99854. this._groundMirror.anisotropicFilteringLevel = 1;
  99855. this._groundMirror.wrapU = wrapping;
  99856. this._groundMirror.wrapV = wrapping;
  99857. this._groundMirror.gammaSpace = false;
  99858. if (this._groundMirror.renderList) {
  99859. for (var i = 0; i < this._scene.meshes.length; i++) {
  99860. var mesh = this._scene.meshes[i];
  99861. if (mesh !== this._ground &&
  99862. mesh !== this._skybox &&
  99863. mesh !== this._rootMesh) {
  99864. this._groundMirror.renderList.push(mesh);
  99865. }
  99866. }
  99867. }
  99868. }
  99869. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  99870. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  99871. };
  99872. /**
  99873. * Setup the ground to receive the mirror texture.
  99874. */
  99875. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  99876. if (this._groundMaterial) {
  99877. this._groundMaterial.reflectionTexture = this._groundMirror;
  99878. this._groundMaterial.reflectionFresnel = true;
  99879. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  99880. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  99881. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  99882. }
  99883. };
  99884. /**
  99885. * Setup the skybox according to the specified options.
  99886. */
  99887. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  99888. var _this = this;
  99889. if (!this._skybox) {
  99890. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  99891. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  99892. }
  99893. this._skybox.parent = this._rootMesh;
  99894. };
  99895. /**
  99896. * Setup the skybox material according to the specified options.
  99897. */
  99898. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  99899. if (!this._skybox) {
  99900. return;
  99901. }
  99902. if (!this._skyboxMaterial) {
  99903. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  99904. }
  99905. this._skyboxMaterial.useRGBColor = false;
  99906. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  99907. this._skyboxMaterial.enableNoise = true;
  99908. this._skybox.material = this._skyboxMaterial;
  99909. };
  99910. /**
  99911. * Setup the skybox reflection texture according to the specified options.
  99912. */
  99913. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  99914. if (!this._skyboxMaterial) {
  99915. return;
  99916. }
  99917. if (this._skyboxTexture) {
  99918. return;
  99919. }
  99920. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  99921. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  99922. return;
  99923. }
  99924. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  99925. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  99926. this._skyboxTexture.gammaSpace = false;
  99927. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  99928. };
  99929. /**
  99930. * Dispose all the elements created by the Helper.
  99931. */
  99932. EnvironmentHelper.prototype.dispose = function () {
  99933. if (this._groundMaterial) {
  99934. this._groundMaterial.dispose(true, true);
  99935. }
  99936. if (this._skyboxMaterial) {
  99937. this._skyboxMaterial.dispose(true, true);
  99938. }
  99939. this._rootMesh.dispose(false);
  99940. };
  99941. /**
  99942. * Default ground texture URL.
  99943. */
  99944. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  99945. /**
  99946. * Default skybox texture URL.
  99947. */
  99948. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  99949. /**
  99950. * Default environment texture URL.
  99951. */
  99952. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  99953. return EnvironmentHelper;
  99954. }());
  99955. BABYLON.EnvironmentHelper = EnvironmentHelper;
  99956. })(BABYLON || (BABYLON = {}));
  99957. //# sourceMappingURL=babylon.environmentHelper.js.map
  99958. var BABYLON;
  99959. (function (BABYLON) {
  99960. /**
  99961. * This class is made for on one-liner static method to help creating particle systems.
  99962. */
  99963. var ParticleHelper = /** @class */ (function () {
  99964. function ParticleHelper() {
  99965. }
  99966. /**
  99967. * This is the main static method (one-liner) of this helper to create different particle systems.
  99968. * @param type This string represents the type to the particle system to create
  99969. * @param emitter The object where the particle system will start to emit from.
  99970. * @param scene The scene where the particle system should live.
  99971. * @param gpu If the system will use gpu.
  99972. * @returns the ParticleSystem created.
  99973. */
  99974. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  99975. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  99976. if (gpu === void 0) { gpu = false; }
  99977. return new Promise(function (resolve, reject) {
  99978. if (!scene) {
  99979. scene = BABYLON.Engine.LastCreatedScene;
  99980. ;
  99981. }
  99982. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  99983. return reject("Particle system with GPU is not supported.");
  99984. }
  99985. BABYLON.Tools.LoadFile(ParticleHelper._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  99986. var newData = JSON.parse(data.toString());
  99987. return resolve(ParticleHelper.CreateSystem(newData, scene, emitter));
  99988. }, undefined, undefined, undefined, function (req, exception) {
  99989. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  99990. });
  99991. });
  99992. };
  99993. /**
  99994. * Static function used to create a new particle system from a IParticleSystemData
  99995. * @param data defines the source data
  99996. * @param scene defines the hosting scene
  99997. * @param emitter defines the particle emitter
  99998. * @returns a new ParticleSystem based on referenced data
  99999. */
  100000. ParticleHelper.CreateSystem = function (data, scene, emitter) {
  100001. // Create a particle system
  100002. var system = new BABYLON.ParticleSystem(data.type, data.capacity, scene);
  100003. // Where the particles come from
  100004. system.emitter = emitter; // the starting object, the emitter
  100005. ParticleHelper.UpdateSystem(system, data, scene);
  100006. return system;
  100007. };
  100008. /**
  100009. * Static function used to update a particle system from a IParticleSystemData
  100010. * @param system defines the particle system to update
  100011. * @param data defines the source data
  100012. * @param scene defines the hosting scene
  100013. */
  100014. ParticleHelper.UpdateSystem = function (system, data, scene) {
  100015. // Texture of each particle
  100016. if (data.textureFile) {
  100017. system.particleTexture = new BABYLON.Texture(ParticleHelper._baseAssetsUrl + "/textures/" + data.textureFile, scene);
  100018. }
  100019. // Colors of all particles
  100020. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  100021. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  100022. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  100023. // Size of each particle (random between...
  100024. system.minSize = data.minSize;
  100025. system.maxSize = data.maxSize;
  100026. system.minScaleX = data.minScaleX;
  100027. system.maxScaleX = data.maxScaleX;
  100028. system.minScaleY = data.minScaleY;
  100029. system.maxScaleY = data.maxScaleY;
  100030. // Life time of each particle (random between...
  100031. system.minLifeTime = data.minLifeTime;
  100032. system.maxLifeTime = data.maxLifeTime;
  100033. // Emission rate
  100034. system.emitRate = data.emitRate;
  100035. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  100036. system.blendMode = data.blendMode;
  100037. // Set the gravity of all particles
  100038. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  100039. // Angular speed, in radians
  100040. system.minAngularSpeed = data.minAngularSpeed;
  100041. system.maxAngularSpeed = data.maxAngularSpeed;
  100042. // Speed
  100043. system.minEmitPower = data.minEmitPower;
  100044. system.maxEmitPower = data.maxEmitPower;
  100045. system.updateSpeed = data.updateSpeed;
  100046. switch (data.emitterType) {
  100047. case "box":
  100048. if (!data.direction1 || !data.direction2) {
  100049. throw new Error("Directions are missing in this particle system.");
  100050. }
  100051. if (!data.minEmitBox || !data.maxEmitBox) {
  100052. throw new Error("EmitBox is missing in this particle system.");
  100053. }
  100054. system.createBoxEmitter(new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z), new BABYLON.Vector3(data.minEmitBox.x, data.minEmitBox.y, data.minEmitBox.z), new BABYLON.Vector3(data.maxEmitBox.x, data.maxEmitBox.y, data.maxEmitBox.z));
  100055. break;
  100056. case "sphere":
  100057. system.createSphereEmitter(data.radius);
  100058. break;
  100059. case "directed_sphere":
  100060. if (!data.direction1 || !data.direction2) {
  100061. throw new Error("Directions are missing in this particle system.");
  100062. }
  100063. system.createDirectedSphereEmitter(data.radius, new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z));
  100064. break;
  100065. case "cone":
  100066. system.createConeEmitter(data.radius, data.angle);
  100067. break;
  100068. default:
  100069. break;
  100070. }
  100071. };
  100072. /**
  100073. * Static function used to export a particle system to a IParticleSystemData variable.
  100074. * Please note that texture file name is not exported and must be added manually
  100075. * @param system defines the particle system to export
  100076. */
  100077. ParticleHelper.ExportSystem = function (system) {
  100078. var outData = {};
  100079. // Colors of all particles
  100080. outData.color1 = { r: system.color1.r, g: system.color1.g, b: system.color1.b, a: system.color1.a };
  100081. outData.color2 = { r: system.color2.r, g: system.color2.g, b: system.color2.b, a: system.color2.a };
  100082. outData.colorDead = { r: system.colorDead.r, g: system.colorDead.g, b: system.colorDead.b, a: system.colorDead.a };
  100083. // Size of each particle (random between...
  100084. outData.minSize = system.minSize;
  100085. outData.maxSize = system.maxSize;
  100086. outData.minScaleX = system.minScaleX;
  100087. outData.maxScaleX = system.maxScaleX;
  100088. outData.minScaleY = system.minScaleY;
  100089. outData.maxScaleY = system.maxScaleY;
  100090. // Life time of each particle (random between...
  100091. outData.minLifeTime = system.minLifeTime;
  100092. outData.maxLifeTime = system.maxLifeTime;
  100093. // Emission rate
  100094. outData.emitRate = system.emitRate;
  100095. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  100096. outData.blendMode = system.blendMode;
  100097. // Set the gravity of all particles
  100098. outData.gravity = { x: system.gravity.x, y: system.gravity.y, z: system.gravity.z };
  100099. // Angular speed, in radians
  100100. outData.minAngularSpeed = system.minAngularSpeed;
  100101. outData.maxAngularSpeed = system.maxAngularSpeed;
  100102. // Speed
  100103. outData.minEmitPower = system.minEmitPower;
  100104. outData.maxEmitPower = system.maxEmitPower;
  100105. outData.updateSpeed = system.updateSpeed;
  100106. switch (system.particleEmitterType.getClassName()) {
  100107. case "BoxEmitter":
  100108. outData.emitterType = "box";
  100109. outData.direction1 = { x: system.direction1.x, y: system.direction1.y, z: system.direction1.z };
  100110. outData.direction2 = { x: system.direction2.x, y: system.direction2.y, z: system.direction2.z };
  100111. outData.minEmitBox = { x: system.minEmitBox.x, y: system.minEmitBox.y, z: system.minEmitBox.z };
  100112. outData.maxEmitBox = { x: system.maxEmitBox.x, y: system.maxEmitBox.y, z: system.maxEmitBox.z };
  100113. break;
  100114. case "SphereParticleEmitter":
  100115. outData.emitterType = "sphere";
  100116. outData.radius = system.particleEmitterType.radius;
  100117. break;
  100118. case "SphereDirectedParticleEmitter":
  100119. outData.emitterType = "directed_sphere";
  100120. var sphereDirectedParticleEmitter = system.particleEmitterType;
  100121. outData.radius = sphereDirectedParticleEmitter.radius;
  100122. outData.direction1 = { x: sphereDirectedParticleEmitter.direction1.x, y: sphereDirectedParticleEmitter.direction1.y, z: sphereDirectedParticleEmitter.direction1.z };
  100123. outData.direction2 = { x: sphereDirectedParticleEmitter.direction2.x, y: sphereDirectedParticleEmitter.direction2.y, z: sphereDirectedParticleEmitter.direction2.z };
  100124. break;
  100125. case "ConeEmitter":
  100126. outData.emitterType = "cone";
  100127. outData.radius = system.particleEmitterType.radius;
  100128. outData.angle = system.particleEmitterType.angle;
  100129. break;
  100130. default:
  100131. break;
  100132. }
  100133. return outData;
  100134. };
  100135. /**
  100136. * Base Assets URL.
  100137. */
  100138. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  100139. return ParticleHelper;
  100140. }());
  100141. BABYLON.ParticleHelper = ParticleHelper;
  100142. })(BABYLON || (BABYLON = {}));
  100143. //# sourceMappingURL=babylon.particleHelper.js.map
  100144. var BABYLON;
  100145. (function (BABYLON) {
  100146. /**
  100147. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  100148. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  100149. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  100150. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  100151. */
  100152. var VideoDome = /** @class */ (function (_super) {
  100153. __extends(VideoDome, _super);
  100154. /**
  100155. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  100156. * @param name Element's name, child elements will append suffixes for their own names.
  100157. * @param urlsOrVideo defines the url(s) or the video element to use
  100158. * @param options An object containing optional or exposed sub element properties
  100159. */
  100160. function VideoDome(name, urlsOrVideo, options, scene) {
  100161. var _this = _super.call(this, name, scene) || this;
  100162. // set defaults and manage values
  100163. name = name || "videoDome";
  100164. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  100165. options.clickToPlay = Boolean(options.clickToPlay);
  100166. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  100167. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  100168. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  100169. // create
  100170. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  100171. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  100172. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  100173. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  100174. flat: false,
  100175. radius: options.size,
  100176. subdivisions: options.resolution,
  100177. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  100178. }, scene);
  100179. // configure material
  100180. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  100181. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  100182. material.reflectionTexture = _this._videoTexture;
  100183. material.useEquirectangularFOV = true;
  100184. material.fovMultiplier = 1.0;
  100185. // configure mesh
  100186. _this._mesh.material = material;
  100187. _this._mesh.parent = _this;
  100188. // optional configuration
  100189. if (options.clickToPlay) {
  100190. scene.onPointerUp = function () {
  100191. _this._videoTexture.video.play();
  100192. };
  100193. }
  100194. return _this;
  100195. }
  100196. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  100197. /**
  100198. * Gets the video texture being displayed on the sphere
  100199. */
  100200. get: function () {
  100201. return this._videoTexture;
  100202. },
  100203. enumerable: true,
  100204. configurable: true
  100205. });
  100206. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  100207. /**
  100208. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100209. * Also see the options.resolution property.
  100210. */
  100211. get: function () {
  100212. return this._material.fovMultiplier;
  100213. },
  100214. set: function (value) {
  100215. this._material.fovMultiplier = value;
  100216. },
  100217. enumerable: true,
  100218. configurable: true
  100219. });
  100220. /**
  100221. * Releases resources associated with this node.
  100222. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  100223. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  100224. */
  100225. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  100226. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  100227. this._videoTexture.dispose();
  100228. this._mesh.dispose();
  100229. this._material.dispose();
  100230. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  100231. };
  100232. return VideoDome;
  100233. }(BABYLON.Node));
  100234. BABYLON.VideoDome = VideoDome;
  100235. })(BABYLON || (BABYLON = {}));
  100236. //# sourceMappingURL=babylon.videoDome.js.map
  100237. var BABYLON;
  100238. (function (BABYLON) {
  100239. /**
  100240. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  100241. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  100242. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  100243. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  100244. */
  100245. var PhotoDome = /** @class */ (function (_super) {
  100246. __extends(PhotoDome, _super);
  100247. /**
  100248. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  100249. * @param name Element's name, child elements will append suffixes for their own names.
  100250. * @param urlsOfPhoto define the url of the photo to display
  100251. * @param options An object containing optional or exposed sub element properties
  100252. */
  100253. function PhotoDome(name, urlOfPhoto, options, scene) {
  100254. var _this = _super.call(this, name, scene) || this;
  100255. // set defaults and manage values
  100256. name = name || "photoDome";
  100257. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  100258. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  100259. // create
  100260. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  100261. var texture = _this._photoTexture = new BABYLON.Texture(urlOfPhoto, scene);
  100262. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  100263. flat: false,
  100264. radius: options.size,
  100265. subdivisions: options.resolution,
  100266. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  100267. }, scene);
  100268. // configure material
  100269. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  100270. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  100271. material.reflectionTexture = _this._photoTexture;
  100272. material.useEquirectangularFOV = true;
  100273. material.fovMultiplier = 1.0;
  100274. // configure mesh
  100275. _this._mesh.material = material;
  100276. _this._mesh.parent = _this;
  100277. return _this;
  100278. }
  100279. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  100280. /**
  100281. * Gets the texture being displayed on the sphere
  100282. */
  100283. get: function () {
  100284. return this._photoTexture;
  100285. },
  100286. enumerable: true,
  100287. configurable: true
  100288. });
  100289. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  100290. /**
  100291. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100292. * Also see the options.resolution property.
  100293. */
  100294. get: function () {
  100295. return this._material.fovMultiplier;
  100296. },
  100297. set: function (value) {
  100298. this._material.fovMultiplier = value;
  100299. },
  100300. enumerable: true,
  100301. configurable: true
  100302. });
  100303. /**
  100304. * Releases resources associated with this node.
  100305. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  100306. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  100307. */
  100308. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  100309. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  100310. this._photoTexture.dispose();
  100311. this._mesh.dispose();
  100312. this._material.dispose();
  100313. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  100314. };
  100315. return PhotoDome;
  100316. }(BABYLON.Node));
  100317. BABYLON.PhotoDome = PhotoDome;
  100318. })(BABYLON || (BABYLON = {}));
  100319. //# sourceMappingURL=babylon.photoDome.js.map
  100320. 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\nvec4 environmentRefraction=vec4(0.,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);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,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);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=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.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=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.rgb*=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.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\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}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\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 vec3 options;\nattribute vec2 size;\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; \nvec2 cornerPos;\nfloat angle=options.x;\nvec2 offset=options.yz;\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); \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 vec3 size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nin vec2 angle;\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);\nvec2 cornerPos=offset*size.yz*size.x;\n\nvec4 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.z=0.;\nrotatedCorner.w=0.;\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+rotatedCorner);\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 scaleRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform vec2 angleRange;\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 coneAngle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin vec3 size;\nin vec4 color;\nin vec3 direction;\nin vec2 angle;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout vec3 outSize;\nout vec4 outColor;\nout vec3 outDirection;\nout vec2 outAngle;\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=vec3(0.,0.,0.);\noutDirection=direction;\noutAngle=angle;\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.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a;\n\noutColor=color1+(color2-color1)*randoms.b;\n\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=0.;\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 (coneAngle == 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;\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,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);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=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.rgb*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.rgb,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"};
  100321. 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}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\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};"};
  100322. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  100323. globalObject["BABYLON"] = BABYLON;
  100324. //backwards compatibility
  100325. if(typeof earcut !== 'undefined') {
  100326. globalObject["Earcut"] = {
  100327. earcut: earcut
  100328. };
  100329. }
  100330. return BABYLON;
  100331. });
  100332. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(17)))
  100333. /***/ }),
  100334. /* 1 */
  100335. /***/ (function(module, exports, __webpack_require__) {
  100336. "use strict";
  100337. Object.defineProperty(exports, "__esModule", { value: true });
  100338. var deepmerge = __webpack_require__(21);
  100339. var expDm = deepmerge['default'];
  100340. exports.deepmerge = expDm;
  100341. /**
  100342. * Is the provided string a URL?
  100343. *
  100344. * @param urlToCheck the url to inspect
  100345. */
  100346. function isUrl(urlToCheck) {
  100347. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  100348. return true;
  100349. }
  100350. return false;
  100351. }
  100352. exports.isUrl = isUrl;
  100353. /**
  100354. * Convert a string from kebab-case to camelCase
  100355. * @param s string to convert
  100356. */
  100357. function kebabToCamel(s) {
  100358. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  100359. }
  100360. exports.kebabToCamel = kebabToCamel;
  100361. //https://gist.github.com/youssman/745578062609e8acac9f
  100362. /**
  100363. * Convert a string from camelCase to kebab-case
  100364. * @param str string to convert
  100365. */
  100366. function camelToKebab(str) {
  100367. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  100368. }
  100369. exports.camelToKebab = camelToKebab;
  100370. /**
  100371. * This will extend an object with configuration values.
  100372. * What it practically does it take the keys from the configuration and set them on the object.
  100373. * I the configuration is a tree, it will traverse into the tree.
  100374. * @param object the object to extend
  100375. * @param config the configuration object that will extend the object
  100376. */
  100377. function extendClassWithConfig(object, config) {
  100378. if (!config)
  100379. return;
  100380. Object.keys(config).forEach(function (key) {
  100381. if (key in object && typeof object[key] !== 'function') {
  100382. // if (typeof object[key] === 'function') return;
  100383. // if it is an object, iterate internally until reaching basic types
  100384. if (typeof object[key] === 'object') {
  100385. extendClassWithConfig(object[key], config[key]);
  100386. }
  100387. else {
  100388. if (config[key] !== undefined) {
  100389. object[key] = config[key];
  100390. }
  100391. }
  100392. }
  100393. });
  100394. }
  100395. exports.extendClassWithConfig = extendClassWithConfig;
  100396. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvaGVscGVyL2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEscUNBQXVDO0FBRXZDLElBQUksS0FBSyxHQUFHLFNBQVMsQ0FBQyxTQUFTLENBQUMsQ0FBQztBQUNmLDBCQUFTO0FBRTNCOzs7O0dBSUc7QUFDSCxlQUFzQixVQUFrQjtJQUNwQyxJQUFJLFVBQVUsQ0FBQyxPQUFPLENBQUMsTUFBTSxDQUFDLEtBQUssQ0FBQyxJQUFJLFVBQVUsQ0FBQyxPQUFPLENBQUMsR0FBRyxDQUFDLEtBQUssQ0FBQyxJQUFJLFVBQVUsQ0FBQyxPQUFPLENBQUMsSUFBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLFVBQVUsQ0FBQyxPQUFPLENBQUMsS0FBSyxDQUFDLEtBQUssQ0FBQyxFQUFFO1FBQ3hJLE9BQU8sSUFBSSxDQUFDO0tBQ2Y7SUFDRCxPQUFPLEtBQUssQ0FBQztBQUNqQixDQUFDO0FBTEQsc0JBS0M7QUFFRDs7O0dBR0c7QUFDSCxzQkFBNkIsQ0FBQztJQUMxQixPQUFPLENBQUMsQ0FBQyxPQUFPLENBQUMsU0FBUyxFQUFFLFVBQVUsQ0FBQyxJQUFJLE9BQU8sQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLFdBQVcsRUFBRSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7QUFDN0UsQ0FBQztBQUZELG9DQUVDO0FBRUQsdURBQXVEO0FBQ3ZEOzs7R0FHRztBQUNILHNCQUE2QixHQUFHO0lBQzVCLE9BQU8sQ0FBQyxHQUFHLENBQUMsQ0FBQyxDQUFDLElBQUksQ0FBQyxDQUFDLENBQUMsR0FBRyxDQUFDLE9BQU8sQ0FBQyxVQUFVLEVBQUUsVUFBVSxDQUFDLElBQUksT0FBTyxHQUFHLEdBQUcsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLFdBQVcsRUFBRSxDQUFBLENBQUMsQ0FBQyxDQUFDLENBQUM7QUFDbkcsQ0FBQztBQUZELG9DQUVDO0FBRUQ7Ozs7OztHQU1HO0FBQ0gsK0JBQXNDLE1BQVcsRUFBRSxNQUFXO0lBQzFELElBQUksQ0FBQyxNQUFNO1FBQUUsT0FBTztJQUNwQixNQUFNLENBQUMsSUFBSSxDQUFDLE1BQU0sQ0FBQyxDQUFDLE9BQU8sQ0FBQyxVQUFBLEdBQUc7UUFDM0IsSUFBSSxHQUFHLElBQUksTUFBTSxJQUFJLE9BQU8sTUFBTSxDQUFDLEdBQUcsQ0FBQyxLQUFLLFVBQVUsRUFBRTtZQUNwRCxpREFBaUQ7WUFDakQsb0VBQW9FO1lBQ3BFLElBQUksT0FBTyxNQUFNLENBQUMsR0FBRyxDQUFDLEtBQUssUUFBUSxFQUFFO2dCQUNqQyxxQkFBcUIsQ0FBQyxNQUFNLENBQUMsR0FBRyxDQUFDLEVBQUUsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUM7YUFDbkQ7aUJBQU07Z0JBQ0gsSUFBSSxNQUFNLENBQUMsR0FBRyxDQUFDLEtBQUssU0FBUyxFQUFFO29CQUMzQixNQUFNLENBQUMsR0FBRyxDQUFDLEdBQUcsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDO2lCQUM3QjthQUNKO1NBQ0o7SUFDTCxDQUFDLENBQUMsQ0FBQztBQUNQLENBQUM7QUFmRCxzREFlQyJ9
  100397. /***/ }),
  100398. /* 2 */
  100399. /***/ (function(module, exports, __webpack_require__) {
  100400. "use strict";
  100401. function __export(m) {
  100402. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  100403. }
  100404. Object.defineProperty(exports, "__esModule", { value: true });
  100405. __export(__webpack_require__(31));
  100406. __export(__webpack_require__(33));
  100407. __export(__webpack_require__(39));
  100408. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvYXNzZXRzL2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7O0FBQUEsNEJBQXVCO0FBQ3ZCLDJCQUFzQjtBQUN0QixpQ0FBNEIifQ==
  100409. /***/ }),
  100410. /* 3 */
  100411. /***/ (function(module, exports, __webpack_require__) {
  100412. "use strict";
  100413. Object.defineProperty(exports, "__esModule", { value: true });
  100414. var babylonjs_1 = __webpack_require__(0);
  100415. var _1 = __webpack_require__(1);
  100416. /**
  100417. * This is a simple HTML mapper.
  100418. * This mapper parses a single HTML element and returns the configuration from its attributes.
  100419. * it parses numbers and boolean values to the corresponding variable types.
  100420. * The following HTML element:
  100421. * <div test="1" random-flag="true" a.string.object="test"> will result in the following configuration:
  100422. *
  100423. * {
  100424. * test: 1, //a number!
  100425. * randomFlag: boolean, //camelCase and boolean
  100426. * a: {
  100427. * string: {
  100428. * object: "test" //dot-separated object levels
  100429. * }
  100430. * }
  100431. * }
  100432. */
  100433. var HTMLMapper = /** @class */ (function () {
  100434. function HTMLMapper() {
  100435. }
  100436. /**
  100437. * Map a specific element and get configuration from it
  100438. * @param element the HTML element to analyze.
  100439. */
  100440. HTMLMapper.prototype.map = function (element) {
  100441. var config = {};
  100442. var _loop_1 = function (attrIdx) {
  100443. var attr = element.attributes.item(attrIdx);
  100444. if (!attr) {
  100445. return "continue";
  100446. }
  100447. // map "object.property" to the right configuration place.
  100448. var split = attr.nodeName.split('.');
  100449. split.reduce(function (currentConfig, key, idx) {
  100450. //convert html-style to json-style
  100451. var camelKey = _1.kebabToCamel(key);
  100452. if (idx === split.length - 1) {
  100453. var val = attr.nodeValue; // firefox warns nodeValue is deprecated, but I found no sign of it anywhere.
  100454. if (val === "true") {
  100455. val = true;
  100456. }
  100457. else if (val === "false") {
  100458. val = false;
  100459. }
  100460. else {
  100461. var isnum = !isNaN(parseFloat(val)) && isFinite(val); ///^\d+$/.test(val);
  100462. if (isnum) {
  100463. var number = parseFloat(val);
  100464. if (!isNaN(number)) {
  100465. val = number;
  100466. }
  100467. }
  100468. }
  100469. currentConfig[camelKey] = val;
  100470. }
  100471. else {
  100472. currentConfig[camelKey] = currentConfig[camelKey] || {};
  100473. }
  100474. return currentConfig[camelKey];
  100475. }, config);
  100476. };
  100477. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  100478. _loop_1(attrIdx);
  100479. }
  100480. return config;
  100481. };
  100482. return HTMLMapper;
  100483. }());
  100484. /**
  100485. * A simple string-to-JSON mapper.
  100486. * This is the main mapper, used to analyze downloaded JSON-Configuration or JSON payload
  100487. */
  100488. var JSONMapper = /** @class */ (function () {
  100489. function JSONMapper() {
  100490. }
  100491. JSONMapper.prototype.map = function (rawSource) {
  100492. return JSON.parse(rawSource);
  100493. };
  100494. return JSONMapper;
  100495. }());
  100496. /**
  100497. * The DOM Mapper will traverse an entire DOM Tree and will load the configuration from the
  100498. * DOM elements and attributes.
  100499. */
  100500. var DOMMapper = /** @class */ (function () {
  100501. function DOMMapper() {
  100502. }
  100503. /**
  100504. * The mapping function that will convert HTML data to a viewer configuration object
  100505. * @param baseElement the baseElement from which to start traversing
  100506. * @returns a ViewerCOnfiguration object from the provided HTML Element
  100507. */
  100508. DOMMapper.prototype.map = function (baseElement) {
  100509. var htmlMapper = new HTMLMapper();
  100510. var config = htmlMapper.map(baseElement);
  100511. var traverseChildren = function (element, partConfig) {
  100512. var children = element.children;
  100513. if (children.length) {
  100514. for (var i = 0; i < children.length; ++i) {
  100515. var item = children.item(i);
  100516. // use the HTML Mapper to read configuration from a single element
  100517. var configMapped = htmlMapper.map(item);
  100518. var key = _1.kebabToCamel(item.nodeName.toLowerCase());
  100519. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  100520. partConfig[key] = [];
  100521. }
  100522. else {
  100523. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  100524. partConfig.push(configMapped);
  100525. }
  100526. else if (partConfig[key]) {
  100527. //exists already! probably an array
  100528. element.setAttribute('array', 'true');
  100529. var oldItem = partConfig[key];
  100530. partConfig = [oldItem, configMapped];
  100531. }
  100532. else {
  100533. partConfig[key] = configMapped;
  100534. }
  100535. }
  100536. traverseChildren(item, partConfig[key] || configMapped);
  100537. }
  100538. }
  100539. return partConfig;
  100540. };
  100541. traverseChildren(baseElement, config);
  100542. return config;
  100543. };
  100544. return DOMMapper;
  100545. }());
  100546. /**
  100547. * The MapperManager manages the different implemented mappers.
  100548. * It allows the user to register new mappers as well and use them to parse their own configuration data
  100549. */
  100550. var MapperManager = /** @class */ (function () {
  100551. function MapperManager() {
  100552. this._mappers = {
  100553. "html": new HTMLMapper(),
  100554. "json": new JSONMapper(),
  100555. "dom": new DOMMapper()
  100556. };
  100557. }
  100558. /**
  100559. * Get a specific configuration mapper.
  100560. *
  100561. * @param type the name of the mapper to load
  100562. */
  100563. MapperManager.prototype.getMapper = function (type) {
  100564. if (!this._mappers[type]) {
  100565. babylonjs_1.Tools.Error("No mapper defined for " + type);
  100566. }
  100567. return this._mappers[type];
  100568. };
  100569. /**
  100570. * Use this functio to register your own configuration mapper.
  100571. * After a mapper is registered, it can be used to parse the specific type fo configuration to the standard ViewerConfiguration.
  100572. * @param type the name of the mapper. This will be used to define the configuration type and/or to get the mapper
  100573. * @param mapper The implemented mapper
  100574. */
  100575. MapperManager.prototype.registerMapper = function (type, mapper) {
  100576. this._mappers[type] = mapper;
  100577. };
  100578. /**
  100579. * Dispose the mapper manager and all of its mappers.
  100580. */
  100581. MapperManager.prototype.dispose = function () {
  100582. this._mappers = {};
  100583. };
  100584. /**
  100585. * The default mapper is the JSON mapper.
  100586. */
  100587. MapperManager.DefaultMapper = 'json';
  100588. return MapperManager;
  100589. }());
  100590. exports.MapperManager = MapperManager;
  100591. /**
  100592. * mapperManager is a singleton of the type MapperManager.
  100593. * The mapperManager can be disposed directly with calling mapperManager.dispose()
  100594. * or indirectly with using BabylonViewer.disposeAll()
  100595. */
  100596. exports.mapperManager = new MapperManager();
  100597. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWFwcGVycy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL21hcHBlcnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBa0M7QUFHbEMsK0JBQTBDO0FBUzFDOzs7Ozs7Ozs7Ozs7Ozs7O0dBZ0JHO0FBQ0g7SUFBQTtJQTRDQSxDQUFDO0lBMUNHOzs7T0FHRztJQUNILHdCQUFHLEdBQUgsVUFBSSxPQUFvQjtRQUVwQixJQUFJLE1BQU0sR0FBRyxFQUFFLENBQUM7Z0NBQ1AsT0FBTztZQUNaLElBQUksSUFBSSxHQUFHLE9BQU8sQ0FBQyxVQUFVLENBQUMsSUFBSSxDQUFDLE9BQU8sQ0FBQyxDQUFDO1lBQzVDLElBQUksQ0FBQyxJQUFJLEVBQUU7O2FBRVY7WUFDRCwwREFBMEQ7WUFDMUQsSUFBSSxLQUFLLEdBQUcsSUFBSSxDQUFDLFFBQVEsQ0FBQyxLQUFLLENBQUMsR0FBRyxDQUFDLENBQUM7WUFDckMsS0FBSyxDQUFDLE1BQU0sQ0FBQyxVQUFDLGFBQWEsRUFBRSxHQUFHLEVBQUUsR0FBRztnQkFDakMsa0NBQWtDO2dCQUNsQyxJQUFJLFFBQVEsR0FBRyxlQUFZLENBQUMsR0FBRyxD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QWEsRUFBRSxDQUFDIn0=
  100598. /***/ }),
  100599. /* 4 */
  100600. /***/ (function(module, exports, __webpack_require__) {
  100601. "use strict";
  100602. Object.defineProperty(exports, "__esModule", { value: true });
  100603. var babylonjs_1 = __webpack_require__(0);
  100604. var ViewerGlobals = /** @class */ (function () {
  100605. function ViewerGlobals() {
  100606. this.disableInit = false;
  100607. this.disableWebGL2Support = false;
  100608. }
  100609. Object.defineProperty(ViewerGlobals.prototype, "version", {
  100610. get: function () {
  100611. return babylonjs_1.Engine.Version;
  100612. },
  100613. enumerable: true,
  100614. configurable: true
  100615. });
  100616. return ViewerGlobals;
  100617. }());
  100618. exports.ViewerGlobals = ViewerGlobals;
  100619. exports.viewerGlobals = new ViewerGlobals();
  100620. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ2xvYmFscy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2dsb2JhbHMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBbUM7QUFFbkM7SUFBQTtRQUVXLGdCQUFXLEdBQVksS0FBSyxDQUFDO1FBQzdCLHlCQUFvQixHQUFZLEtBQUssQ0FBQztJQU1qRCxDQUFDO0lBSkcsc0JBQVcsa0NBQU87YUFBbEI7WUFDSSxPQUFPLGtCQUFNLENBQUMsT0FBTyxDQUFDO1FBQzFCLENBQUM7OztPQUFBO0lBRUwsb0JBQUM7QUFBRCxDQUFDLEFBVEQsSUFTQztBQVRZLHNDQUFhO0FBV2YsUUFBQSxhQUFhLEdBQWtCLElBQUksYUFBYSxFQUFFLENBQUMifQ==
  100621. /***/ }),
  100622. /* 5 */
  100623. /***/ (function(module, exports, __webpack_require__) {
  100624. "use strict";
  100625. Object.defineProperty(exports, "__esModule", { value: true });
  100626. var babylonjs_1 = __webpack_require__(0);
  100627. var modelAnimation_1 = __webpack_require__(23);
  100628. var _1 = __webpack_require__(1);
  100629. /**
  100630. * The current state of the model
  100631. */
  100632. var ModelState;
  100633. (function (ModelState) {
  100634. ModelState[ModelState["INIT"] = 0] = "INIT";
  100635. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  100636. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  100637. ModelState[ModelState["ENTRY"] = 3] = "ENTRY";
  100638. ModelState[ModelState["ENTRYDONE"] = 4] = "ENTRYDONE";
  100639. ModelState[ModelState["COMPLETE"] = 5] = "COMPLETE";
  100640. ModelState[ModelState["CANCELED"] = 6] = "CANCELED";
  100641. ModelState[ModelState["ERROR"] = 7] = "ERROR";
  100642. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  100643. /**
  100644. * The viewer model is a container for all assets representing a sngle loaded model.
  100645. */
  100646. var ViewerModel = /** @class */ (function () {
  100647. function ViewerModel(_observablesManager, modelConfiguration, _configurationContainer) {
  100648. var _this = this;
  100649. this._observablesManager = _observablesManager;
  100650. this._configurationContainer = _configurationContainer;
  100651. /**
  100652. * the list of meshes that are a part of this model
  100653. */
  100654. this._meshes = [];
  100655. /**
  100656. * ParticleSystems connected to this model
  100657. */
  100658. this.particleSystems = [];
  100659. /**
  100660. * Skeletons defined in this model
  100661. */
  100662. this.skeletons = [];
  100663. this._loaderDone = false;
  100664. this._animatables = [];
  100665. this._frameRate = 60;
  100666. this._shadowsRenderedAfterLoad = false;
  100667. this.onLoadedObservable = new babylonjs_1.Observable();
  100668. this.onLoadErrorObservable = new babylonjs_1.Observable();
  100669. this.onLoadProgressObservable = new babylonjs_1.Observable();
  100670. this.onCompleteObservable = new babylonjs_1.Observable();
  100671. this.onAfterConfigure = new babylonjs_1.Observable();
  100672. this.state = ModelState.INIT;
  100673. this.rootMesh = new babylonjs_1.AbstractMesh("modelRootMesh");
  100674. this._pivotMesh = new babylonjs_1.AbstractMesh("pivotMesh");
  100675. this._pivotMesh.parent = this.rootMesh;
  100676. // rotate 180, gltf fun
  100677. this._pivotMesh.rotation.y += Math.PI;
  100678. this._scaleTransition = new babylonjs_1.Animation("scaleAnimation", "scaling", this._frameRate, babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3, babylonjs_1.Animation.ANIMATIONLOOPMODE_CONSTANT);
  100679. this._animations = [];
  100680. //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer
  100681. this._modelConfiguration = _1.deepmerge((this._configurationContainer && this._configurationContainer.configuration.model) || {}, modelConfiguration);
  100682. if (this._observablesManager) {
  100683. this._observablesManager.onModelAddedObservable.notifyObservers(this);
  100684. }
  100685. if (this._modelConfiguration.entryAnimation) {
  100686. this.rootMesh.setEnabled(false);
  100687. }
  100688. this.onLoadedObservable.add(function () {
  100689. _this.updateConfiguration(_this._modelConfiguration);
  100690. if (_this._observablesManager) {
  100691. _this._observablesManager.onModelLoadedObservable.notifyObservers(_this);
  100692. }
  100693. _this._initAnimations();
  100694. });
  100695. this.onCompleteObservable.add(function () {
  100696. _this.state = ModelState.COMPLETE;
  100697. });
  100698. }
  100699. Object.defineProperty(ViewerModel.prototype, "shadowsRenderedAfterLoad", {
  100700. get: function () {
  100701. return this._shadowsRenderedAfterLoad;
  100702. },
  100703. set: function (rendered) {
  100704. if (!rendered) {
  100705. throw new Error("can only be enabled");
  100706. }
  100707. else {
  100708. this._shadowsRenderedAfterLoad = rendered;
  100709. }
  100710. },
  100711. enumerable: true,
  100712. configurable: true
  100713. });
  100714. ViewerModel.prototype.getViewerId = function () {
  100715. return this._configurationContainer && this._configurationContainer.viewerId;
  100716. };
  100717. Object.defineProperty(ViewerModel.prototype, "enabled", {
  100718. /**
  100719. * Is this model enabled?
  100720. */
  100721. get: function () {
  100722. return this.rootMesh.isEnabled();
  100723. },
  100724. /**
  100725. * Set whether this model is enabled or not.
  100726. */
  100727. set: function (enable) {
  100728. this.rootMesh.setEnabled(enable);
  100729. },
  100730. enumerable: true,
  100731. configurable: true
  100732. });
  100733. Object.defineProperty(ViewerModel.prototype, "loaderDone", {
  100734. set: function (done) {
  100735. this._loaderDone = done;
  100736. this._checkCompleteState();
  100737. },
  100738. enumerable: true,
  100739. configurable: true
  100740. });
  100741. ViewerModel.prototype._checkCompleteState = function () {
  100742. if (this._loaderDone && (this.state === ModelState.ENTRYDONE)) {
  100743. this._modelComplete();
  100744. }
  100745. };
  100746. /**
  100747. * Add a mesh to this model.
  100748. * Any mesh that has no parent will be provided with the root mesh as its new parent.
  100749. *
  100750. * @param mesh the new mesh to add
  100751. * @param triggerLoaded should this mesh trigger the onLoaded observable. Used when adding meshes manually.
  100752. */
  100753. ViewerModel.prototype.addMesh = function (mesh, triggerLoaded) {
  100754. if (!mesh.parent) {
  100755. mesh.parent = this._pivotMesh;
  100756. }
  100757. mesh.receiveShadows = !!this.configuration.receiveShadows;
  100758. this._meshes.push(mesh);
  100759. if (triggerLoaded) {
  100760. return this.onLoadedObservable.notifyObserversWithPromise(this);
  100761. }
  100762. };
  100763. Object.defineProperty(ViewerModel.prototype, "meshes", {
  100764. /**
  100765. * get the list of meshes (excluding the root mesh)
  100766. */
  100767. get: function () {
  100768. return this._meshes;
  100769. },
  100770. enumerable: true,
  100771. configurable: true
  100772. });
  100773. Object.defineProperty(ViewerModel.prototype, "configuration", {
  100774. /**
  100775. * Get the model's configuration
  100776. */
  100777. get: function () {
  100778. return this._modelConfiguration;
  100779. },
  100780. /**
  100781. * (Re-)set the model's entire configuration
  100782. * @param newConfiguration the new configuration to replace the new one
  100783. */
  100784. set: function (newConfiguration) {
  100785. this._modelConfiguration = newConfiguration;
  100786. this._configureModel();
  100787. },
  100788. enumerable: true,
  100789. configurable: true
  100790. });
  100791. /**
  100792. * Update the current configuration with new values.
  100793. * Configuration will not be overwritten, but merged with the new configuration.
  100794. * Priority is to the new configuration
  100795. * @param newConfiguration the configuration to be merged into the current configuration;
  100796. */
  100797. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  100798. this._modelConfiguration = _1.deepmerge(this._modelConfiguration, newConfiguration);
  100799. this._configureModel();
  100800. };
  100801. ViewerModel.prototype._initAnimations = function () {
  100802. var _this = this;
  100803. // check if this is not a gltf loader and init the animations
  100804. if (this.skeletons.length) {
  100805. this.skeletons.forEach(function (skeleton, idx) {
  100806. var ag = new babylonjs_1.AnimationGroup("animation-" + idx);
  100807. skeleton.getAnimatables().forEach(function (a) {
  100808. if (a.animations[0]) {
  100809. ag.addTargetedAnimation(a.animations[0], a);
  100810. }
  100811. });
  100812. _this.addAnimationGroup(ag);
  100813. });
  100814. }
  100815. var completeCallback = function () {
  100816. };
  100817. if (this._modelConfiguration.animation) {
  100818. if (this._modelConfiguration.animation.playOnce) {
  100819. this._animations.forEach(function (a) {
  100820. a.playMode = 0 /* ONCE */;
  100821. });
  100822. }
  100823. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  100824. var animationName_1 = this._modelConfiguration.animation.autoStart === true ?
  100825. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  100826. completeCallback = function () {
  100827. _this.playAnimation(animationName_1);
  100828. };
  100829. }
  100830. }
  100831. this._enterScene(completeCallback);
  100832. };
  100833. /**
  100834. * Animates the model from the current position to the default position
  100835. * @param completeCallback A function to call when the animation has completed
  100836. */
  100837. ViewerModel.prototype._enterScene = function (completeCallback) {
  100838. var _this = this;
  100839. var scene = this.rootMesh.getScene();
  100840. var previousValue = scene.animationPropertiesOverride.enableBlending;
  100841. var callback = function () {
  100842. _this.state = ModelState.ENTRYDONE;
  100843. scene.animationPropertiesOverride.enableBlending = previousValue;
  100844. _this._checkCompleteState();
  100845. if (completeCallback)
  100846. completeCallback();
  100847. };
  100848. if (!this._entryAnimation) {
  100849. callback();
  100850. return;
  100851. }
  100852. this.rootMesh.setEnabled(true);
  100853. // disable blending for the sake of the entry animation;
  100854. scene.animationPropertiesOverride.enableBlending = false;
  100855. this._applyAnimation(this._entryAnimation, true, callback);
  100856. };
  100857. /**
  100858. * Animates the model from the current position to the exit-screen position
  100859. * @param completeCallback A function to call when the animation has completed
  100860. */
  100861. ViewerModel.prototype._exitScene = function (completeCallback) {
  100862. if (!this._exitAnimation) {
  100863. completeCallback();
  100864. return;
  100865. }
  100866. this._applyAnimation(this._exitAnimation, false, completeCallback);
  100867. };
  100868. ViewerModel.prototype._modelComplete = function () {
  100869. var _this = this;
  100870. //reapply material defines to be sure:
  100871. var meshes = this._pivotMesh.getChildMeshes(false);
  100872. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  100873. _this._applyModelMaterialConfiguration(mesh.material);
  100874. });
  100875. this.state = ModelState.COMPLETE;
  100876. this.onCompleteObservable.notifyObservers(this);
  100877. };
  100878. /**
  100879. * Add a new animation group to this model.
  100880. * @param animationGroup the new animation group to be added
  100881. */
  100882. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  100883. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  100884. };
  100885. /**
  100886. * Get the ModelAnimation array
  100887. */
  100888. ViewerModel.prototype.getAnimations = function () {
  100889. return this._animations;
  100890. };
  100891. /**
  100892. * Get the animations' names. Using the names you can play a specific animation.
  100893. */
  100894. ViewerModel.prototype.getAnimationNames = function () {
  100895. return this._animations.map(function (a) { return a.name; });
  100896. };
  100897. /**
  100898. * Get an animation by the provided name. Used mainly when playing n animation.
  100899. * @param name the name of the animation to find
  100900. */
  100901. ViewerModel.prototype._getAnimationByName = function (name) {
  100902. // can't use .find, noe available on IE
  100903. var filtered = this._animations.filter(function (a) { return a.name === name; });
  100904. // what the next line means - if two animations have the same name, they will not be returned!
  100905. if (filtered.length === 1) {
  100906. return filtered[0];
  100907. }
  100908. else {
  100909. return null;
  100910. }
  100911. };
  100912. /**
  100913. * Choose an initialized animation using its name and start playing it
  100914. * @param name the name of the animation to play
  100915. * @returns The model aniamtion to be played.
  100916. */
  100917. ViewerModel.prototype.playAnimation = function (name) {
  100918. var animation = this.setCurrentAnimationByName(name);
  100919. if (animation) {
  100920. animation.start();
  100921. }
  100922. return animation;
  100923. };
  100924. ViewerModel.prototype.setCurrentAnimationByName = function (name) {
  100925. var animation = this._getAnimationByName(name);
  100926. if (animation) {
  100927. if (this.currentAnimation && this.currentAnimation.state !== 3 /* STOPPED */) {
  100928. this.currentAnimation.stop();
  100929. }
  100930. this.currentAnimation = animation;
  100931. return animation;
  100932. }
  100933. else {
  100934. throw new Error("animation not found - " + name);
  100935. }
  100936. };
  100937. ViewerModel.prototype._configureModel = function () {
  100938. var _this = this;
  100939. // this can be changed to the meshes that have rootMesh a parent without breaking anything.
  100940. var meshesWithNoParent = [this.rootMesh]; //this._meshes.filter(m => m.parent === this.rootMesh);
  100941. var updateMeshesWithNoParent = function (variable, value, param) {
  100942. meshesWithNoParent.forEach(function (mesh) {
  100943. if (param) {
  100944. mesh[variable][param] = value;
  100945. }
  100946. else {
  100947. mesh[variable] = value;
  100948. }
  100949. });
  100950. };
  100951. var updateXYZ = function (variable, configValues) {
  100952. if (configValues.x !== undefined) {
  100953. updateMeshesWithNoParent(variable, configValues.x, 'x');
  100954. }
  100955. if (configValues.y !== undefined) {
  100956. updateMeshesWithNoParent(variable, configValues.y, 'y');
  100957. }
  100958. if (configValues.z !== undefined) {
  100959. updateMeshesWithNoParent(variable, configValues.z, 'z');
  100960. }
  100961. if (configValues.w !== undefined) {
  100962. updateMeshesWithNoParent(variable, configValues.w, 'w');
  100963. }
  100964. };
  100965. if (this._modelConfiguration.normalize) {
  100966. var center = false;
  100967. var unitSize = false;
  100968. var parentIndex = void 0;
  100969. if (this._modelConfiguration.normalize === true) {
  100970. center = true;
  100971. unitSize = true;
  100972. }
  100973. else {
  100974. center = !!this._modelConfiguration.normalize.center;
  100975. unitSize = !!this._modelConfiguration.normalize.unitSize;
  100976. parentIndex = this._modelConfiguration.normalize.parentIndex;
  100977. }
  100978. var meshesToNormalize = [];
  100979. if (parentIndex !== undefined) {
  100980. meshesToNormalize.push(this._meshes[parentIndex]);
  100981. }
  100982. else {
  100983. meshesToNormalize = this._pivotMesh.getChildMeshes(true).length === 1 ? [this._pivotMesh] : meshesWithNoParent;
  100984. }
  100985. if (unitSize) {
  100986. meshesToNormalize.forEach(function (mesh) {
  100987. mesh.normalizeToUnitCube(true);
  100988. mesh.computeWorldMatrix(true);
  100989. });
  100990. }
  100991. if (center) {
  100992. meshesToNormalize.forEach(function (mesh) {
  100993. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  100994. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  100995. var halfSizeVec = sizeVec.scale(0.5);
  100996. var center = boundingInfo.min.add(halfSizeVec);
  100997. mesh.position = center.scale(-1);
  100998. mesh.position.y += halfSizeVec.y;
  100999. // Recompute Info.
  101000. mesh.computeWorldMatrix(true);
  101001. });
  101002. }
  101003. }
  101004. else {
  101005. // if centered, should be done here
  101006. }
  101007. // position?
  101008. if (this._modelConfiguration.position) {
  101009. updateXYZ('position', this._modelConfiguration.position);
  101010. }
  101011. if (this._modelConfiguration.rotation) {
  101012. //quaternion?
  101013. if (this._modelConfiguration.rotation.w) {
  101014. meshesWithNoParent.forEach(function (mesh) {
  101015. if (!mesh.rotationQuaternion) {
  101016. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  101017. }
  101018. });
  101019. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  101020. }
  101021. else {
  101022. updateXYZ('rotation', this._modelConfiguration.rotation);
  101023. }
  101024. }
  101025. if (this._modelConfiguration.rotationOffsetAxis) {
  101026. var rotationAxis_1 = new babylonjs_1.Vector3(0, 0, 0).copyFrom(this._modelConfiguration.rotationOffsetAxis);
  101027. meshesWithNoParent.forEach(function (m) {
  101028. if (_this._modelConfiguration.rotationOffsetAngle) {
  101029. m.rotate(rotationAxis_1, _this._modelConfiguration.rotationOffsetAngle);
  101030. }
  101031. });
  101032. }
  101033. if (this._modelConfiguration.scaling) {
  101034. updateXYZ('scaling', this._modelConfiguration.scaling);
  101035. }
  101036. if (this._modelConfiguration.castShadow) {
  101037. this._meshes.forEach(function (mesh) {
  101038. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  101039. });
  101040. }
  101041. var meshes = this._pivotMesh.getChildMeshes(false);
  101042. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  101043. _this._applyModelMaterialConfiguration(mesh.material);
  101044. });
  101045. if (this._modelConfiguration.entryAnimation) {
  101046. this._entryAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.entryAnimation);
  101047. }
  101048. if (this._modelConfiguration.exitAnimation) {
  101049. this._exitAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.exitAnimation);
  101050. }
  101051. this.onAfterConfigure.notifyObservers(this);
  101052. };
  101053. ViewerModel.prototype._modelAnimationConfigurationToObject = function (animConfig) {
  101054. var anim = {
  101055. time: 0.5
  101056. };
  101057. if (animConfig.scaling) {
  101058. anim.scaling = babylonjs_1.Vector3.Zero();
  101059. }
  101060. if (animConfig.easingFunction !== undefined) {
  101061. anim.easingFunction = animConfig.easingFunction;
  101062. }
  101063. if (animConfig.easingMode !== undefined) {
  101064. anim.easingMode = animConfig.easingMode;
  101065. }
  101066. _1.extendClassWithConfig(anim, animConfig);
  101067. return anim;
  101068. };
  101069. /**
  101070. * Apply a material configuration to a material
  101071. * @param material Material to apply configuration to
  101072. */
  101073. ViewerModel.prototype._applyModelMaterialConfiguration = function (material) {
  101074. if (!this._modelConfiguration.material)
  101075. return;
  101076. _1.extendClassWithConfig(material, this._modelConfiguration.material);
  101077. if (material instanceof babylonjs_1.PBRMaterial) {
  101078. if (this._modelConfiguration.material.directIntensity !== undefined) {
  101079. material.directIntensity = this._modelConfiguration.material.directIntensity;
  101080. }
  101081. if (this._modelConfiguration.material.emissiveIntensity !== undefined) {
  101082. material.emissiveIntensity = this._modelConfiguration.material.emissiveIntensity;
  101083. }
  101084. if (this._modelConfiguration.material.environmentIntensity !== undefined) {
  101085. material.environmentIntensity = this._modelConfiguration.material.environmentIntensity;
  101086. }
  101087. if (this._modelConfiguration.material.directEnabled !== undefined) {
  101088. material.disableLighting = !this._modelConfiguration.material.directEnabled;
  101089. }
  101090. if (this._configurationContainer && this._configurationContainer.reflectionColor) {
  101091. material.reflectionColor = this._configurationContainer.reflectionColor;
  101092. }
  101093. }
  101094. else if (material instanceof babylonjs_1.MultiMaterial) {
  101095. for (var i = 0; i < material.subMaterials.length; i++) {
  101096. var subMaterial = material.subMaterials[i];
  101097. if (subMaterial) {
  101098. this._applyModelMaterialConfiguration(subMaterial);
  101099. }
  101100. }
  101101. }
  101102. };
  101103. /**
  101104. * Start entry/exit animation given an animation configuration
  101105. * @param animationConfiguration Entry/Exit animation configuration
  101106. * @param isEntry Pass true if the animation is an entry animation
  101107. * @param completeCallback Callback to execute when the animation completes
  101108. */
  101109. ViewerModel.prototype._applyAnimation = function (animationConfiguration, isEntry, completeCallback) {
  101110. var animations = [];
  101111. //scale
  101112. if (animationConfiguration.scaling) {
  101113. var scaleStart = isEntry ? animationConfiguration.scaling : new babylonjs_1.Vector3(1, 1, 1);
  101114. var scaleEnd = isEntry ? new babylonjs_1.Vector3(1, 1, 1) : animationConfiguration.scaling;
  101115. if (!scaleStart.equals(scaleEnd)) {
  101116. this.rootMesh.scaling = scaleStart;
  101117. this._setLinearKeys(this._scaleTransition, this.rootMesh.scaling, scaleEnd, animationConfiguration.time);
  101118. animations.push(this._scaleTransition);
  101119. }
  101120. }
  101121. //Start the animation(s)
  101122. this.transitionTo(animations, animationConfiguration.time, this._createEasingFunction(animationConfiguration.easingFunction), animationConfiguration.easingMode, function () { if (completeCallback)
  101123. completeCallback(); });
  101124. };
  101125. /**
  101126. * Begin @animations with the specified @easingFunction
  101127. * @param animations The BABYLON Animations to begin
  101128. * @param duration of transition, in seconds
  101129. * @param easingFunction An easing function to apply
  101130. * @param easingMode A easing mode to apply to the easingFunction
  101131. * @param onAnimationEnd Call back trigger at the end of the animation.
  101132. */
  101133. ViewerModel.prototype.transitionTo = function (animations, duration, easingFunction, easingMode, onAnimationEnd) {
  101134. if (easingMode === void 0) { easingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT; }
  101135. if (easingFunction) {
  101136. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  101137. var animation = animations_1[_i];
  101138. easingFunction.setEasingMode(easingMode);
  101139. animation.setEasingFunction(easingFunction);
  101140. }
  101141. }
  101142. //Stop any current animations before starting the new one - merging not yet supported.
  101143. this.stopAllAnimations();
  101144. this.rootMesh.animations = animations;
  101145. if (this.rootMesh.getScene().beginAnimation) {
  101146. var animatable = this.rootMesh.getScene().beginAnimation(this.rootMesh, 0, this._frameRate * duration, false, 1, function () {
  101147. if (onAnimationEnd) {
  101148. onAnimationEnd();
  101149. }
  101150. });
  101151. this._animatables.push(animatable);
  101152. }
  101153. };
  101154. /**
  101155. * Sets key values on an Animation from first to last frame.
  101156. * @param animation The Babylon animation object to set keys on
  101157. * @param startValue The value of the first key
  101158. * @param endValue The value of the last key
  101159. * @param duration The duration of the animation, used to determine the end frame
  101160. */
  101161. ViewerModel.prototype._setLinearKeys = function (animation, startValue, endValue, duration) {
  101162. animation.setKeys([
  101163. {
  101164. frame: 0,
  101165. value: startValue
  101166. },
  101167. {
  101168. frame: this._frameRate * duration,
  101169. value: endValue
  101170. }
  101171. ]);
  101172. };
  101173. /**
  101174. * Creates and returns a Babylon easing funtion object based on a string representing the Easing function
  101175. * @param easingFunctionID The enum of the easing funtion to create
  101176. * @return The newly created Babylon easing function object
  101177. */
  101178. ViewerModel.prototype._createEasingFunction = function (easingFunctionID) {
  101179. var easingFunction;
  101180. switch (easingFunctionID) {
  101181. case 1 /* CircleEase */:
  101182. easingFunction = new babylonjs_1.CircleEase();
  101183. break;
  101184. case 2 /* BackEase */:
  101185. easingFunction = new babylonjs_1.BackEase(0.3);
  101186. break;
  101187. case 3 /* BounceEase */:
  101188. easingFunction = new babylonjs_1.BounceEase();
  101189. break;
  101190. case 4 /* CubicEase */:
  101191. easingFunction = new babylonjs_1.CubicEase();
  101192. break;
  101193. case 5 /* ElasticEase */:
  101194. easingFunction = new babylonjs_1.ElasticEase();
  101195. break;
  101196. case 6 /* ExponentialEase */:
  101197. easingFunction = new babylonjs_1.ExponentialEase();
  101198. break;
  101199. case 7 /* PowerEase */:
  101200. easingFunction = new babylonjs_1.PowerEase();
  101201. break;
  101202. case 8 /* QuadraticEase */:
  101203. easingFunction = new babylonjs_1.QuadraticEase();
  101204. break;
  101205. case 9 /* QuarticEase */:
  101206. easingFunction = new babylonjs_1.QuarticEase();
  101207. break;
  101208. case 10 /* QuinticEase */:
  101209. easingFunction = new babylonjs_1.QuinticEase();
  101210. break;
  101211. case 11 /* SineEase */:
  101212. easingFunction = new babylonjs_1.SineEase();
  101213. break;
  101214. default:
  101215. babylonjs_1.Tools.Log("No ease function found");
  101216. break;
  101217. }
  101218. return easingFunction;
  101219. };
  101220. /**
  101221. * Stops and removes all animations that have been applied to the model
  101222. */
  101223. ViewerModel.prototype.stopAllAnimations = function () {
  101224. if (this.rootMesh) {
  101225. this.rootMesh.animations = [];
  101226. }
  101227. if (this.currentAnimation) {
  101228. this.currentAnimation.stop();
  101229. }
  101230. while (this._animatables.length) {
  101231. this._animatables[0].onAnimationEnd = null;
  101232. this._animatables[0].stop();
  101233. this._animatables.shift();
  101234. }
  101235. };
  101236. /**
  101237. * Will remove this model from the viewer (but NOT dispose it).
  101238. */
  101239. ViewerModel.prototype.remove = function () {
  101240. this.stopAllAnimations();
  101241. // hide it
  101242. this.rootMesh.isVisible = false;
  101243. if (this._observablesManager) {
  101244. this._observablesManager.onModelRemovedObservable.notifyObservers(this);
  101245. }
  101246. };
  101247. /**
  101248. * Dispose this model, including all of its associated assets.
  101249. */
  101250. ViewerModel.prototype.dispose = function () {
  101251. this.remove();
  101252. this.onAfterConfigure.clear();
  101253. this.onLoadedObservable.clear();
  101254. this.onLoadErrorObservable.clear();
  101255. this.onLoadProgressObservable.clear();
  101256. if (this.loader && this.loader.name === "gltf") {
  101257. this.loader.dispose();
  101258. }
  101259. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  101260. this.particleSystems.length = 0;
  101261. this.skeletons.forEach(function (s) { return s.dispose(); });
  101262. this.skeletons.length = 0;
  101263. this._animations.forEach(function (ag) { return ag.dispose(); });
  101264. this._animations.length = 0;
  101265. this.rootMesh.dispose(false, true);
  101266. };
  101267. return ViewerModel;
  101268. }());
  101269. exports.ViewerModel = ViewerModel;
  101270. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTW9kZWwuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbW9kZWwvdmlld2VyTW9kZWwudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBc2Q7QUFJdGQsbURBQXdKO0FBRXhKLCtCQUE4RDtBQUs5RDs7R0FFRztBQUNILElBQVksVUFTWDtBQVRELFdBQVksVUFBVTtJQUNsQiwyQ0FBSSxDQUFBO0lBQ0osaURBQU8sQ0FBQTtJQUNQLCtDQUFNLENBQUE7SUFDTiw2Q0FBSyxDQUFBO0lBQ0wscURBQVMsQ0FBQTtJQUNULG1EQUFRLENBQUE7SUFDUixtREFBUSxDQUFBO0lBQ1IsNkNBQUssQ0FBQTtBQUNULENBQUMsRUFUVyxVQUFVLEdBQVYsa0JBQVUsS0FBVixrQkFBVSxRQVNyQjtBQUVEOztHQUVHO0FBQ0g7SUErRUkscUJBQW9CLG1CQUF1QyxFQUFFLGtCQUF1QyxFQUFVLHVCQUFnRDtRQUE5SixpQkFvQ0M7UUFwQ21CLHdCQUFtQixHQUFuQixtQkFBbUIsQ0FBb0I7UUFBbUQsNEJBQXVCLEdBQXZCLHVCQUF1QixDQUF5QjtRQXZFOUo7O1dBRUc7UUFDSyxZQUFPLEdBQXdCLEVBQUUsQ0FBQztRQVExQzs7V0FFRztRQUNJLG9CQUFlLEdBQTBCLEVBQUUsQ0FBQztRQUNuRDs7V0FFRztRQUNJLGNBQVMsR0FBb0IsRUFBRSxDQUFDO1FBMkMvQixnQkFBVyxHQUFZLEtBQUssQ0F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VEsQ0FBQyxPQUFPLENBQUMsS0FBSyxFQUFFLElBQUksQ0FBQyxDQUFDO0lBQ3ZDLENBQUM7SUFDTCxrQkFBQztBQUFELENBQUMsQUE1dEJELElBNHRCQztBQTV0Qlksa0NBQVcifQ==
  101271. /***/ }),
  101272. /* 6 */
  101273. /***/ (function(module, exports, __webpack_require__) {
  101274. "use strict";
  101275. Object.defineProperty(exports, "__esModule", { value: true });
  101276. var babylonjs_1 = __webpack_require__(0);
  101277. /**
  101278. * Receives Telemetry events and raises events to the API
  101279. */
  101280. var TelemetryManager = /** @class */ (function () {
  101281. function TelemetryManager() {
  101282. this.onEventBroadcastedObservable = new babylonjs_1.Observable();
  101283. this._event = this._eventEnabled;
  101284. }
  101285. Object.defineProperty(TelemetryManager.prototype, "broadcast", {
  101286. /**
  101287. * Receives a telemetry event
  101288. * @param event The name of the Telemetry event
  101289. * @param details An additional value, or an object containing a list of property/value pairs
  101290. */
  101291. get: function () {
  101292. return this._event;
  101293. },
  101294. enumerable: true,
  101295. configurable: true
  101296. });
  101297. /**
  101298. * Log a Telemetry event for errors raised on the WebGL context.
  101299. * @param engine The Babylon engine with the WebGL context.
  101300. */
  101301. TelemetryManager.prototype.flushWebGLErrors = function (engine, viewerId) {
  101302. if (!engine) {
  101303. return;
  101304. }
  101305. var logErrors = true;
  101306. while (logErrors) {
  101307. var gl = engine._gl;
  101308. if (gl && gl.getError) {
  101309. var error = gl.getError();
  101310. if (error === gl.NO_ERROR) {
  101311. logErrors = false;
  101312. }
  101313. else {
  101314. this.broadcast("WebGL Error", viewerId, { error: error });
  101315. }
  101316. }
  101317. else {
  101318. logErrors = false;
  101319. }
  101320. }
  101321. };
  101322. Object.defineProperty(TelemetryManager.prototype, "enable", {
  101323. /**
  101324. * Enable or disable telemetry events
  101325. * @param enabled Boolan, true if events are enabled
  101326. */
  101327. set: function (enabled) {
  101328. if (enabled) {
  101329. this._event = this._eventEnabled;
  101330. }
  101331. else {
  101332. this._event = this._eventDisabled;
  101333. }
  101334. },
  101335. enumerable: true,
  101336. configurable: true
  101337. });
  101338. /**
  101339. * Called on event when disabled, typically do nothing here
  101340. */
  101341. TelemetryManager.prototype._eventDisabled = function () {
  101342. // nothing to do
  101343. };
  101344. /**
  101345. * Called on event when enabled
  101346. * @param event - The name of the Telemetry event
  101347. * @param details An additional value, or an object containing a list of property/value pairs
  101348. */
  101349. TelemetryManager.prototype._eventEnabled = function (event, viewerId, details) {
  101350. var telemetryData = {
  101351. viewerId: viewerId,
  101352. event: event,
  101353. session: this.session,
  101354. date: new Date(),
  101355. now: window.performance ? window.performance.now() : Date.now(),
  101356. detail: null
  101357. };
  101358. if (typeof details === "object") {
  101359. for (var attr in details) {
  101360. if (details.hasOwnProperty(attr)) {
  101361. telemetryData[attr] = details[attr];
  101362. }
  101363. }
  101364. }
  101365. else if (details) {
  101366. telemetryData.detail = details;
  101367. }
  101368. this.onEventBroadcastedObservable.notifyObservers(telemetryData);
  101369. };
  101370. Object.defineProperty(TelemetryManager.prototype, "session", {
  101371. /**
  101372. * Returns the current session ID or creates one if it doesn't exixt
  101373. * @return The current session ID
  101374. */
  101375. get: function () {
  101376. if (!this._currentSessionId) {
  101377. //String + Timestamp + Random Integer
  101378. this._currentSessionId = "SESSION_" + Date.now() + Math.floor(Math.random() * 0x10000);
  101379. }
  101380. return this._currentSessionId;
  101381. },
  101382. enumerable: true,
  101383. configurable: true
  101384. });
  101385. /**
  101386. * Disposes the telemetry manager
  101387. */
  101388. TelemetryManager.prototype.dispose = function () {
  101389. this.onEventBroadcastedObservable.clear();
  101390. delete this.onEventBroadcastedObservable;
  101391. };
  101392. return TelemetryManager;
  101393. }());
  101394. exports.TelemetryManager = TelemetryManager;
  101395. exports.telemetryManager = new TelemetryManager();
  101396. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVsZW1ldHJ5TWFuYWdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4u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EsQ0FBQyxNQUFNLEdBQUcsT0FBTyxDQUFDO1NBQ2xDO1FBRUQsSUFBSSxDQUFDLDRCQUE0QixDQUFDLGVBQWUsQ0FBQyxhQUFhLENBQUMsQ0FBQztJQUNyRSxDQUFDO0lBTUQsc0JBQVcscUNBQU87UUFKbEI7OztXQUdHO2FBQ0g7WUFDSSxJQUFJLENBQUMsSUFBSSxDQUFDLGlCQUFpQixFQUFFO2dCQUN6QixxQ0FBcUM7Z0JBQ3JDLElBQUksQ0FBQyxpQkFBaUIsR0FBRyxVQUFVLEdBQUcsSUFBSSxDQUFDLEdBQUcsRUFBRSxHQUFHLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLE1BQU0sRUFBRSxHQUFHLE9BQU8sQ0FBQyxDQUFDO2FBQzFGO1lBQ0QsT0FBTyxJQUFJLENBQUMsaUJBQWlCLENBQUM7UUFDbEMsQ0FBQzs7O09BQUE7SUFFRDs7T0FFRztJQUNJLGtDQUFPLEdBQWQ7UUFDSSxJQUFJLENBQUMsNEJBQTRCLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDMUMsT0FBTyxJQUFJLENBQUMsNEJBQTRCLENBQUM7SUFDN0MsQ0FBQztJQUNMLHVCQUFDO0FBQUQsQ0FBQyxBQTVHRCxJQTRHQztBQTVHWSw0Q0FBZ0I7QUE4R2hCLFFBQUEsZ0JBQWdCLEdBQUcsSUFBSSxnQkFBZ0IsRUFBRSxDQUFDIn0=
  101397. /***/ }),
  101398. /* 7 */
  101399. /***/ (function(module, exports, __webpack_require__) {
  101400. "use strict";
  101401. Object.defineProperty(exports, "__esModule", { value: true });
  101402. var babylonjs_1 = __webpack_require__(0);
  101403. /**
  101404. * The viewer manager is the container for all viewers currently registered on this page.
  101405. * It is possible to have more than one viewer on a single page.
  101406. */
  101407. var ViewerManager = /** @class */ (function () {
  101408. function ViewerManager() {
  101409. this._viewers = {};
  101410. this.onViewerAddedObservable = new babylonjs_1.Observable();
  101411. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  101412. }
  101413. /**
  101414. * Adding a new viewer to the viewer manager and start tracking it.
  101415. * @param viewer the viewer to add
  101416. */
  101417. ViewerManager.prototype.addViewer = function (viewer) {
  101418. this._viewers[viewer.getBaseId()] = viewer;
  101419. this._onViewerAdded(viewer);
  101420. };
  101421. /**
  101422. * remove a viewer from the viewer manager
  101423. * @param viewer the viewer to remove
  101424. */
  101425. ViewerManager.prototype.removeViewer = function (viewer) {
  101426. var id = viewer.getBaseId();
  101427. delete this._viewers[id];
  101428. this.onViewerRemovedObservable.notifyObservers(id);
  101429. };
  101430. /**
  101431. * 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)
  101432. * @param id the id of the HTMl element (or the viewer's, if none provided)
  101433. */
  101434. ViewerManager.prototype.getViewerById = function (id) {
  101435. return this._viewers[id];
  101436. };
  101437. /**
  101438. * Get a viewer using a container element
  101439. * @param element the HTML element to search viewers associated with
  101440. */
  101441. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  101442. for (var id in this._viewers) {
  101443. if (this._viewers[id].containerElement === element) {
  101444. return this.getViewerById(id);
  101445. }
  101446. }
  101447. };
  101448. /**
  101449. * Get a promise that will fullfil when this viewer was initialized.
  101450. * Since viewer initialization and template injection is asynchronous, using the promise will guaranty that
  101451. * you will get the viewer after everything was already configured.
  101452. * @param id the viewer id to find
  101453. */
  101454. ViewerManager.prototype.getViewerPromiseById = function (id) {
  101455. var _this = this;
  101456. return new Promise(function (resolve, reject) {
  101457. var localViewer = _this.getViewerById(id);
  101458. if (localViewer) {
  101459. return resolve(localViewer);
  101460. }
  101461. var viewerFunction = function (viewer) {
  101462. if (viewer.getBaseId() === id) {
  101463. resolve(viewer);
  101464. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  101465. }
  101466. };
  101467. _this.onViewerAddedObservable.add(viewerFunction);
  101468. });
  101469. };
  101470. ViewerManager.prototype._onViewerAdded = function (viewer) {
  101471. this.onViewerAdded && this.onViewerAdded(viewer);
  101472. this.onViewerAddedObservable.notifyObservers(viewer);
  101473. };
  101474. /**
  101475. * dispose the manager and all of its associated viewers
  101476. */
  101477. ViewerManager.prototype.dispose = function () {
  101478. delete this._onViewerAdded;
  101479. for (var id in this._viewers) {
  101480. this._viewers[id].dispose();
  101481. }
  101482. this.onViewerAddedObservable.clear();
  101483. this.onViewerRemovedObservable.clear();
  101484. };
  101485. return ViewerManager;
  101486. }());
  101487. exports.ViewerManager = ViewerManager;
  101488. exports.viewerManager = new ViewerManager();
  101489. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTWFuYWdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy92aWV3ZXIvdmlld2VyTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUF1QztBQUd2Qzs7O0dBR0c7QUFDSDtJQWlCSTtRQUNJLElBQUksQ0FBQyxRQUFRLEdBQUcsRUFBRSxDQUFDO1FBQ25CLElBQUksQ0FBQyx1QkFBdUIsR0FBRyxJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUNoRCxJQUFJLENBQUMseUJBQXlCLEdBQUcsSUFBSSxzQkFBVSxFQUFFLENBQUM7SUFDdEQsQ0FBQztJQUVEOzs7T0FHRztJQUNJLGlDQUFTLEdBQWhCLFVBQWlCLE1BQXNCO1FBQ25DLElBQUksQ0FBQyxRQUFRLENBQUMsTUFBTSxDQUFDLFNBQVMsRUFBRSxDQUFDLEdBQUcsTUFBTSxDQUFDO1FBQzNDLElBQUksQ0FBQyxjQUFjLENBQUMsTUFBTSxDQUFDLENBQUM7SUFDaEMsQ0FBQztJQUVEOzs7T0FHRztJQUNJLG9DQUFZLEdBQW5CLFVBQW9CLE1BQXNCO1FBQ3RDLElBQUksRUFBRSxHQUFHLE1BQU0sQ0FBQyxTQUFTLEVBQUUsQ0FBQztRQUM1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QyxjQUFjLENBQUMsY0FBYyxDQUFDLENBQUM7aUJBQy9EO1lBQ0wsQ0FBQyxDQUFBO1lBQ0QsS0FBSSxDQUFDLHVCQUF1QixDQUFDLEdBQUcsQ0FBQyxjQUFjLENBQUMsQ0FBQztRQUNyRCxDQUFDLENBQUMsQ0FBQztJQUNQLENBQUM7SUFFTyxzQ0FBYyxHQUF0QixVQUF1QixNQUFzQjtRQUN6QyxJQUFJLENBQUMsYUFBYSxJQUFJLElBQUksQ0FBQyxhQUFhLENBQUMsTUFBTSxDQUFDLENBQUM7UUFDakQsSUFBSSxDQUFDLHVCQUF1QixDQUFDLGVBQWUsQ0FBQyxNQUFNLENBQUMsQ0FBQztJQUN6RCxDQUFDO0lBRUQ7O09BRUc7SUFDSSwrQkFBTyxHQUFkO1FBQ0ksT0FBTyxJQUFJLENBQUMsY0FBYyxDQUFDO1FBRTNCLEtBQUssSUFBSSxFQUFFLElBQUksSUFBSSxDQUFDLFFBQVEsRUFBRTtZQUMxQixJQUFJLENBQUMsUUFBUSxDQUFDLEVBQUUsQ0FBQyxDQUFDLE9BQU8sRUFBRSxDQUFDO1NBQy9CO1FBRUQsSUFBSSxDQUFDLHVCQUF1QixDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ3JDLElBQUksQ0FBQyx5QkFBeUIsQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUMzQyxDQUFDO0lBQ0wsb0JBQUM7QUFBRCxDQUFDLEFBdEdELElBc0dDO0FBdEdZLHNDQUFhO0FBd0dmLFFBQUEsYUFBYSxHQUFHLElBQUksYUFBYSxFQUFFLENBQUMifQ==
  101490. /***/ }),
  101491. /* 8 */
  101492. /***/ (function(module, exports, __webpack_require__) {
  101493. "use strict";
  101494. var __extends = (this && this.__extends) || (function () {
  101495. var extendStatics = Object.setPrototypeOf ||
  101496. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  101497. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  101498. return function (d, b) {
  101499. extendStatics(d, b);
  101500. function __() { this.constructor = d; }
  101501. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  101502. };
  101503. })();
  101504. Object.defineProperty(exports, "__esModule", { value: true });
  101505. var viewer_1 = __webpack_require__(9);
  101506. var babylonjs_1 = __webpack_require__(0);
  101507. /**
  101508. * The Default viewer is the default implementation of the AbstractViewer.
  101509. * It uses the templating system to render a new canvas and controls.
  101510. */
  101511. var DefaultViewer = /** @class */ (function (_super) {
  101512. __extends(DefaultViewer, _super);
  101513. /**
  101514. * Create a new default viewer
  101515. * @param containerElement the element in which the templates will be rendered
  101516. * @param initialConfiguration the initial configuration. Defaults to extending the default configuration
  101517. */
  101518. function DefaultViewer(containerElement, initialConfiguration) {
  101519. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  101520. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  101521. _this.containerElement = containerElement;
  101522. _this._handlePointerDown = function (event) {
  101523. var pointerDown = event.event;
  101524. if (pointerDown.button !== 0)
  101525. return;
  101526. var element = event.event.target;
  101527. if (!element) {
  101528. return;
  101529. }
  101530. var parentClasses = element.parentElement.classList;
  101531. switch (element.id) {
  101532. case "speed-button":
  101533. case "types-button":
  101534. if (parentClasses.contains("open")) {
  101535. parentClasses.remove("open");
  101536. }
  101537. else {
  101538. parentClasses.add("open");
  101539. }
  101540. break;
  101541. case "play-pause-button":
  101542. _this._togglePlayPause();
  101543. break;
  101544. case "label-option-button":
  101545. var label = element.dataset["value"];
  101546. if (label) {
  101547. _this._updateAnimationType(label);
  101548. }
  101549. break;
  101550. case "speed-option-button":
  101551. if (!_this._currentAnimation) {
  101552. return;
  101553. }
  101554. var speed = element.dataset["value"];
  101555. if (speed)
  101556. _this._updateAnimationSpeed(speed);
  101557. break;
  101558. case "progress-wrapper":
  101559. _this._resumePlay = !_this._isAnimationPaused;
  101560. if (_this._resumePlay) {
  101561. _this._togglePlayPause(true);
  101562. }
  101563. break;
  101564. case "fullscreen-button":
  101565. _this.toggleFullscreen();
  101566. break;
  101567. default:
  101568. return;
  101569. }
  101570. };
  101571. /**
  101572. * Plays or Pauses animation
  101573. */
  101574. _this._togglePlayPause = function (noUiUpdate) {
  101575. if (!_this._currentAnimation) {
  101576. return;
  101577. }
  101578. if (_this._isAnimationPaused) {
  101579. _this._currentAnimation.restart();
  101580. }
  101581. else {
  101582. _this._currentAnimation.pause();
  101583. }
  101584. _this._isAnimationPaused = !_this._isAnimationPaused;
  101585. if (noUiUpdate)
  101586. return;
  101587. var navbar = _this.templateManager.getTemplate('navBar');
  101588. if (!navbar)
  101589. return;
  101590. navbar.updateParams({
  101591. paused: _this._isAnimationPaused,
  101592. });
  101593. };
  101594. /**
  101595. * Control progress bar position based on animation current frame
  101596. */
  101597. _this._updateProgressBar = function () {
  101598. var navbar = _this.templateManager.getTemplate('navBar');
  101599. if (!navbar)
  101600. return;
  101601. var progressSlider = navbar.parent.querySelector("input#progress-wrapper");
  101602. if (progressSlider && _this._currentAnimation) {
  101603. var progress = _this._currentAnimation.currentFrame / _this._currentAnimation.frames * 100;
  101604. var currentValue = progressSlider.valueAsNumber;
  101605. if (Math.abs(currentValue - progress) > 0.5) { // Only move if greater than a 1% change
  101606. progressSlider.value = '' + progress;
  101607. }
  101608. if (_this._currentAnimation.state === 1 /* PLAYING */) {
  101609. if (_this.sceneManager.camera.autoRotationBehavior && !_this._oldIdleRotationValue) {
  101610. _this._oldIdleRotationValue = _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed;
  101611. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = 0;
  101612. }
  101613. }
  101614. else {
  101615. if (_this.sceneManager.camera.autoRotationBehavior && _this._oldIdleRotationValue) {
  101616. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = _this._oldIdleRotationValue;
  101617. _this._oldIdleRotationValue = 0;
  101618. }
  101619. }
  101620. }
  101621. };
  101622. /**
  101623. * Update Current Animation Speed
  101624. */
  101625. _this._updateAnimationSpeed = function (speed, paramsObject) {
  101626. var navbar = _this.templateManager.getTemplate('navBar');
  101627. if (!navbar)
  101628. return;
  101629. if (speed && _this._currentAnimation) {
  101630. _this._currentAnimation.speedRatio = parseFloat(speed);
  101631. if (!_this._isAnimationPaused) {
  101632. _this._currentAnimation.restart();
  101633. }
  101634. if (paramsObject) {
  101635. paramsObject.selectedSpeed = speed + "x";
  101636. }
  101637. else {
  101638. navbar.updateParams({
  101639. selectedSpeed: speed + "x",
  101640. });
  101641. }
  101642. }
  101643. };
  101644. /**
  101645. * Update Current Animation Type
  101646. */
  101647. _this._updateAnimationType = function (label, paramsObject) {
  101648. var navbar = _this.templateManager.getTemplate('navBar');
  101649. if (!navbar)
  101650. return;
  101651. if (label) {
  101652. _this._currentAnimation = _this.sceneManager.models[0].setCurrentAnimationByName(label);
  101653. }
  101654. if (paramsObject) {
  101655. paramsObject.selectedAnimation = (_this._animationList.indexOf(label) + 1);
  101656. paramsObject.selectedAnimationName = label;
  101657. }
  101658. else {
  101659. navbar.updateParams({
  101660. selectedAnimation: (_this._animationList.indexOf(label) + 1),
  101661. selectedAnimationName: label
  101662. });
  101663. }
  101664. _this._updateAnimationSpeed("1.0", paramsObject);
  101665. };
  101666. /**
  101667. * Toggle fullscreen of the entire viewer
  101668. */
  101669. _this.toggleFullscreen = function () {
  101670. var viewerTemplate = _this.templateManager.getTemplate('viewer');
  101671. var viewerElement = viewerTemplate && viewerTemplate.parent;
  101672. if (viewerElement) {
  101673. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  101674. if (!fullscreenElement) {
  101675. var requestFullScreen = viewerElement.requestFullscreen || viewerElement.webkitRequestFullscreen || viewerElement.msRequestFullscreen || viewerElement.mozRequestFullScreen;
  101676. requestFullScreen.call(viewerElement);
  101677. }
  101678. else {
  101679. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  101680. exitFullscreen.call(document);
  101681. }
  101682. }
  101683. };
  101684. _this._onModelLoaded = function (model) {
  101685. _this._configureTemplate(model);
  101686. // with a short timeout, making sure everything is there already.
  101687. var hideLoadingDelay = 20;
  101688. if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) {
  101689. hideLoadingDelay = _this.configuration.lab.hideLoadingDelay;
  101690. }
  101691. setTimeout(function () {
  101692. _this.sceneManager.scene.executeWhenReady(function () {
  101693. _this.hideLoadingScreen();
  101694. });
  101695. }, hideLoadingDelay);
  101696. return;
  101697. };
  101698. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  101699. _this.onModelRemovedObservable.add(function () {
  101700. _this._configureTemplate();
  101701. });
  101702. _this.onEngineInitObservable.add(function () {
  101703. _this.sceneManager.onLightsConfiguredObservable.add(function (data) {
  101704. _this._configureLights(data.newConfiguration, data.model);
  101705. });
  101706. });
  101707. return _this;
  101708. }
  101709. /**
  101710. * This will be executed when the templates initialize.
  101711. */
  101712. DefaultViewer.prototype._onTemplatesLoaded = function () {
  101713. var _this = this;
  101714. this.showLoadingScreen();
  101715. // navbar
  101716. this._initNavbar();
  101717. // close overlay button
  101718. var closeButton = document.getElementById('close-button');
  101719. if (closeButton) {
  101720. closeButton.addEventListener('pointerdown', function () {
  101721. _this.hideOverlayScreen();
  101722. });
  101723. }
  101724. if (this.configuration.templates && this.configuration.templates.viewer) {
  101725. if (this.configuration.templates.viewer.params && this.configuration.templates.viewer.params.enableDragAndDrop) {
  101726. var filesInput = new babylonjs_1.FilesInput(this.engine, this.sceneManager.scene, function () {
  101727. }, function () {
  101728. }, function () {
  101729. }, function () {
  101730. }, function () {
  101731. }, function (file) {
  101732. _this.loadModel(file);
  101733. }, function () {
  101734. });
  101735. filesInput.monitorElementForDragNDrop(this.templateManager.getCanvas());
  101736. }
  101737. }
  101738. return _super.prototype._onTemplatesLoaded.call(this);
  101739. };
  101740. DefaultViewer.prototype._dropped = function (evt) {
  101741. };
  101742. DefaultViewer.prototype._initNavbar = function () {
  101743. var _this = this;
  101744. var navbar = this.templateManager.getTemplate('navBar');
  101745. if (navbar) {
  101746. this.onFrameRenderedObservable.add(this._updateProgressBar);
  101747. this.templateManager.eventManager.registerCallback('navBar', this._handlePointerDown, 'pointerdown');
  101748. // an example how to trigger the help button. publiclly available
  101749. this.templateManager.eventManager.registerCallback("navBar", function () {
  101750. // do your thing
  101751. }, "pointerdown", "#help-button");
  101752. this.templateManager.eventManager.registerCallback("navBar", function (event) {
  101753. var evt = event.event;
  101754. var element = (evt.target);
  101755. if (!_this._currentAnimation)
  101756. return;
  101757. var gotoFrame = +element.value / 100 * _this._currentAnimation.frames;
  101758. if (isNaN(gotoFrame))
  101759. return;
  101760. _this._currentAnimation.goToFrame(gotoFrame);
  101761. }, "input");
  101762. this.templateManager.eventManager.registerCallback("navBar", function (e) {
  101763. if (_this._resumePlay) {
  101764. _this._togglePlayPause(true);
  101765. }
  101766. _this._resumePlay = false;
  101767. }, "pointerup", "#progress-wrapper");
  101768. }
  101769. };
  101770. /**
  101771. * Preparing the container element to present the viewer
  101772. */
  101773. DefaultViewer.prototype._prepareContainerElement = function () {
  101774. this.containerElement.style.position = 'relative';
  101775. this.containerElement.style.height = '100%';
  101776. this.containerElement.style.display = 'flex';
  101777. };
  101778. /**
  101779. * This function will configure the templates and update them after a model was loaded
  101780. * It is mainly responsible to changing the title and subtitle etc'.
  101781. * @param model the model to be used to configure the templates by
  101782. */
  101783. DefaultViewer.prototype._configureTemplate = function (model) {
  101784. var navbar = this.templateManager.getTemplate('navBar');
  101785. if (!navbar)
  101786. return;
  101787. var newParams = navbar.configuration.params || {};
  101788. if (!model) {
  101789. newParams.animations = null;
  101790. }
  101791. else {
  101792. var animationNames = model.getAnimationNames();
  101793. newParams.animations = animationNames;
  101794. if (animationNames.length) {
  101795. this._isAnimationPaused = (model.configuration.animation && !model.configuration.animation.autoStart) || !model.configuration.animation;
  101796. this._animationList = animationNames;
  101797. newParams.paused = this._isAnimationPaused;
  101798. var animationIndex = 0;
  101799. if (model.configuration.animation && typeof model.configuration.animation.autoStart === 'string') {
  101800. animationIndex = animationNames.indexOf(model.configuration.animation.autoStart);
  101801. if (animationIndex === -1) {
  101802. animationIndex = 0;
  101803. }
  101804. }
  101805. this._updateAnimationType(animationNames[animationIndex], newParams);
  101806. }
  101807. else {
  101808. newParams.animations = null;
  101809. }
  101810. if (model.configuration.thumbnail) {
  101811. newParams.logoImage = model.configuration.thumbnail;
  101812. }
  101813. }
  101814. navbar.updateParams(newParams, false);
  101815. };
  101816. /**
  101817. * This will load a new model to the default viewer
  101818. * overriding the AbstractViewer's loadModel.
  101819. * The scene will automatically be cleared of the old models, if exist.
  101820. * @param model the configuration object (or URL) to load.
  101821. */
  101822. DefaultViewer.prototype.loadModel = function (model) {
  101823. var _this = this;
  101824. if (!model) {
  101825. model = this.configuration.model;
  101826. }
  101827. this.showLoadingScreen();
  101828. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  101829. console.log(error);
  101830. _this.hideLoadingScreen();
  101831. _this.showOverlayScreen('error');
  101832. return Promise.reject(error);
  101833. });
  101834. };
  101835. /**
  101836. * Show the overlay and the defined sub-screen.
  101837. * Mainly used for help and errors
  101838. * @param subScreen the name of the subScreen. Those can be defined in the configuration object
  101839. */
  101840. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  101841. var _this = this;
  101842. var template = this.templateManager.getTemplate('overlay');
  101843. if (!template)
  101844. return Promise.resolve('Overlay template not found');
  101845. return template.show((function (template) {
  101846. var canvasRect = _this.containerElement.getBoundingClientRect();
  101847. template.parent.style.display = 'flex';
  101848. template.parent.style.width = canvasRect.width + "px";
  101849. template.parent.style.height = canvasRect.height + "px";
  101850. template.parent.style.opacity = "1";
  101851. var subTemplate = _this.templateManager.getTemplate(subScreen);
  101852. if (!subTemplate) {
  101853. return Promise.reject(subScreen + ' template not found');
  101854. }
  101855. return subTemplate.show((function (template) {
  101856. template.parent.style.display = 'flex';
  101857. return Promise.resolve(template);
  101858. }));
  101859. }));
  101860. };
  101861. /**
  101862. * Hide the overlay screen.
  101863. */
  101864. DefaultViewer.prototype.hideOverlayScreen = function () {
  101865. var template = this.templateManager.getTemplate('overlay');
  101866. if (!template)
  101867. return Promise.resolve('Overlay template not found');
  101868. return template.hide((function (template) {
  101869. template.parent.style.opacity = "0";
  101870. var onTransitionEnd = function () {
  101871. template.parent.removeEventListener("transitionend", onTransitionEnd);
  101872. template.parent.style.display = 'none';
  101873. };
  101874. template.parent.addEventListener("transitionend", onTransitionEnd);
  101875. var overlays = template.parent.querySelectorAll('.overlay');
  101876. if (overlays) {
  101877. for (var i = 0; i < overlays.length; ++i) {
  101878. var htmlElement = overlays.item(i);
  101879. htmlElement.style.display = 'none';
  101880. }
  101881. }
  101882. return Promise.resolve(template);
  101883. }));
  101884. };
  101885. /**
  101886. * show the viewer (in case it was hidden)
  101887. *
  101888. * @param visibilityFunction an optional function to execute in order to show the container
  101889. */
  101890. DefaultViewer.prototype.show = function (visibilityFunction) {
  101891. var template = this.templateManager.getTemplate('main');
  101892. //not possible, but yet:
  101893. if (!template)
  101894. return Promise.reject('Main template not found');
  101895. return template.show(visibilityFunction);
  101896. };
  101897. /**
  101898. * hide the viewer (in case it is visible)
  101899. *
  101900. * @param visibilityFunction an optional function to execute in order to hide the container
  101901. */
  101902. DefaultViewer.prototype.hide = function (visibilityFunction) {
  101903. var template = this.templateManager.getTemplate('main');
  101904. //not possible, but yet:
  101905. if (!template)
  101906. return Promise.reject('Main template not found');
  101907. return template.hide(visibilityFunction);
  101908. };
  101909. /**
  101910. * Show the loading screen.
  101911. * The loading screen can be configured using the configuration object
  101912. */
  101913. DefaultViewer.prototype.showLoadingScreen = function () {
  101914. var _this = this;
  101915. var template = this.templateManager.getTemplate('loadingScreen');
  101916. if (!template)
  101917. return Promise.resolve('Loading Screen template not found');
  101918. return template.show((function (template) {
  101919. var canvasRect = _this.containerElement.getBoundingClientRect();
  101920. // var canvasPositioning = window.getComputedStyle(this.containerElement).position;
  101921. template.parent.style.display = 'flex';
  101922. template.parent.style.width = canvasRect.width + "px";
  101923. template.parent.style.height = canvasRect.height + "px";
  101924. template.parent.style.opacity = "1";
  101925. // from the configuration!!!
  101926. var color = "black";
  101927. if (_this.configuration.templates && _this.configuration.templates.loadingScreen) {
  101928. color = (_this.configuration.templates.loadingScreen.params &&
  101929. _this.configuration.templates.loadingScreen.params.backgroundColor) || color;
  101930. }
  101931. template.parent.style.backgroundColor = color;
  101932. return Promise.resolve(template);
  101933. }));
  101934. };
  101935. /**
  101936. * Hide the loading screen
  101937. */
  101938. DefaultViewer.prototype.hideLoadingScreen = function () {
  101939. var template = this.templateManager.getTemplate('loadingScreen');
  101940. if (!template)
  101941. return Promise.resolve('Loading Screen template not found');
  101942. return template.hide((function (template) {
  101943. template.parent.style.opacity = "0";
  101944. var onTransitionEnd = function () {
  101945. template.parent.removeEventListener("transitionend", onTransitionEnd);
  101946. template.parent.style.display = 'none';
  101947. };
  101948. template.parent.addEventListener("transitionend", onTransitionEnd);
  101949. return Promise.resolve(template);
  101950. }));
  101951. };
  101952. DefaultViewer.prototype.dispose = function () {
  101953. this.templateManager.dispose();
  101954. _super.prototype.dispose.call(this);
  101955. };
  101956. DefaultViewer.prototype._onConfigurationLoaded = function (configuration) {
  101957. var _this = this;
  101958. _super.prototype._onConfigurationLoaded.call(this, configuration);
  101959. // initialize the templates
  101960. var templateConfiguration = this.configuration.templates || {};
  101961. this.templateManager.initTemplate(templateConfiguration);
  101962. // when done, execute onTemplatesLoaded()
  101963. this.templateManager.onAllLoaded.add(function () {
  101964. var canvas = _this.templateManager.getCanvas();
  101965. if (canvas) {
  101966. _this._canvas = canvas;
  101967. }
  101968. _this._onTemplateLoaded();
  101969. });
  101970. };
  101971. /**
  101972. * An extension of the light configuration of the abstract viewer.
  101973. * @param lightsConfiguration the light configuration to use
  101974. * @param model the model that will be used to configure the lights (if the lights are model-dependant)
  101975. */
  101976. DefaultViewer.prototype._configureLights = function (lightsConfiguration, model) {
  101977. var _this = this;
  101978. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  101979. // labs feature - flashlight
  101980. if (this.configuration.lab && this.configuration.lab.flashlight) {
  101981. var pointerPosition = babylonjs_1.Vector3.Zero();
  101982. var lightTarget_1;
  101983. var angle = 0.5;
  101984. var exponent = Math.PI / 2;
  101985. if (typeof this.configuration.lab.flashlight === "object") {
  101986. exponent = this.configuration.lab.flashlight.exponent || exponent;
  101987. angle = this.configuration.lab.flashlight.angle || angle;
  101988. }
  101989. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.sceneManager.scene);
  101990. if (typeof this.configuration.lab.flashlight === "object") {
  101991. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  101992. if (this.configuration.lab.flashlight.diffuse) {
  101993. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  101994. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  101995. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  101996. }
  101997. if (this.configuration.lab.flashlight.specular) {
  101998. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  101999. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  102000. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  102001. }
  102002. }
  102003. this.sceneManager.scene.constantlyUpdateMeshUnderPointer = true;
  102004. this.sceneManager.scene.onPointerObservable.add(function (eventData, eventState) {
  102005. if (eventData.type === 4 && eventData.pickInfo) {
  102006. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  102007. }
  102008. else {
  102009. lightTarget_1 = undefined;
  102010. }
  102011. });
  102012. var updateFlashlightFunction = function () {
  102013. if (_this.sceneManager.camera && flashlight) {
  102014. flashlight.position.copyFrom(_this.sceneManager.camera.position);
  102015. if (lightTarget_1) {
  102016. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  102017. }
  102018. }
  102019. };
  102020. this.sceneManager.scene.registerBeforeRender(updateFlashlightFunction);
  102021. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  102022. }
  102023. };
  102024. return DefaultViewer;
  102025. }(viewer_1.AbstractViewer));
  102026. exports.DefaultViewer = DefaultViewer;
  102027. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVmYXVsdFZpZXdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy92aWV3ZXIvZGVmYXVsdFZpZXdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7QUFJQSxtQ0FBMEM7QUFDMUMsdUNBQXNZO0FBTXRZOzs7R0FHRztBQUNIO0lBQW1DLGlDQUFjO0lBSTdDOzs7O09BSUc7SUFDSCx1QkFBbUIsZ0JBQTZCLEVBQUUsb0JBQWtFO1FBQWxFLHFDQUFBLEVBQUEseUJBQThDLE9BQU8sRUFBRSxTQUFTLEVBQUU7UUFBcEgsWUFDSSxrQkFBTSxnQkFBZ0IsRUFBRSxvQkFBb0IsQ0FBQyxTQVloRDtRQWJrQixzQkFBZ0IsR0FBaEIsZ0JBQWdCLENBQWE7UUF3RnhDLHdCQUFrQixHQUFHLFVBQUMsS0FBb0I7WUFFOUMsSUFBSSxXQUFXLEdBQWlCLEtBQUssQ0FBQyxLQUFLLENBQUM7WUFDNUMsSUFBSSxXQUFXLENBQUMsTUFBTSxLQUFLLENBQUM7Z0JBQUUsT0FBTztZQUNyQyxJQUFJLE9BQU8sR0FBaUIsS0FBSyxDQUFDLEtBQUssQ0FBQyxNQUFPLENBQUM7WUFFaEQsSUFBSSxDQUFDLE9BQU8sRUFBRTtnQkFDVixPQUFPO2FBQ1Y7WUFFRCxJQUFJLGFBQWEsR0FBRyxPQUFPLENBQUMsYUFBYyxDQUFDLFNBQVMsQ0FBQztZQUVyRCxRQUFRLE9BQU8sQ0FB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SUFBSSxDQUFDLHdCQUF3QixDQUFDLENBQUM7U0FDMUU7SUFDTCxDQUFDO0lBQ0wsb0JBQUM7QUFBRCxDQUFDLEFBemlCRCxDQUFtQyx1QkFBYyxHQXlpQmhEO0FBemlCWSxzQ0FBYSJ9
  102028. /***/ }),
  102029. /* 9 */
  102030. /***/ (function(module, exports, __webpack_require__) {
  102031. "use strict";
  102032. Object.defineProperty(exports, "__esModule", { value: true });
  102033. var viewerManager_1 = __webpack_require__(7);
  102034. var sceneManager_1 = __webpack_require__(22);
  102035. var loader_1 = __webpack_require__(28);
  102036. var babylonjs_1 = __webpack_require__(0);
  102037. var modelLoader_1 = __webpack_require__(13);
  102038. var globals_1 = __webpack_require__(4);
  102039. var telemetryManager_1 = __webpack_require__(6);
  102040. var _1 = __webpack_require__(1);
  102041. var observablesManager_1 = __webpack_require__(59);
  102042. var configurationContainer_1 = __webpack_require__(60);
  102043. var templateManager_1 = __webpack_require__(61);
  102044. /**
  102045. * The AbstractViewr is the center of Babylon's viewer.
  102046. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  102047. */
  102048. var AbstractViewer = /** @class */ (function () {
  102049. function AbstractViewer(containerElement, initialConfiguration) {
  102050. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  102051. var _this = this;
  102052. this.containerElement = containerElement;
  102053. /**
  102054. * A flag that controls whether or not the render loop should be executed
  102055. */
  102056. this.runRenderLoop = true;
  102057. /**
  102058. * is this viewer disposed?
  102059. */
  102060. this._isDisposed = false;
  102061. /**
  102062. * The resize function that will be registered with the window object
  102063. */
  102064. this._resize = function () {
  102065. // Only resize if Canvas is in the DOM
  102066. if (!_this.isCanvasInDOM()) {
  102067. return;
  102068. }
  102069. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  102070. return;
  102071. }
  102072. if (_this.configuration.engine && _this.configuration.engine.disableResize) {
  102073. return;
  102074. }
  102075. _this.engine.resize();
  102076. };
  102077. /**
  102078. * render loop that will be executed by the engine
  102079. */
  102080. this._render = function (force) {
  102081. if (force === void 0) { force = false; }
  102082. if (force || (_this.sceneManager.scene && _this.sceneManager.scene.activeCamera)) {
  102083. if (_this.runRenderLoop || force) {
  102084. _this.engine.performanceMonitor.enable();
  102085. _this.sceneManager.scene.render();
  102086. _this.onFrameRenderedObservable.notifyObservers(_this);
  102087. }
  102088. else {
  102089. _this.engine.performanceMonitor.disable();
  102090. // update camera instead of rendering
  102091. _this.sceneManager.scene.activeCamera && _this.sceneManager.scene.activeCamera.update();
  102092. }
  102093. }
  102094. };
  102095. // if exists, use the container id. otherwise, generate a random string.
  102096. if (containerElement.id) {
  102097. this.baseId = containerElement.id;
  102098. }
  102099. else {
  102100. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  102101. }
  102102. this._registeredOnBeforeRenderFunctions = [];
  102103. this._configurationContainer = new configurationContainer_1.ConfigurationContainer();
  102104. // add this viewer to the viewer manager
  102105. viewerManager_1.viewerManager.addViewer(this);
  102106. this.observablesManager = new observablesManager_1.ObservablesManager();
  102107. this.modelLoader = new modelLoader_1.ModelLoader(this.observablesManager, this._configurationContainer);
  102108. babylonjs_1.RenderingManager.AUTOCLEAR = false;
  102109. // extend the configuration
  102110. this._configurationLoader = new loader_1.ConfigurationLoader();
  102111. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  102112. _this._onConfigurationLoaded(configuration);
  102113. });
  102114. this.onSceneInitObservable.add(function () {
  102115. _this.updateConfiguration();
  102116. });
  102117. this.onInitDoneObservable.add(function () {
  102118. _this._isInit = true;
  102119. _this.engine.runRenderLoop(_this._render);
  102120. });
  102121. this._prepareContainerElement();
  102122. }
  102123. Object.defineProperty(AbstractViewer.prototype, "onSceneInitObservable", {
  102124. // observables
  102125. /**
  102126. * Will notify when the scene was initialized
  102127. */
  102128. get: function () {
  102129. return this.observablesManager.onSceneInitObservable;
  102130. },
  102131. enumerable: true,
  102132. configurable: true
  102133. });
  102134. Object.defineProperty(AbstractViewer.prototype, "onEngineInitObservable", {
  102135. /**
  102136. * will notify when the engine was initialized
  102137. */
  102138. get: function () {
  102139. return this.observablesManager.onEngineInitObservable;
  102140. },
  102141. enumerable: true,
  102142. configurable: true
  102143. });
  102144. Object.defineProperty(AbstractViewer.prototype, "onModelAddedObservable", {
  102145. /**
  102146. * Will notify when a new model was added to the scene.
  102147. * Note that added does not neccessarily mean loaded!
  102148. */
  102149. get: function () {
  102150. return this.observablesManager.onModelAddedObservable;
  102151. },
  102152. enumerable: true,
  102153. configurable: true
  102154. });
  102155. Object.defineProperty(AbstractViewer.prototype, "onModelLoadedObservable", {
  102156. /**
  102157. * will notify after every model load
  102158. */
  102159. get: function () {
  102160. return this.observablesManager.onModelLoadedObservable;
  102161. },
  102162. enumerable: true,
  102163. configurable: true
  102164. });
  102165. Object.defineProperty(AbstractViewer.prototype, "onModelLoadProgressObservable", {
  102166. /**
  102167. * will notify when any model notify of progress
  102168. */
  102169. get: function () {
  102170. return this.observablesManager.onModelLoadProgressObservable;
  102171. },
  102172. enumerable: true,
  102173. configurable: true
  102174. });
  102175. Object.defineProperty(AbstractViewer.prototype, "onModelLoadErrorObservable", {
  102176. /**
  102177. * will notify when any model load failed.
  102178. */
  102179. get: function () {
  102180. return this.observablesManager.onModelLoadErrorObservable;
  102181. },
  102182. enumerable: true,
  102183. configurable: true
  102184. });
  102185. Object.defineProperty(AbstractViewer.prototype, "onModelRemovedObservable", {
  102186. /**
  102187. * Will notify when a model was removed from the scene;
  102188. */
  102189. get: function () {
  102190. return this.observablesManager.onModelRemovedObservable;
  102191. },
  102192. enumerable: true,
  102193. configurable: true
  102194. });
  102195. Object.defineProperty(AbstractViewer.prototype, "onLoaderInitObservable", {
  102196. /**
  102197. * will notify when a new loader was initialized.
  102198. * Used mainly to know when a model starts loading.
  102199. */
  102200. get: function () {
  102201. return this.observablesManager.onLoaderInitObservable;
  102202. },
  102203. enumerable: true,
  102204. configurable: true
  102205. });
  102206. Object.defineProperty(AbstractViewer.prototype, "onInitDoneObservable", {
  102207. /**
  102208. * Observers registered here will be executed when the entire load process has finished.
  102209. */
  102210. get: function () {
  102211. return this.observablesManager.onViewerInitDoneObservable;
  102212. },
  102213. enumerable: true,
  102214. configurable: true
  102215. });
  102216. Object.defineProperty(AbstractViewer.prototype, "onFrameRenderedObservable", {
  102217. /**
  102218. * Functions added to this observable will be executed on each frame rendered.
  102219. */
  102220. get: function () {
  102221. return this.observablesManager.onFrameRenderedObservable;
  102222. },
  102223. enumerable: true,
  102224. configurable: true
  102225. });
  102226. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  102227. /**
  102228. * The (single) canvas of this viewer
  102229. */
  102230. get: function () {
  102231. return this._canvas;
  102232. },
  102233. enumerable: true,
  102234. configurable: true
  102235. });
  102236. Object.defineProperty(AbstractViewer.prototype, "configurationContainer", {
  102237. get: function () {
  102238. return this._configurationContainer;
  102239. },
  102240. enumerable: true,
  102241. configurable: true
  102242. });
  102243. /**
  102244. * get the baseId of this viewer
  102245. */
  102246. AbstractViewer.prototype.getBaseId = function () {
  102247. return this.baseId;
  102248. };
  102249. /**
  102250. * Do we have a canvas to render on, and is it a part of the scene
  102251. */
  102252. AbstractViewer.prototype.isCanvasInDOM = function () {
  102253. return !!this._canvas && !!this._canvas.parentElement;
  102254. };
  102255. Object.defineProperty(AbstractViewer.prototype, "renderInBackground", {
  102256. /**
  102257. * Is the engine currently set to rende even when the page is in background
  102258. */
  102259. get: function () {
  102260. return this.engine && this.engine.renderEvenInBackground;
  102261. },
  102262. /**
  102263. * Set the viewer's background rendering flag.
  102264. */
  102265. set: function (value) {
  102266. if (this.engine) {
  102267. this.engine.renderEvenInBackground = value;
  102268. }
  102269. },
  102270. enumerable: true,
  102271. configurable: true
  102272. });
  102273. Object.defineProperty(AbstractViewer.prototype, "configuration", {
  102274. /**
  102275. * Get the configuration object. This is a reference only.
  102276. * The configuration can ONLY be updated using the updateConfiguration function.
  102277. * changing this object will have no direct effect on the scene.
  102278. */
  102279. get: function () {
  102280. return this._configurationContainer.configuration;
  102281. },
  102282. enumerable: true,
  102283. configurable: true
  102284. });
  102285. /**
  102286. * force resizing the engine.
  102287. */
  102288. AbstractViewer.prototype.forceResize = function () {
  102289. this._resize();
  102290. };
  102291. AbstractViewer.prototype._onConfigurationLoaded = function (configuration) {
  102292. var _this = this;
  102293. this._configurationContainer.configuration = _1.deepmerge(this.configuration || {}, configuration);
  102294. if (this.configuration.observers) {
  102295. this._configureObservers(this.configuration.observers);
  102296. }
  102297. // TODO remove this after testing, as this is done in the updateCOnfiguration as well.
  102298. if (this.configuration.loaderPlugins) {
  102299. Object.keys(this.configuration.loaderPlugins).forEach((function (name) {
  102300. if (_this.configuration.loaderPlugins && _this.configuration.loaderPlugins[name]) {
  102301. _this.modelLoader.addPlugin(name);
  102302. }
  102303. }));
  102304. }
  102305. this.templateManager = new templateManager_1.TemplateManager(this.containerElement);
  102306. };
  102307. /**
  102308. * Force a single render loop execution.
  102309. */
  102310. AbstractViewer.prototype.forceRender = function () {
  102311. this._render(true);
  102312. };
  102313. /**
  102314. * Takes a screenshot of the scene and returns it as a base64 encoded png.
  102315. * @param callback optional callback that will be triggered when screenshot is done.
  102316. * @param width Optional screenshot width (default to 512).
  102317. * @param height Optional screenshot height (default to 512).
  102318. * @returns a promise with the screenshot data
  102319. */
  102320. AbstractViewer.prototype.takeScreenshot = function (callback, width, height) {
  102321. var _this = this;
  102322. if (width === void 0) { width = 0; }
  102323. if (height === void 0) { height = 0; }
  102324. width = width || this.canvas.clientWidth;
  102325. height = height || this.canvas.clientHeight;
  102326. // Create the screenshot
  102327. return new Promise(function (resolve, reject) {
  102328. try {
  102329. BABYLON.Tools.CreateScreenshot(_this.engine, _this.sceneManager.camera, { width: width, height: height }, function (data) {
  102330. if (callback) {
  102331. callback(data);
  102332. }
  102333. resolve(data);
  102334. });
  102335. }
  102336. catch (e) {
  102337. reject(e);
  102338. }
  102339. });
  102340. };
  102341. /**
  102342. * Update the current viewer configuration with new values.
  102343. * Only provided information will be updated, old configuration values will be kept.
  102344. * If this.configuration was manually changed, you can trigger this function with no parameters,
  102345. * and the entire configuration will be updated.
  102346. * @param newConfiguration the partial configuration to update
  102347. *
  102348. */
  102349. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  102350. var _this = this;
  102351. if (newConfiguration === void 0) { newConfiguration = this.configuration; }
  102352. // update this.configuration with the new data
  102353. this._configurationContainer.configuration = _1.deepmerge(this.configuration || {}, newConfiguration);
  102354. this.sceneManager.updateConfiguration(newConfiguration);
  102355. // observers in configuration
  102356. if (newConfiguration.observers) {
  102357. this._configureObservers(newConfiguration.observers);
  102358. }
  102359. if (newConfiguration.loaderPlugins) {
  102360. Object.keys(newConfiguration.loaderPlugins).forEach((function (name) {
  102361. if (newConfiguration.loaderPlugins && newConfiguration.loaderPlugins[name]) {
  102362. _this.modelLoader.addPlugin(name);
  102363. }
  102364. }));
  102365. }
  102366. };
  102367. /**
  102368. * this is used to register native functions using the configuration object.
  102369. * This will configure the observers.
  102370. * @param observersConfiguration observers configuration
  102371. */
  102372. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  102373. if (observersConfiguration.onEngineInit) {
  102374. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  102375. }
  102376. else {
  102377. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) {
  102378. this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]);
  102379. }
  102380. }
  102381. if (observersConfiguration.onSceneInit) {
  102382. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  102383. }
  102384. else {
  102385. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) {
  102386. this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]);
  102387. }
  102388. }
  102389. if (observersConfiguration.onModelLoaded) {
  102390. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  102391. }
  102392. else {
  102393. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) {
  102394. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]);
  102395. }
  102396. }
  102397. };
  102398. /**
  102399. * Dispoe the entire viewer including the scene and the engine
  102400. */
  102401. AbstractViewer.prototype.dispose = function () {
  102402. if (this._isDisposed) {
  102403. return;
  102404. }
  102405. window.removeEventListener('resize', this._resize);
  102406. if (this.sceneManager) {
  102407. if (this.sceneManager.scene && this.sceneManager.scene.activeCamera) {
  102408. this.sceneManager.scene.activeCamera.detachControl(this.canvas);
  102409. }
  102410. this.sceneManager.dispose();
  102411. }
  102412. this._fpsTimeoutInterval && clearInterval(this._fpsTimeoutInterval);
  102413. this.observablesManager.dispose();
  102414. this.modelLoader.dispose();
  102415. if (this.engine) {
  102416. this.engine.dispose();
  102417. }
  102418. viewerManager_1.viewerManager.removeViewer(this);
  102419. this._isDisposed = true;
  102420. };
  102421. /**
  102422. * This function will execute when the HTML templates finished initializing.
  102423. * It should initialize the engine and continue execution.
  102424. *
  102425. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  102426. */
  102427. AbstractViewer.prototype._onTemplatesLoaded = function () {
  102428. return Promise.resolve(this);
  102429. };
  102430. /**
  102431. * This will force the creation of an engine and a scene.
  102432. * It will also load a model if preconfigured.
  102433. * But first - it will load the extendible onTemplateLoaded()!
  102434. */
  102435. AbstractViewer.prototype._onTemplateLoaded = function () {
  102436. var _this = this;
  102437. // check if viewer was disposed right after created
  102438. if (this._isDisposed) {
  102439. return Promise.reject("viewer was disposed");
  102440. }
  102441. return this._onTemplatesLoaded().then(function () {
  102442. var autoLoad = typeof _this.configuration.model === 'string' || (_this.configuration.model && _this.configuration.model.url);
  102443. return _this._initEngine().then(function (engine) {
  102444. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  102445. }).then(function () {
  102446. _this._initTelemetryEvents();
  102447. if (autoLoad) {
  102448. return _this.loadModel(_this.configuration.model).catch(function (e) { }).then(function () { return _this.sceneManager.scene; });
  102449. }
  102450. else {
  102451. return _this.sceneManager.scene || _this.sceneManager.initScene(_this.configuration.scene);
  102452. }
  102453. }).then(function () {
  102454. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  102455. }).catch(function (e) {
  102456. babylonjs_1.Tools.Warn(e.toString());
  102457. return _this;
  102458. });
  102459. });
  102460. };
  102461. /**
  102462. * Initialize the engine. Retruns a promise in case async calls are needed.
  102463. *
  102464. * @protected
  102465. * @returns {Promise<Engine>}
  102466. * @memberof Viewer
  102467. */
  102468. AbstractViewer.prototype._initEngine = function () {
  102469. // init custom shaders
  102470. this._injectCustomShaders();
  102471. //let canvasElement = this.templateManager.getCanvas();
  102472. if (!this.canvas) {
  102473. return Promise.reject('Canvas element not found!');
  102474. }
  102475. var config = this.configuration.engine || {};
  102476. // TDO enable further configuration
  102477. // check for webgl2 support, force-disable if needed.
  102478. if (globals_1.viewerGlobals.disableWebGL2Support) {
  102479. config.engineOptions = config.engineOptions || {};
  102480. config.engineOptions.disableWebGL2Support = true;
  102481. }
  102482. this.engine = new babylonjs_1.Engine(this.canvas, !!config.antialiasing, config.engineOptions);
  102483. // Disable manifest checking
  102484. babylonjs_1.Database.IDBStorageEnabled = false;
  102485. if (!config.disableResize) {
  102486. window.addEventListener('resize', this._resize);
  102487. }
  102488. if (this.configuration.engine && this.configuration.engine.adaptiveQuality) {
  102489. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  102490. this.engine.setHardwareScalingLevel(scale);
  102491. }
  102492. // create a new template manager for this viewer
  102493. this.sceneManager = new sceneManager_1.SceneManager(this.engine, this._configurationContainer, this.observablesManager);
  102494. return Promise.resolve(this.engine);
  102495. };
  102496. /**
  102497. * Initialize a model loading. The returned object (a ViewerModel object) will be loaded in the background.
  102498. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  102499. *
  102500. * @param modelConfig model configuration to use when loading the model.
  102501. * @param clearScene should the scene be cleared before loading this model
  102502. * @returns a ViewerModel object that is not yet fully loaded.
  102503. */
  102504. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  102505. var _this = this;
  102506. if (clearScene === void 0) { clearScene = true; }
  102507. var configuration;
  102508. if (typeof modelConfig === 'string') {
  102509. configuration = {
  102510. url: modelConfig
  102511. };
  102512. }
  102513. else if (modelConfig instanceof File) {
  102514. configuration = {
  102515. file: modelConfig,
  102516. root: "file:"
  102517. };
  102518. }
  102519. else {
  102520. configuration = modelConfig;
  102521. }
  102522. if (!configuration.url && !configuration.file) {
  102523. throw new Error("no model provided");
  102524. }
  102525. if (clearScene) {
  102526. this.sceneManager.clearScene(true, false);
  102527. }
  102528. //merge the configuration for future models:
  102529. if (this.configuration.model && typeof this.configuration.model === 'object') {
  102530. var globalConfig = _1.deepmerge({}, this.configuration.model);
  102531. configuration = _1.deepmerge(globalConfig, configuration);
  102532. if (modelConfig instanceof File) {
  102533. configuration.file = modelConfig;
  102534. }
  102535. }
  102536. else {
  102537. this.configuration.model = configuration;
  102538. }
  102539. this._isLoading = true;
  102540. var model = this.modelLoader.load(configuration);
  102541. this.lastUsedLoader = model.loader;
  102542. model.onLoadErrorObservable.add(function (errorObject) {
  102543. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  102544. });
  102545. model.onLoadProgressObservable.add(function (progressEvent) {
  102546. _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  102547. });
  102548. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  102549. model.onLoadedObservable.add(function () {
  102550. _this._isLoading = false;
  102551. });
  102552. return model;
  102553. };
  102554. /**
  102555. * load a model using the provided configuration.
  102556. * This function, as opposed to initModel, will return a promise that resolves when the model is loaded, and rejects with error.
  102557. * If you want to attach to the observables of the model, use initModle instead.
  102558. *
  102559. * @param modelConfig the model configuration or URL to load.
  102560. * @param clearScene Should the scene be cleared before loading the model
  102561. * @returns a Promise the fulfills when the model finished loading successfully.
  102562. */
  102563. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  102564. var _this = this;
  102565. if (clearScene === void 0) { clearScene = true; }
  102566. if (this._isLoading) {
  102567. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  102568. return Promise.reject("another model is curently being loaded.");
  102569. }
  102570. return Promise.resolve(this.sceneManager.scene).then(function (scene) {
  102571. if (!scene)
  102572. return _this.sceneManager.initScene(_this.configuration.scene, _this.configuration.optimizer);
  102573. return scene;
  102574. }).then(function () {
  102575. var model = _this.initModel(modelConfig, clearScene);
  102576. return new Promise(function (resolve, reject) {
  102577. // at this point, configuration.model is an object, not a string
  102578. model.onLoadedObservable.add(function () {
  102579. resolve(model);
  102580. });
  102581. model.onLoadErrorObservable.add(function (error) {
  102582. reject(error);
  102583. });
  102584. });
  102585. });
  102586. };
  102587. AbstractViewer.prototype._initTelemetryEvents = function () {
  102588. var _this = this;
  102589. telemetryManager_1.telemetryManager.broadcast("Engine Capabilities", this.baseId, this.engine.getCaps());
  102590. telemetryManager_1.telemetryManager.broadcast("Platform Details", this.baseId, {
  102591. userAgent: navigator.userAgent,
  102592. platform: navigator.platform
  102593. });
  102594. telemetryManager_1.telemetryManager.flushWebGLErrors(this.engine, this.baseId);
  102595. var trackFPS = function () {
  102596. telemetryManager_1.telemetryManager.broadcast("Current FPS", _this.baseId, { fps: _this.engine.getFps() });
  102597. };
  102598. trackFPS();
  102599. // Track the FPS again after 60 seconds
  102600. this._fpsTimeoutInterval = window.setInterval(trackFPS, 60 * 1000);
  102601. };
  102602. /**
  102603. * Injects all the spectre shader in the babylon shader store
  102604. */
  102605. AbstractViewer.prototype._injectCustomShaders = function () {
  102606. var customShaders = this.configuration.customShaders;
  102607. // Inject all the spectre shader in the babylon shader store.
  102608. if (!customShaders) {
  102609. return;
  102610. }
  102611. if (customShaders.shaders) {
  102612. Object.keys(customShaders.shaders).forEach(function (key) {
  102613. // typescript considers a callback "unsafe", so... '!'
  102614. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  102615. });
  102616. }
  102617. if (customShaders.includes) {
  102618. Object.keys(customShaders.includes).forEach(function (key) {
  102619. // typescript considers a callback "unsafe", so... '!'
  102620. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  102621. });
  102622. }
  102623. };
  102624. return AbstractViewer;
  102625. }());
  102626. exports.AbstractViewer = AbstractViewer;
  102627. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3ZpZXdlci92aWV3ZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpREFBZ0Q7QUFDaEQseURBQXdEO0FBQ3hELGtEQUE4RDtBQUM5RCx1Q0FBbWdCO0FBS25nQixxREFBb0Q7QUFFcEQsb0RBQXlEO0FBRXpELGlFQUFnRTtBQUNoRSwrQkFBdUM7QUFDdkMscUVBQW9FO0FBQ3BFLGtGQUFpRjtBQUNqRixpRUFBZ0U7QUFFaEU7OztHQUdHO0FBQ0g7SUFnSkksd0JBQW1CLGdCQUE2QixFQUFFLG9CQUE4QztRQUE5QyxxQ0FBQSxFQUFBLHlCQUE4QztRQUFoRyxpQkFzQ0M7UUF0Q2tCLHFCQUFnQixHQUFoQixnQkFBZ0IsQ0FBYTtRQXJIaEQ7O1dBRUc7UUFDSSxrQkFBYSxHQUFZLElBQUksQ0FBQztRQXdGckM7O1dBRUc7UUFDTyxnQkFBVyxHQUFZLEtBQUssQ0FBQztRQTZHdkM7O1dBRUc7UUFDTyxZQUFPLEdBQUc7WUFDaEIsc0NBQXNDO1lBQ3RDLElBQUksQ0FBQyxLQUFJLENBQUMsYUFBYSxFQUFFLEVBQUU7Z0JBQ3ZCLE9BQU87YUFDVjtZQUVELElBQUksS0FBSSxDQUFDLE1BQU0sQ0FBQyxXQUFXLElBQUksQ0FBQyxJQUFJLEtBQUksQ0FBQyxNQUFNLENBQUMsWUF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ztJQUN2RSxDQUFDO0lBRUQ7O09BRUc7SUFDTyw2Q0FBb0IsR0FBOUI7UUFDSSxJQUFJLGFBQWEsR0FBRyxJQUFJLENBQUMsYUFBYSxDQUFDLGFBQWEsQ0FBQztRQUNyRCw2REFBNkQ7UUFDN0QsSUFBSSxDQUFDLGFBQWEsRUFBRTtZQUNoQixPQUFPO1NBQ1Y7UUFDRCxJQUFJLGFBQWEsQ0FBQyxPQUFPLEVBQUU7WUFDdkIsTUFBTSxDQUFDLElBQUksQ0FBQyxhQUFhLENBQUMsT0FBTyxDQUFDLENBQUMsT0FBTyxDQUFDLFVBQUEsR0FBRztnQkFDMUMsc0RBQXNEO2dCQUN0RCxrQkFBTSxDQUFDLFlBQVksQ0FBQyxHQUFHLENBQUMsR0FBRyxhQUFjLENBQUMsT0FBUSxDQUFDLEdBQUcsQ0FBQyxDQUFDO1lBQzVELENBQUMsQ0FBQyxDQUFDO1NBQ047UUFDRCxJQUFJLGFBQWEsQ0FBQyxRQUFRLEVBQUU7WUFDeEIsTUFBTSxDQUFDLElBQUksQ0FBQyxhQUFhLENBQUMsUUFBUSxDQUFDLENBQUMsT0FBTyxDQUFDLFVBQUEsR0FBRztnQkFDM0Msc0RBQXNEO2dCQUN0RCxrQkFBTSxDQUFDLG9CQUFvQixDQUFDLEdBQUcsQ0FBQyxHQUFHLGFBQWMsQ0FBQyxRQUFTLENBQUMsR0FBRyxDQUFDLENBQUM7WUFDckUsQ0FBQyxDQUFDLENBQUM7U0FDTjtJQUNMLENBQUM7SUFDTCxxQkFBQztBQUFELENBQUMsQUE5bkJELElBOG5CQztBQTluQnFCLHdDQUFjIn0=
  102628. /***/ }),
  102629. /* 10 */
  102630. /***/ (function(module, exports, __webpack_require__) {
  102631. "use strict";
  102632. function __export(m) {
  102633. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  102634. }
  102635. Object.defineProperty(exports, "__esModule", { value: true });
  102636. __export(__webpack_require__(11));
  102637. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7OztBQUFBLHFDQUFnQyJ9
  102638. /***/ }),
  102639. /* 11 */
  102640. /***/ (function(module, exports, __webpack_require__) {
  102641. "use strict";
  102642. Object.defineProperty(exports, "__esModule", { value: true });
  102643. function getConfigurationKey(key, configObject) {
  102644. var splits = key.split('.');
  102645. if (splits.length === 0 || !configObject)
  102646. return;
  102647. else if (splits.length === 1) {
  102648. if (configObject[key] !== undefined) {
  102649. return configObject[key];
  102650. }
  102651. }
  102652. else {
  102653. var firstKey = splits.shift();
  102654. return getConfigurationKey(splits.join("."), configObject[firstKey]);
  102655. }
  102656. }
  102657. exports.getConfigurationKey = getConfigurationKey;
  102658. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2NvbmZpZ3VyYXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFHQSw2QkFBb0MsR0FBVyxFQUFFLFlBQWlCO0lBQzlELElBQUksTUFBTSxHQUFHLEdBQUcsQ0FBQyxLQUFLLENBQUMsR0FBRyxDQUFDLENBQUM7SUFFNUIsSUFBSSxNQUFNLENBQUMsTUFBTSxLQUFLLENBQUMsSUFBSSxDQUFDLFlBQVk7UUFBRSxPQUFPO1NBQzVDLElBQUksTUFBTSxDQUFDLE1BQU0sS0FBSyxDQUFDLEVBQUU7UUFDMUIsSUFBSSxZQUFZLENBQUMsR0FBRyxDQUFDLEtBQUssU0FBUyxFQUFFO1lBQ2pDLE9BQU8sWUFBWSxDQUFDLEdBQUcsQ0FBQyxDQUFDO1NBQzVCO0tBQ0o7U0FBTTtRQUNILElBQUksUUFBUSxHQUFHLE1BQU0sQ0FBQyxLQUFLLEVBQUUsQ0FBQztRQUM5QixPQUFPLG1CQUFtQixDQUFDLE1BQU0sQ0FBQyxJQUFJLENBQUMsR0FBRyxDQUFDLEVBQUUsWUFBWSxDQUFDLFFBQVMsQ0FBQyxDQUFDLENBQUE7S0FDeEU7QUFDTCxDQUFDO0FBWkQsa0RBWUMifQ==
  102659. /***/ }),
  102660. /* 12 */
  102661. /***/ (function(module, exports, __webpack_require__) {
  102662. "use strict";
  102663. Object.defineProperty(exports, "__esModule", { value: true });
  102664. var babylonjs_1 = __webpack_require__(0);
  102665. /**
  102666. * A minimal WebGL cubemap descriptor
  102667. */
  102668. var TextureCube = /** @class */ (function () {
  102669. /**
  102670. * constructor
  102671. * @param internalFormat WebGL pixel format for the texture on the GPU
  102672. * @param type WebGL pixel type of the supplied data and texture on the GPU
  102673. * @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
  102674. */
  102675. function TextureCube(internalFormat, type, source) {
  102676. if (source === void 0) { source = []; }
  102677. this.internalFormat = internalFormat;
  102678. this.type = type;
  102679. this.source = source;
  102680. }
  102681. Object.defineProperty(TextureCube.prototype, "Width", {
  102682. /**
  102683. * Returns the width of a face of the texture or 0 if not available
  102684. */
  102685. get: function () {
  102686. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].width : 0;
  102687. },
  102688. enumerable: true,
  102689. configurable: true
  102690. });
  102691. Object.defineProperty(TextureCube.prototype, "Height", {
  102692. /**
  102693. * Returns the height of a face of the texture or 0 if not available
  102694. */
  102695. get: function () {
  102696. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].height : 0;
  102697. },
  102698. enumerable: true,
  102699. configurable: true
  102700. });
  102701. return TextureCube;
  102702. }());
  102703. exports.TextureCube = TextureCube;
  102704. /**
  102705. * A static class providing methods to aid working with Bablyon textures.
  102706. */
  102707. var TextureUtils = /** @class */ (function () {
  102708. function TextureUtils() {
  102709. }
  102710. /**
  102711. * Returns a BabylonCubeTexture instance from a Spectre texture cube, subject to sampling parameters.
  102712. * If such a texture has already been requested in the past, this texture will be returned, otherwise a new one will be created.
  102713. * The advantage of this is to enable working with texture objects without the need to initialize on the GPU until desired.
  102714. * @param scene A Babylon Scene instance
  102715. * @param textureCube A Spectre TextureCube object
  102716. * @param parameters WebGL texture sampling parameters
  102717. * @param automaticMipmaps Pass true to enable automatic mipmap generation where possible (requires power of images)
  102718. * @param environment Specifies that the texture will be used as an environment
  102719. * @param singleLod Specifies that the texture will be a singleLod (for environment)
  102720. * @return Babylon cube texture
  102721. */
  102722. TextureUtils.GetBabylonCubeTexture = function (scene, textureCube, automaticMipmaps, environment, singleLod) {
  102723. if (environment === void 0) { environment = false; }
  102724. if (singleLod === void 0) { singleLod = false; }
  102725. if (!textureCube)
  102726. throw new Error("no texture cube provided");
  102727. var parameters;
  102728. if (environment) {
  102729. parameters = singleLod ? TextureUtils._EnvironmentSingleMipSampling : TextureUtils._EnvironmentSampling;
  102730. }
  102731. else {
  102732. parameters = {
  102733. magFilter: 9728 /* NEAREST */,
  102734. minFilter: 9728 /* NEAREST */,
  102735. wrapS: 33071 /* CLAMP_TO_EDGE */,
  102736. wrapT: 33071 /* CLAMP_TO_EDGE */
  102737. };
  102738. }
  102739. var key = TextureUtils.BabylonTextureKeyPrefix + parameters.magFilter + '' + parameters.minFilter + '' + parameters.wrapS + '' + parameters.wrapT;
  102740. var babylonTexture = textureCube[key];
  102741. if (!babylonTexture) {
  102742. //initialize babylon texture
  102743. babylonTexture = new babylonjs_1.CubeTexture('', scene);
  102744. if (environment) {
  102745. babylonTexture.lodGenerationOffset = TextureUtils.EnvironmentLODOffset;
  102746. babylonTexture.lodGenerationScale = TextureUtils.EnvironmentLODScale;
  102747. }
  102748. babylonTexture.gammaSpace = false;
  102749. var internalTexture_1 = new babylonjs_1.InternalTexture(scene.getEngine(), babylonjs_1.InternalTexture.DATASOURCE_CUBERAW);
  102750. var glTexture_1 = internalTexture_1._webGLTexture;
  102751. //babylon properties
  102752. internalTexture_1.isCube = true;
  102753. internalTexture_1.generateMipMaps = false;
  102754. babylonTexture._texture = internalTexture_1;
  102755. TextureUtils.ApplySamplingParameters(babylonTexture, parameters);
  102756. var maxMipLevel_1 = automaticMipmaps ? 0 : textureCube.source.length - 1;
  102757. var texturesUploaded_1 = 0;
  102758. var textureComplete = function () {
  102759. return texturesUploaded_1 === ((maxMipLevel_1 + 1) * 6);
  102760. };
  102761. var uploadFace = function (i, level, face) {
  102762. if (!glTexture_1)
  102763. return;
  102764. if (i === 0 && level === 0) {
  102765. internalTexture_1.width = face.width;
  102766. internalTexture_1.height = face.height;
  102767. }
  102768. var gl = (scene.getEngine())._gl;
  102769. gl.bindTexture(gl.TEXTURE_CUBE_MAP, glTexture_1);
  102770. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  102771. if (face instanceof HTMLElement || face instanceof ImageData) {
  102772. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureCube.internalFormat, textureCube.type, face);
  102773. }
  102774. else {
  102775. var textureData = face;
  102776. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureData.width, textureData.height, 0, textureData.format, textureCube.type, textureData.data);
  102777. }
  102778. texturesUploaded_1++;
  102779. if (textureComplete()) {
  102780. //generate mipmaps
  102781. if (automaticMipmaps) {
  102782. var w = face.width;
  102783. var h = face.height;
  102784. var isPot = (((w !== 0) && (w & (w - 1))) === 0) && (((h !== 0) && (h & (h - 1))) === 0);
  102785. if (isPot) {
  102786. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  102787. }
  102788. }
  102789. // Upload Separate lods in case there is no support for texture lod.
  102790. if (environment && !scene.getEngine().getCaps().textureLOD && !singleLod) {
  102791. var mipSlices = 3;
  102792. for (var i_1 = 0; i_1 < mipSlices; i_1++) {
  102793. var lodKey = TextureUtils.BabylonTextureKeyPrefix + 'lod' + i_1;
  102794. var lod = textureCube[lodKey];
  102795. //initialize lod texture if it doesn't already exist
  102796. if (lod == null && textureCube.Width) {
  102797. //compute LOD from even spacing in smoothness (matching shader calculation)
  102798. var smoothness = i_1 / (mipSlices - 1);
  102799. var roughness = 1 - smoothness;
  102800. var kMinimumVariance = 0.0005;
  102801. var alphaG = roughness * roughness + kMinimumVariance;
  102802. var microsurfaceAverageSlopeTexels = alphaG * textureCube.Width;
  102803. var environmentSpecularLOD = TextureUtils.EnvironmentLODScale * (babylonjs_1.Scalar.Log2(microsurfaceAverageSlopeTexels)) + TextureUtils.EnvironmentLODOffset;
  102804. var maxLODIndex = textureCube.source.length - 1;
  102805. var mipmapIndex = Math.min(Math.max(Math.round(environmentSpecularLOD), 0), maxLODIndex);
  102806. lod = TextureUtils.GetBabylonCubeTexture(scene, new TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */, [textureCube.source[mipmapIndex]]), false, true, true);
  102807. if (i_1 === 0) {
  102808. internalTexture_1._lodTextureLow = lod;
  102809. }
  102810. else if (i_1 === 1) {
  102811. internalTexture_1._lodTextureMid = lod;
  102812. }
  102813. else {
  102814. internalTexture_1._lodTextureHigh = lod;
  102815. }
  102816. textureCube[lodKey] = lod;
  102817. }
  102818. }
  102819. }
  102820. internalTexture_1.isReady = true;
  102821. }
  102822. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  102823. scene.getEngine().resetTextureCache();
  102824. };
  102825. var _loop_1 = function (i) {
  102826. var faces = textureCube.source[i];
  102827. var _loop_2 = function (j) {
  102828. var face = faces[j];
  102829. if (face instanceof HTMLImageElement && !face.complete) {
  102830. face.addEventListener('load', function () {
  102831. uploadFace(j, i, face);
  102832. }, false);
  102833. }
  102834. else {
  102835. uploadFace(j, i, face);
  102836. }
  102837. };
  102838. for (var j = 0; j < faces.length; j++) {
  102839. _loop_2(j);
  102840. }
  102841. };
  102842. for (var i = 0; i <= maxMipLevel_1; i++) {
  102843. _loop_1(i);
  102844. }
  102845. scene.getEngine().resetTextureCache();
  102846. babylonTexture.isReady = function () {
  102847. return textureComplete();
  102848. };
  102849. textureCube[key] = babylonTexture;
  102850. }
  102851. return babylonTexture;
  102852. };
  102853. /**
  102854. * Applies Spectre SamplingParameters to a Babylon texture by directly setting texture parameters on the internal WebGLTexture as well as setting Babylon fields
  102855. * @param babylonTexture Babylon texture to apply texture to (requires the Babylon texture has an initialize _texture field)
  102856. * @param parameters Spectre SamplingParameters to apply
  102857. */
  102858. TextureUtils.ApplySamplingParameters = function (babylonTexture, parameters) {
  102859. var scene = babylonTexture.getScene();
  102860. if (!scene)
  102861. return;
  102862. var gl = (scene.getEngine())._gl;
  102863. var target = babylonTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  102864. var internalTexture = babylonTexture._texture;
  102865. if (!internalTexture)
  102866. return;
  102867. var glTexture = internalTexture._webGLTexture;
  102868. gl.bindTexture(target, glTexture);
  102869. if (parameters.magFilter != null)
  102870. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, parameters.magFilter);
  102871. if (parameters.minFilter != null)
  102872. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, parameters.minFilter);
  102873. if (parameters.wrapS != null)
  102874. gl.texParameteri(target, gl.TEXTURE_WRAP_S, parameters.wrapS);
  102875. if (parameters.wrapT != null)
  102876. gl.texParameteri(target, gl.TEXTURE_WRAP_T, parameters.wrapT);
  102877. //set babylon wrap modes from sampling parameter
  102878. switch (parameters.wrapS) {
  102879. case 10497 /* REPEAT */:
  102880. babylonTexture.wrapU = babylonjs_1.Texture.WRAP_ADDRESSMODE;
  102881. break;
  102882. case 33071 /* CLAMP_TO_EDGE */:
  102883. babylonTexture.wrapU = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  102884. break;
  102885. case 33648 /* MIRRORED_REPEAT */:
  102886. babylonTexture.wrapU = babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  102887. break;
  102888. default: babylonTexture.wrapU = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  102889. }
  102890. switch (parameters.wrapT) {
  102891. case 10497 /* REPEAT */:
  102892. babylonTexture.wrapV = babylonjs_1.Texture.WRAP_ADDRESSMODE;
  102893. break;
  102894. case 33071 /* CLAMP_TO_EDGE */:
  102895. babylonTexture.wrapV = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  102896. break;
  102897. case 33648 /* MIRRORED_REPEAT */:
  102898. babylonTexture.wrapV = babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  102899. break;
  102900. default: babylonTexture.wrapV = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  102901. }
  102902. if (parameters.maxAnisotropy != null && parameters.maxAnisotropy > 1) {
  102903. var anisotropicExt = gl.getExtension('EXT_texture_filter_anisotropic');
  102904. if (anisotropicExt) {
  102905. var maxAnisotropicSamples = gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  102906. var maxAnisotropy = Math.min(parameters.maxAnisotropy, maxAnisotropicSamples);
  102907. gl.texParameterf(target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropy);
  102908. babylonTexture.anisotropicFilteringLevel = maxAnisotropy;
  102909. }
  102910. }
  102911. gl.bindTexture(target, null);
  102912. scene.getEngine().resetTextureCache();
  102913. };
  102914. /**
  102915. * A prefix used when storing a babylon texture object reference on a Spectre texture object
  102916. */
  102917. TextureUtils.BabylonTextureKeyPrefix = '__babylonTexture_';
  102918. /**
  102919. * Controls anisotropic filtering for deserialized textures.
  102920. */
  102921. TextureUtils.MaxAnisotropy = 4;
  102922. TextureUtils._EnvironmentSampling = {
  102923. magFilter: 9729 /* LINEAR */,
  102924. minFilter: 9987 /* LINEAR_MIPMAP_LINEAR */,
  102925. wrapS: 33071 /* CLAMP_TO_EDGE */,
  102926. wrapT: 33071 /* CLAMP_TO_EDGE */,
  102927. maxAnisotropy: 1
  102928. };
  102929. TextureUtils._EnvironmentSingleMipSampling = {
  102930. magFilter: 9729 /* LINEAR */,
  102931. minFilter: 9729 /* LINEAR */,
  102932. wrapS: 33071 /* CLAMP_TO_EDGE */,
  102933. wrapT: 33071 /* CLAMP_TO_EDGE */,
  102934. maxAnisotropy: 1
  102935. };
  102936. //from "/Internal/Lighting.EnvironmentFilterScale" in Engine/*/Configuration.cpp
  102937. /**
  102938. * Environment preprocessing dedicated value (Internal Use or Advanced only).
  102939. */
  102940. TextureUtils.EnvironmentLODScale = 0.8;
  102941. /**
  102942. * Environment preprocessing dedicated value (Internal Use or Advanced only)..
  102943. */
  102944. TextureUtils.EnvironmentLODOffset = 1.0;
  102945. return TextureUtils;
  102946. }());
  102947. exports.TextureUtils = TextureUtils;
  102948. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGV4dHVyZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9sYWJzL3RleHR1cmUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBOEY7QUFrSTlGOztHQUVHO0FBQ0g7SUFnQkk7Ozs7O09BS0c7SUFDSCxxQkFBbUIsY0FBMkIsRUFBUyxJQUFlLEVBQVMsTUFBd0I7UUFBeEIsdUJBQUEsRUFBQSxXQUF3QjtRQUFwRixtQkFBYyxHQUFkLGNBQWMsQ0FBYTtRQUFTLFNBQUksR0FBSixJQUFJLENBQVc7UUFBUyxXQUFNLEdBQU4sTUFBTSxDQUFrQjtJQUFJLENBQUM7SUFqQjVHLHNCQUFXLDhCQUFLO1FBSGhCOztXQUVHO2FBQ0g7WUFDSSxPQUFPLENBQUMsSUFBSSxDQUFDLE1BQU0sSUFBSSxJQUFJLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxJQUFJLElBQUksQ0FBQyxNQUFNLENBQUMsQ0FBQyxDQUFDLENBQUMsQ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FDLENBQUM7SUF1TmpCLGlDQUFvQixHQUF1QjtRQUN0RCxTQUFTLG1CQUF5QjtRQUNsQyxTQUFTLGlDQUF1QztRQUNoRCxLQUFLLDJCQUErQjtRQUNwQyxLQUFLLDJCQUErQjtRQUNwQyxhQUFhLEVBQUUsQ0FBQztLQUNuQixDQUFDO0lBRWEsMENBQTZCLEdBQXVCO1FBQy9ELFNBQVMsbUJBQXlCO1FBQ2xDLFNBQVMsbUJBQXlCO1FBQ2xDLEtBQUssMkJBQStCO1FBQ3BDLEtBQUssMkJBQStCO1FBQ3BDLGFBQWEsRUFBRSxDQUFDO0tBQ25CLENBQUM7SUFFRixnRkFBZ0Y7SUFDaEY7O09BRUc7SUFDVyxnQ0FBbUIsR0FBRyxHQUFHLENBQUM7SUFDeEM7O09BRUc7SUFDVyxpQ0FBb0IsR0FBRyxHQUFHLENBQUM7SUFDN0MsbUJBQUM7Q0FBQSxBQTFQRCxJQTBQQztBQTFQWSxvQ0FBWSJ9
  102949. /***/ }),
  102950. /* 13 */
  102951. /***/ (function(module, exports, __webpack_require__) {
  102952. "use strict";
  102953. Object.defineProperty(exports, "__esModule", { value: true });
  102954. var babylonjs_1 = __webpack_require__(0);
  102955. var babylonjs_loaders_1 = __webpack_require__(14);
  102956. var viewerModel_1 = __webpack_require__(5);
  102957. var _1 = __webpack_require__(54);
  102958. /**
  102959. * An instance of the class is in charge of loading the model correctly.
  102960. * This class will continously be expended with tasks required from the specific loaders Babylon has.
  102961. *
  102962. * A Model loader is unique per (Abstract)Viewer. It is being generated by the viewer
  102963. */
  102964. var ModelLoader = /** @class */ (function () {
  102965. /**
  102966. * Create a new Model loader
  102967. * @param _viewer the viewer using this model loader
  102968. */
  102969. function ModelLoader(_observablesManager, _configurationContainer) {
  102970. this._observablesManager = _observablesManager;
  102971. this._configurationContainer = _configurationContainer;
  102972. this._disposed = false;
  102973. this._loaders = [];
  102974. this._loadId = 0;
  102975. this._plugins = [];
  102976. }
  102977. /**
  102978. * Adds a new plugin to the loader process.
  102979. *
  102980. * @param plugin the plugin name or the plugin itself
  102981. */
  102982. ModelLoader.prototype.addPlugin = function (plugin) {
  102983. var actualPlugin = {};
  102984. if (typeof plugin === 'string') {
  102985. var loadedPlugin = _1.getLoaderPluginByName(plugin);
  102986. if (loadedPlugin) {
  102987. actualPlugin = loadedPlugin;
  102988. }
  102989. }
  102990. else {
  102991. actualPlugin = plugin;
  102992. }
  102993. if (actualPlugin && this._plugins.indexOf(actualPlugin) === -1) {
  102994. this._plugins.push(actualPlugin);
  102995. }
  102996. };
  102997. /**
  102998. * Load a model using predefined configuration
  102999. * @param modelConfiguration the modelConfiguration to use to load the model
  103000. */
  103001. ModelLoader.prototype.load = function (modelConfiguration) {
  103002. var _this = this;
  103003. var model = new viewerModel_1.ViewerModel(this._observablesManager, modelConfiguration);
  103004. model.loadId = this._loadId++;
  103005. if (!modelConfiguration.url) {
  103006. model.state = viewerModel_1.ModelState.ERROR;
  103007. babylonjs_1.Tools.Error("No URL provided");
  103008. return model;
  103009. }
  103010. var base;
  103011. var filename;
  103012. if (modelConfiguration.file) {
  103013. base = "file:";
  103014. filename = modelConfiguration.file;
  103015. }
  103016. else {
  103017. filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  103018. base = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  103019. }
  103020. var plugin = modelConfiguration.loader;
  103021. var scene = model.rootMesh.getScene();
  103022. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  103023. meshes.forEach(function (mesh) {
  103024. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  103025. model.addMesh(mesh);
  103026. });
  103027. model.particleSystems = particleSystems;
  103028. model.skeletons = skeletons;
  103029. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  103030. var animationGroup = animationGroups_1[_i];
  103031. model.addAnimationGroup(animationGroup);
  103032. }
  103033. _this._checkAndRun("onLoaded", model);
  103034. scene.executeWhenReady(function () {
  103035. model.onLoadedObservable.notifyObservers(model);
  103036. });
  103037. }, function (progressEvent) {
  103038. _this._checkAndRun("onProgress", progressEvent);
  103039. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  103040. }, function (scene, m, exception) {
  103041. model.state = viewerModel_1.ModelState.ERROR;
  103042. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  103043. _this._checkAndRun("onError", m, exception);
  103044. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  103045. }, plugin);
  103046. if (model.loader.name === "gltf") {
  103047. var gltfLoader_1 = model.loader;
  103048. gltfLoader_1.animationStartMode = babylonjs_loaders_1.GLTFLoaderAnimationStartMode.NONE;
  103049. gltfLoader_1.compileMaterials = true;
  103050. if (!modelConfiguration.file) {
  103051. gltfLoader_1.rewriteRootURL = function (rootURL, responseURL) {
  103052. return modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(responseURL || modelConfiguration.url || '');
  103053. };
  103054. }
  103055. // if ground is set to "mirror":
  103056. if (this._configurationContainer
  103057. && this._configurationContainer.configuration
  103058. && this._configurationContainer.configuration.ground
  103059. && typeof this._configurationContainer.configuration.ground === 'object'
  103060. && this._configurationContainer.configuration.ground.mirror) {
  103061. gltfLoader_1.useClipPlane = true;
  103062. }
  103063. Object.keys(gltfLoader_1).filter(function (name) { return name.indexOf('on') === 0 && name.indexOf('Observable') !== -1; }).forEach(function (functionName) {
  103064. gltfLoader_1[functionName].add(function (payload) {
  103065. _this._checkAndRun(functionName.replace("Observable", ''), payload);
  103066. });
  103067. });
  103068. gltfLoader_1.onParsedObservable.add(function (data) {
  103069. if (data && data.json && data.json['asset']) {
  103070. model.loadInfo = data.json['asset'];
  103071. }
  103072. });
  103073. gltfLoader_1.onCompleteObservable.add(function () {
  103074. model.loaderDone = true;
  103075. });
  103076. }
  103077. else {
  103078. model.loaderDone = true;
  103079. }
  103080. this._checkAndRun("onInit", model.loader, model);
  103081. this._loaders.push(model.loader);
  103082. return model;
  103083. };
  103084. ModelLoader.prototype.cancelLoad = function (model) {
  103085. var loader = model.loader || this._loaders[model.loadId];
  103086. // ATM only available in the GLTF Loader
  103087. if (loader && loader.name === "gltf") {
  103088. var gltfLoader = loader;
  103089. gltfLoader.dispose();
  103090. model.state = viewerModel_1.ModelState.CANCELED;
  103091. }
  103092. else {
  103093. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  103094. }
  103095. };
  103096. /**
  103097. * dispose the model loader.
  103098. * If loaders are registered and are in the middle of loading, they will be disposed and the request(s) will be cancelled.
  103099. */
  103100. ModelLoader.prototype.dispose = function () {
  103101. this._loaders.forEach(function (loader) {
  103102. if (loader.name === "gltf") {
  103103. loader.dispose();
  103104. }
  103105. });
  103106. this._loaders.length = 0;
  103107. this._disposed = true;
  103108. };
  103109. ModelLoader.prototype._checkAndRun = function (functionName) {
  103110. var _this = this;
  103111. var payload = [];
  103112. for (var _i = 1; _i < arguments.length; _i++) {
  103113. payload[_i - 1] = arguments[_i];
  103114. }
  103115. if (this._disposed)
  103116. return;
  103117. this._plugins.filter(function (p) { return p[functionName]; }).forEach(function (plugin) {
  103118. try {
  103119. plugin[functionName].apply(_this, payload);
  103120. }
  103121. catch (e) { }
  103122. });
  103123. };
  103124. return ModelLoader;
  103125. }());
  103126. exports.ModelLoader = ModelLoader;
  103127. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kZWxMb2FkZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbG9hZGVyL21vZGVsTG9hZGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQWtHO0FBQ2xHLHVEQUFpRjtBQUdqRixvREFBK0Q7QUFDL0QsK0JBQXlGO0FBSXpGOzs7OztHQUtHO0FBQ0g7SUFTSTs7O09BR0c7SU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QjtRQUF6QyxpQkFPQztRQVAwQyxpQkFBc0I7YUFBdEIsVUFBc0IsRUFBdEIscUJBQXNCLEVBQXRCLElBQXNCO1lBQXRCLGdDQUFzQjs7UUFDN0QsSUFBSSxJQUFJLENBQUMsU0FBUztZQUFFLE9BQU87UUFDM0IsSUFBSSxDQUFDLFFBQVEsQ0FBQyxNQUFNLENBQUMsVUFBQSxDQUFDLElBQUksT0FBQSxDQUFDLENBQUMsWUFBWSxDQUFDLEVBQWYsQ0FBZSxDQUFDLENBQUMsT0FBTyxDQUFDLFVBQUEsTUFBTTtZQUNyRCxJQUFJO2dCQUNBLE1BQU0sQ0FBQyxZQUFZLENBQUMsQ0FBQyxLQUFLLENBQUMsS0FBSSxFQUFFLE9BQU8sQ0FBQyxDQUFDO2FBQzdDO1lBQUMsT0FBTyxDQUFDLEVBQUUsR0FBRztRQUNuQixDQUFDLENBQUMsQ0FBQTtJQUNOLENBQUM7SUFDTCxrQkFBQztBQUFELENBQUMsQUFoTEQsSUFnTEM7QUFoTFksa0NBQVcifQ==
  103128. /***/ }),
  103129. /* 14 */
  103130. /***/ (function(module, exports, __webpack_require__) {
  103131. (function universalModuleDefinition(root, factory) {
  103132. var amdDependencies = [];
  103133. var BABYLON = root.BABYLON || this.BABYLON;
  103134. if(true) {
  103135. BABYLON = BABYLON || __webpack_require__(0);
  103136. module.exports = factory(BABYLON);
  103137. } else if(typeof define === 'function' && define.amd) {
  103138. amdDependencies.push("babylonjs");
  103139. define("babylonjs-loaders", amdDependencies, factory);
  103140. } else if(typeof exports === 'object') {
  103141. BABYLON = BABYLON || require("babylonjs");
  103142. exports["babylonjs-loaders"] = factory(BABYLON);
  103143. } else {
  103144. root["BABYLON"] = factory(BABYLON);
  103145. }
  103146. })(this, function(BABYLON) {
  103147. BABYLON = BABYLON || this.BABYLON;
  103148. 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};
  103149. 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)}}();
  103150. var BABYLON;
  103151. (function (BABYLON) {
  103152. var STLFileLoader = /** @class */ (function () {
  103153. function STLFileLoader() {
  103154. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  103155. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  103156. 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;
  103157. 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;
  103158. this.name = "stl";
  103159. // force data to come in as an ArrayBuffer
  103160. // we'll convert to string if it looks like it's an ASCII .stl
  103161. this.extensions = {
  103162. ".stl": { isBinary: true },
  103163. };
  103164. }
  103165. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  103166. var matches;
  103167. if (this.isBinary(data)) {
  103168. // binary .stl
  103169. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  103170. this.parseBinary(babylonMesh, data);
  103171. if (meshes) {
  103172. meshes.push(babylonMesh);
  103173. }
  103174. return true;
  103175. }
  103176. // ASCII .stl
  103177. // convert to string
  103178. var array_buffer = new Uint8Array(data);
  103179. var str = '';
  103180. for (var i = 0; i < data.byteLength; i++) {
  103181. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  103182. }
  103183. data = str;
  103184. while (matches = this.solidPattern.exec(data)) {
  103185. var meshName = matches[1];
  103186. var meshNameFromEnd = matches[3];
  103187. if (meshName != meshNameFromEnd) {
  103188. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  103189. return false;
  103190. }
  103191. // check meshesNames
  103192. if (meshesNames && meshName) {
  103193. if (meshesNames instanceof Array) {
  103194. if (!meshesNames.indexOf(meshName)) {
  103195. continue;
  103196. }
  103197. }
  103198. else {
  103199. if (meshName !== meshesNames) {
  103200. continue;
  103201. }
  103202. }
  103203. }
  103204. // stl mesh name can be empty as well
  103205. meshName = meshName || "stlmesh";
  103206. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  103207. this.parseASCII(babylonMesh, matches[2]);
  103208. if (meshes) {
  103209. meshes.push(babylonMesh);
  103210. }
  103211. }
  103212. return true;
  103213. };
  103214. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  103215. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  103216. if (result) {
  103217. scene.createDefaultCameraOrLight();
  103218. }
  103219. return result;
  103220. };
  103221. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  103222. var container = new BABYLON.AssetContainer(scene);
  103223. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  103224. container.removeAllFromScene();
  103225. return container;
  103226. };
  103227. STLFileLoader.prototype.isBinary = function (data) {
  103228. // check if file size is correct for binary stl
  103229. var faceSize, nFaces, reader;
  103230. reader = new DataView(data);
  103231. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  103232. nFaces = reader.getUint32(80, true);
  103233. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  103234. return true;
  103235. }
  103236. // check characters higher than ASCII to confirm binary
  103237. var fileLength = reader.byteLength;
  103238. for (var index = 0; index < fileLength; index++) {
  103239. if (reader.getUint8(index) > 127) {
  103240. return true;
  103241. }
  103242. }
  103243. return false;
  103244. };
  103245. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  103246. var reader = new DataView(data);
  103247. var faces = reader.getUint32(80, true);
  103248. var dataOffset = 84;
  103249. var faceLength = 12 * 4 + 2;
  103250. var offset = 0;
  103251. var positions = new Float32Array(faces * 3 * 3);
  103252. var normals = new Float32Array(faces * 3 * 3);
  103253. var indices = new Uint32Array(faces * 3);
  103254. var indicesCount = 0;
  103255. for (var face = 0; face < faces; face++) {
  103256. var start = dataOffset + face * faceLength;
  103257. var normalX = reader.getFloat32(start, true);
  103258. var normalY = reader.getFloat32(start + 4, true);
  103259. var normalZ = reader.getFloat32(start + 8, true);
  103260. for (var i = 1; i <= 3; i++) {
  103261. var vertexstart = start + i * 12;
  103262. // ordering is intentional to match ascii import
  103263. positions[offset] = reader.getFloat32(vertexstart, true);
  103264. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  103265. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  103266. normals[offset] = normalX;
  103267. normals[offset + 2] = normalY;
  103268. normals[offset + 1] = normalZ;
  103269. offset += 3;
  103270. }
  103271. indices[indicesCount] = indicesCount++;
  103272. indices[indicesCount] = indicesCount++;
  103273. indices[indicesCount] = indicesCount++;
  103274. }
  103275. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  103276. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  103277. mesh.setIndices(indices);
  103278. mesh.computeWorldMatrix(true);
  103279. };
  103280. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  103281. var positions = [];
  103282. var normals = [];
  103283. var indices = [];
  103284. var indicesCount = 0;
  103285. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  103286. var matches;
  103287. while (matches = this.facetsPattern.exec(solidData)) {
  103288. var facet = matches[1];
  103289. //one normal per face
  103290. var normalMatches = this.normalPattern.exec(facet);
  103291. this.normalPattern.lastIndex = 0;
  103292. if (!normalMatches) {
  103293. continue;
  103294. }
  103295. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  103296. var vertexMatch;
  103297. while (vertexMatch = this.vertexPattern.exec(facet)) {
  103298. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  103299. normals.push(normal[0], normal[1], normal[2]);
  103300. }
  103301. indices.push(indicesCount++, indicesCount++, indicesCount++);
  103302. this.vertexPattern.lastIndex = 0;
  103303. }
  103304. this.facetsPattern.lastIndex = 0;
  103305. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  103306. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  103307. mesh.setIndices(indices);
  103308. mesh.computeWorldMatrix(true);
  103309. };
  103310. return STLFileLoader;
  103311. }());
  103312. BABYLON.STLFileLoader = STLFileLoader;
  103313. if (BABYLON.SceneLoader) {
  103314. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  103315. }
  103316. })(BABYLON || (BABYLON = {}));
  103317. //# sourceMappingURL=babylon.stlFileLoader.js.map
  103318. var BABYLON;
  103319. (function (BABYLON) {
  103320. /**
  103321. * Class reading and parsing the MTL file bundled with the obj file.
  103322. */
  103323. var MTLFileLoader = /** @class */ (function () {
  103324. function MTLFileLoader() {
  103325. // All material loaded from the mtl will be set here
  103326. this.materials = [];
  103327. }
  103328. /**
  103329. * This function will read the mtl file and create each material described inside
  103330. * This function could be improve by adding :
  103331. * -some component missing (Ni, Tf...)
  103332. * -including the specific options available
  103333. *
  103334. * @param scene
  103335. * @param data
  103336. * @param rootUrl
  103337. */
  103338. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  103339. if (data instanceof ArrayBuffer) {
  103340. return;
  103341. }
  103342. //Split the lines from the file
  103343. var lines = data.split('\n');
  103344. //Space char
  103345. var delimiter_pattern = /\s+/;
  103346. //Array with RGB colors
  103347. var color;
  103348. //New material
  103349. var material = null;
  103350. //Look at each line
  103351. for (var i = 0; i < lines.length; i++) {
  103352. var line = lines[i].trim();
  103353. // Blank line or comment
  103354. if (line.length === 0 || line.charAt(0) === '#') {
  103355. continue;
  103356. }
  103357. //Get the first parameter (keyword)
  103358. var pos = line.indexOf(' ');
  103359. var key = (pos >= 0) ? line.substring(0, pos) : line;
  103360. key = key.toLowerCase();
  103361. //Get the data following the key
  103362. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  103363. //This mtl keyword will create the new material
  103364. if (key === "newmtl") {
  103365. //Check if it is the first material.
  103366. // Materials specifications are described after this keyword.
  103367. if (material) {
  103368. //Add the previous material in the material array.
  103369. this.materials.push(material);
  103370. }
  103371. //Create a new material.
  103372. // value is the name of the material read in the mtl file
  103373. material = new BABYLON.StandardMaterial(value, scene);
  103374. }
  103375. else if (key === "kd" && material) {
  103376. // Diffuse color (color under white light) using RGB values
  103377. //value = "r g b"
  103378. color = value.split(delimiter_pattern, 3).map(parseFloat);
  103379. //color = [r,g,b]
  103380. //Set tghe color into the material
  103381. material.diffuseColor = BABYLON.Color3.FromArray(color);
  103382. }
  103383. else if (key === "ka" && material) {
  103384. // Ambient color (color under shadow) using RGB values
  103385. //value = "r g b"
  103386. color = value.split(delimiter_pattern, 3).map(parseFloat);
  103387. //color = [r,g,b]
  103388. //Set tghe color into the material
  103389. material.ambientColor = BABYLON.Color3.FromArray(color);
  103390. }
  103391. else if (key === "ks" && material) {
  103392. // Specular color (color when light is reflected from shiny surface) using RGB values
  103393. //value = "r g b"
  103394. color = value.split(delimiter_pattern, 3).map(parseFloat);
  103395. //color = [r,g,b]
  103396. //Set the color into the material
  103397. material.specularColor = BABYLON.Color3.FromArray(color);
  103398. }
  103399. else if (key === "ke" && material) {
  103400. // Emissive color using RGB values
  103401. color = value.split(delimiter_pattern, 3).map(parseFloat);
  103402. material.emissiveColor = BABYLON.Color3.FromArray(color);
  103403. }
  103404. else if (key === "ns" && material) {
  103405. //value = "Integer"
  103406. material.specularPower = parseFloat(value);
  103407. }
  103408. else if (key === "d" && material) {
  103409. //d is dissolve for current material. It mean alpha for BABYLON
  103410. material.alpha = parseFloat(value);
  103411. //Texture
  103412. //This part can be improved by adding the possible options of texture
  103413. }
  103414. else if (key === "map_ka" && material) {
  103415. // ambient texture map with a loaded image
  103416. //We must first get the folder of the image
  103417. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103418. }
  103419. else if (key === "map_kd" && material) {
  103420. // Diffuse texture map with a loaded image
  103421. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103422. }
  103423. else if (key === "map_ks" && material) {
  103424. // Specular texture map with a loaded image
  103425. //We must first get the folder of the image
  103426. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103427. }
  103428. else if (key === "map_ns") {
  103429. //Specular
  103430. //Specular highlight component
  103431. //We must first get the folder of the image
  103432. //
  103433. //Not supported by BABYLON
  103434. //
  103435. // continue;
  103436. }
  103437. else if (key === "map_bump" && material) {
  103438. //The bump texture
  103439. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103440. }
  103441. else if (key === "map_d" && material) {
  103442. // The dissolve of the material
  103443. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103444. //Options for illumination
  103445. }
  103446. else if (key === "illum") {
  103447. //Illumination
  103448. if (value === "0") {
  103449. //That mean Kd == Kd
  103450. }
  103451. else if (value === "1") {
  103452. //Color on and Ambient on
  103453. }
  103454. else if (value === "2") {
  103455. //Highlight on
  103456. }
  103457. else if (value === "3") {
  103458. //Reflection on and Ray trace on
  103459. }
  103460. else if (value === "4") {
  103461. //Transparency: Glass on, Reflection: Ray trace on
  103462. }
  103463. else if (value === "5") {
  103464. //Reflection: Fresnel on and Ray trace on
  103465. }
  103466. else if (value === "6") {
  103467. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  103468. }
  103469. else if (value === "7") {
  103470. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  103471. }
  103472. else if (value === "8") {
  103473. //Reflection on and Ray trace off
  103474. }
  103475. else if (value === "9") {
  103476. //Transparency: Glass on, Reflection: Ray trace off
  103477. }
  103478. else if (value === "10") {
  103479. //Casts shadows onto invisible surfaces
  103480. }
  103481. }
  103482. else {
  103483. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  103484. }
  103485. }
  103486. //At the end of the file, add the last material
  103487. if (material) {
  103488. this.materials.push(material);
  103489. }
  103490. };
  103491. /**
  103492. * Gets the texture for the material.
  103493. *
  103494. * If the material is imported from input file,
  103495. * We sanitize the url to ensure it takes the textre from aside the material.
  103496. *
  103497. * @param rootUrl The root url to load from
  103498. * @param value The value stored in the mtl
  103499. * @return The Texture
  103500. */
  103501. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  103502. if (!value) {
  103503. return null;
  103504. }
  103505. var url = rootUrl;
  103506. // Load from input file.
  103507. if (rootUrl === "file:") {
  103508. var lastDelimiter = value.lastIndexOf("\\");
  103509. if (lastDelimiter === -1) {
  103510. lastDelimiter = value.lastIndexOf("/");
  103511. }
  103512. if (lastDelimiter > -1) {
  103513. url += value.substr(lastDelimiter + 1);
  103514. }
  103515. else {
  103516. url += value;
  103517. }
  103518. }
  103519. // Not from input file.
  103520. else {
  103521. url += value;
  103522. }
  103523. return new BABYLON.Texture(url, scene);
  103524. };
  103525. return MTLFileLoader;
  103526. }());
  103527. BABYLON.MTLFileLoader = MTLFileLoader;
  103528. var OBJFileLoader = /** @class */ (function () {
  103529. function OBJFileLoader() {
  103530. this.name = "obj";
  103531. this.extensions = ".obj";
  103532. this.obj = /^o/;
  103533. this.group = /^g/;
  103534. this.mtllib = /^mtllib /;
  103535. this.usemtl = /^usemtl /;
  103536. this.smooth = /^s /;
  103537. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  103538. // vn float float float
  103539. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  103540. // vt float float
  103541. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  103542. // f vertex vertex vertex ...
  103543. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  103544. // f vertex/uvs vertex/uvs vertex/uvs ...
  103545. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  103546. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  103547. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  103548. // f vertex//normal vertex//normal vertex//normal ...
  103549. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  103550. }
  103551. /**
  103552. * Calls synchronously the MTL file attached to this obj.
  103553. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  103554. * Without this function materials are not displayed in the first frame (but displayed after).
  103555. * In consequence it is impossible to get material information in your HTML file
  103556. *
  103557. * @param url The URL of the MTL file
  103558. * @param rootUrl
  103559. * @param onSuccess Callback function to be called when the MTL file is loaded
  103560. * @private
  103561. */
  103562. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  103563. //The complete path to the mtl file
  103564. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  103565. // Loads through the babylon tools to allow fileInput search.
  103566. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  103567. };
  103568. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  103569. //get the meshes from OBJ file
  103570. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  103571. //Push meshes from OBJ file into the variable mesh of this function
  103572. if (meshes) {
  103573. loadedMeshes.forEach(function (mesh) {
  103574. meshes.push(mesh);
  103575. });
  103576. }
  103577. return true;
  103578. };
  103579. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  103580. //Get the 3D model
  103581. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  103582. };
  103583. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  103584. var container = new BABYLON.AssetContainer(scene);
  103585. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  103586. container.removeAllFromScene();
  103587. return container;
  103588. };
  103589. /**
  103590. * Read the OBJ file and create an Array of meshes.
  103591. * Each mesh contains all information given by the OBJ and the MTL file.
  103592. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  103593. *
  103594. * @param meshesNames
  103595. * @param scene BABYLON.Scene The scene where are displayed the data
  103596. * @param data String The content of the obj file
  103597. * @param rootUrl String The path to the folder
  103598. * @returns Array<AbstractMesh>
  103599. * @private
  103600. */
  103601. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  103602. var positions = []; //values for the positions of vertices
  103603. var normals = []; //Values for the normals
  103604. var uvs = []; //Values for the textures
  103605. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  103606. var handledMesh; //The current mesh of meshes array
  103607. var indicesForBabylon = []; //The list of indices for VertexData
  103608. var wrappedPositionForBabylon = []; //The list of position in vectors
  103609. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  103610. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  103611. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  103612. var curPositionInIndices = 0;
  103613. var hasMeshes = false; //Meshes are defined in the file
  103614. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  103615. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  103616. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  103617. var triangles = []; //Indices from new triangles coming from polygons
  103618. var materialNameFromObj = ""; //The name of the current material
  103619. var fileToLoad = ""; //The name of the mtlFile to load
  103620. var materialsFromMTLFile = new MTLFileLoader();
  103621. var objMeshName = ""; //The name of the current obj mesh
  103622. var increment = 1; //Id for meshes created by the multimaterial
  103623. var isFirstMaterial = true;
  103624. /**
  103625. * Search for obj in the given array.
  103626. * This function is called to check if a couple of data already exists in an array.
  103627. *
  103628. * If found, returns the index of the founded tuple index. Returns -1 if not found
  103629. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  103630. * @param obj Array<number>
  103631. * @returns {boolean}
  103632. */
  103633. var isInArray = function (arr, obj) {
  103634. if (!arr[obj[0]])
  103635. arr[obj[0]] = { normals: [], idx: [] };
  103636. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  103637. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  103638. };
  103639. var isInArrayUV = function (arr, obj) {
  103640. if (!arr[obj[0]])
  103641. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  103642. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  103643. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  103644. return arr[obj[0]].idx[idx];
  103645. }
  103646. return -1;
  103647. };
  103648. /**
  103649. * This function set the data for each triangle.
  103650. * Data are position, normals and uvs
  103651. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  103652. * If the tuple already exist, add only their indice
  103653. *
  103654. * @param indicePositionFromObj Integer The index in positions array
  103655. * @param indiceUvsFromObj Integer The index in uvs array
  103656. * @param indiceNormalFromObj Integer The index in normals array
  103657. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  103658. * @param textureVectorFromOBJ Vector3 The value of uvs
  103659. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  103660. */
  103661. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  103662. //Check if this tuple already exists in the list of tuples
  103663. var _index;
  103664. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  103665. _index = isInArrayUV(tuplePosNorm, [
  103666. indicePositionFromObj,
  103667. indiceNormalFromObj,
  103668. indiceUvsFromObj
  103669. ]);
  103670. }
  103671. else {
  103672. _index = isInArray(tuplePosNorm, [
  103673. indicePositionFromObj,
  103674. indiceNormalFromObj
  103675. ]);
  103676. }
  103677. //If it not exists
  103678. if (_index == -1) {
  103679. //Add an new indice.
  103680. //The array of indices is only an array with his length equal to the number of triangles - 1.
  103681. //We add vertices data in this order
  103682. indicesForBabylon.push(wrappedPositionForBabylon.length);
  103683. //Push the position of vertice for Babylon
  103684. //Each element is a BABYLON.Vector3(x,y,z)
  103685. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  103686. //Push the uvs for Babylon
  103687. //Each element is a BABYLON.Vector3(u,v)
  103688. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  103689. //Push the normals for Babylon
  103690. //Each element is a BABYLON.Vector3(x,y,z)
  103691. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  103692. //Add the tuple in the comparison list
  103693. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  103694. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  103695. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  103696. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  103697. }
  103698. else {
  103699. //The tuple already exists
  103700. //Add the index of the already existing tuple
  103701. //At this index we can get the value of position, normal and uvs of vertex
  103702. indicesForBabylon.push(_index);
  103703. }
  103704. };
  103705. /**
  103706. * Transform BABYLON.Vector() object onto 3 digits in an array
  103707. */
  103708. var unwrapData = function () {
  103709. //Every array has the same length
  103710. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  103711. //Push the x, y, z values of each element in the unwrapped array
  103712. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  103713. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  103714. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  103715. }
  103716. // Reset arrays for the next new meshes
  103717. wrappedPositionForBabylon = [];
  103718. wrappedNormalsForBabylon = [];
  103719. wrappedUvsForBabylon = [];
  103720. tuplePosNorm = [];
  103721. curPositionInIndices = 0;
  103722. };
  103723. /**
  103724. * Create triangles from polygons by recursion
  103725. * The best to understand how it works is to draw it in the same time you get the recursion.
  103726. * It is important to notice that a triangle is a polygon
  103727. * We get 4 patterns of face defined in OBJ File :
  103728. * facePattern1 = ["1","2","3","4","5","6"]
  103729. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  103730. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  103731. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  103732. * Each pattern is divided by the same method
  103733. * @param face Array[String] The indices of elements
  103734. * @param v Integer The variable to increment
  103735. */
  103736. var getTriangles = function (face, v) {
  103737. //Work for each element of the array
  103738. if (v + 1 < face.length) {
  103739. //Add on the triangle variable the indexes to obtain triangles
  103740. triangles.push(face[0], face[v], face[v + 1]);
  103741. //Incrementation for recursion
  103742. v += 1;
  103743. //Recursion
  103744. getTriangles(face, v);
  103745. }
  103746. //Result obtained after 2 iterations:
  103747. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  103748. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  103749. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  103750. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  103751. };
  103752. /**
  103753. * Create triangles and push the data for each polygon for the pattern 1
  103754. * In this pattern we get vertice positions
  103755. * @param face
  103756. * @param v
  103757. */
  103758. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  103759. //Get the indices of triangles for each polygon
  103760. getTriangles(face, v);
  103761. //For each element in the triangles array.
  103762. //This var could contains 1 to an infinity of triangles
  103763. for (var k = 0; k < triangles.length; k++) {
  103764. // Set position indice
  103765. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  103766. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  103767. positions[indicePositionFromObj], //Get the vectors data
  103768. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  103769. );
  103770. }
  103771. //Reset variable for the next line
  103772. triangles = [];
  103773. };
  103774. /**
  103775. * Create triangles and push the data for each polygon for the pattern 2
  103776. * In this pattern we get vertice positions and uvsu
  103777. * @param face
  103778. * @param v
  103779. */
  103780. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  103781. //Get the indices of triangles for each polygon
  103782. getTriangles(face, v);
  103783. for (var k = 0; k < triangles.length; k++) {
  103784. //triangle[k] = "1/1"
  103785. //Split the data for getting position and uv
  103786. var point = triangles[k].split("/"); // ["1", "1"]
  103787. //Set position indice
  103788. var indicePositionFromObj = parseInt(point[0]) - 1;
  103789. //Set uv indice
  103790. var indiceUvsFromObj = parseInt(point[1]) - 1;
  103791. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  103792. positions[indicePositionFromObj], //Get the values for each element
  103793. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  103794. );
  103795. }
  103796. //Reset variable for the next line
  103797. triangles = [];
  103798. };
  103799. /**
  103800. * Create triangles and push the data for each polygon for the pattern 3
  103801. * In this pattern we get vertice positions, uvs and normals
  103802. * @param face
  103803. * @param v
  103804. */
  103805. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  103806. //Get the indices of triangles for each polygon
  103807. getTriangles(face, v);
  103808. for (var k = 0; k < triangles.length; k++) {
  103809. //triangle[k] = "1/1/1"
  103810. //Split the data for getting position, uv, and normals
  103811. var point = triangles[k].split("/"); // ["1", "1", "1"]
  103812. // Set position indice
  103813. var indicePositionFromObj = parseInt(point[0]) - 1;
  103814. // Set uv indice
  103815. var indiceUvsFromObj = parseInt(point[1]) - 1;
  103816. // Set normal indice
  103817. var indiceNormalFromObj = parseInt(point[2]) - 1;
  103818. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  103819. );
  103820. }
  103821. //Reset variable for the next line
  103822. triangles = [];
  103823. };
  103824. /**
  103825. * Create triangles and push the data for each polygon for the pattern 4
  103826. * In this pattern we get vertice positions and normals
  103827. * @param face
  103828. * @param v
  103829. */
  103830. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  103831. getTriangles(face, v);
  103832. for (var k = 0; k < triangles.length; k++) {
  103833. //triangle[k] = "1//1"
  103834. //Split the data for getting position and normals
  103835. var point = triangles[k].split("//"); // ["1", "1"]
  103836. // We check indices, and normals
  103837. var indicePositionFromObj = parseInt(point[0]) - 1;
  103838. var indiceNormalFromObj = parseInt(point[1]) - 1;
  103839. setData(indicePositionFromObj, 1, //Default value for uv
  103840. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  103841. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  103842. }
  103843. //Reset variable for the next line
  103844. triangles = [];
  103845. };
  103846. var addPreviousObjMesh = function () {
  103847. //Check if it is not the first mesh. Otherwise we don't have data.
  103848. if (meshesFromObj.length > 0) {
  103849. //Get the previous mesh for applying the data about the faces
  103850. //=> in obj file, faces definition append after the name of the mesh
  103851. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  103852. //Set the data into Array for the mesh
  103853. unwrapData();
  103854. // Reverse tab. Otherwise face are displayed in the wrong sens
  103855. indicesForBabylon.reverse();
  103856. //Set the information for the mesh
  103857. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  103858. handledMesh.indices = indicesForBabylon.slice();
  103859. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  103860. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  103861. handledMesh.uvs = unwrappedUVForBabylon.slice();
  103862. //Reset the array for the next mesh
  103863. indicesForBabylon = [];
  103864. unwrappedPositionsForBabylon = [];
  103865. unwrappedNormalsForBabylon = [];
  103866. unwrappedUVForBabylon = [];
  103867. }
  103868. };
  103869. //Main function
  103870. //Split the file into lines
  103871. var lines = data.split('\n');
  103872. //Look at each line
  103873. for (var i = 0; i < lines.length; i++) {
  103874. var line = lines[i].trim();
  103875. var result;
  103876. //Comment or newLine
  103877. if (line.length === 0 || line.charAt(0) === '#') {
  103878. continue;
  103879. //Get information about one position possible for the vertices
  103880. }
  103881. else if ((result = this.vertexPattern.exec(line)) !== null) {
  103882. //Create a Vector3 with the position x, y, z
  103883. //Value of result:
  103884. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  103885. //Add the Vector in the list of positions
  103886. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  103887. }
  103888. else if ((result = this.normalPattern.exec(line)) !== null) {
  103889. //Create a Vector3 with the normals x, y, z
  103890. //Value of result
  103891. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  103892. //Add the Vector in the list of normals
  103893. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  103894. }
  103895. else if ((result = this.uvPattern.exec(line)) !== null) {
  103896. //Create a Vector2 with the normals u, v
  103897. //Value of result
  103898. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  103899. //Add the Vector in the list of uvs
  103900. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  103901. //Identify patterns of faces
  103902. //Face could be defined in different type of pattern
  103903. }
  103904. else if ((result = this.facePattern3.exec(line)) !== null) {
  103905. //Value of result:
  103906. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  103907. //Set the data for this face
  103908. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  103909. 1);
  103910. }
  103911. else if ((result = this.facePattern4.exec(line)) !== null) {
  103912. //Value of result:
  103913. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  103914. //Set the data for this face
  103915. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  103916. 1);
  103917. }
  103918. else if ((result = this.facePattern2.exec(line)) !== null) {
  103919. //Value of result:
  103920. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  103921. //Set the data for this face
  103922. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  103923. 1);
  103924. }
  103925. else if ((result = this.facePattern1.exec(line)) !== null) {
  103926. //Value of result
  103927. //["f 1 2 3", "1 2 3"...]
  103928. //Set the data for this face
  103929. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  103930. 1);
  103931. //Define a mesh or an object
  103932. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  103933. }
  103934. else if (this.group.test(line) || this.obj.test(line)) {
  103935. //Create a new mesh corresponding to the name of the group.
  103936. //Definition of the mesh
  103937. var objMesh =
  103938. //Set the name of the current obj mesh
  103939. {
  103940. name: line.substring(2).trim(),
  103941. indices: undefined,
  103942. positions: undefined,
  103943. normals: undefined,
  103944. uvs: undefined,
  103945. materialName: ""
  103946. };
  103947. addPreviousObjMesh();
  103948. //Push the last mesh created with only the name
  103949. meshesFromObj.push(objMesh);
  103950. //Set this variable to indicate that now meshesFromObj has objects defined inside
  103951. hasMeshes = true;
  103952. isFirstMaterial = true;
  103953. increment = 1;
  103954. //Keyword for applying a material
  103955. }
  103956. else if (this.usemtl.test(line)) {
  103957. //Get the name of the material
  103958. materialNameFromObj = line.substring(7).trim();
  103959. //If this new material is in the same mesh
  103960. if (!isFirstMaterial) {
  103961. //Set the data for the previous mesh
  103962. addPreviousObjMesh();
  103963. //Create a new mesh
  103964. var objMesh =
  103965. //Set the name of the current obj mesh
  103966. {
  103967. name: objMeshName + "_mm" + increment.toString(),
  103968. indices: undefined,
  103969. positions: undefined,
  103970. normals: undefined,
  103971. uvs: undefined,
  103972. materialName: materialNameFromObj
  103973. };
  103974. increment++;
  103975. //If meshes are already defined
  103976. meshesFromObj.push(objMesh);
  103977. }
  103978. //Set the material name if the previous line define a mesh
  103979. if (hasMeshes && isFirstMaterial) {
  103980. //Set the material name to the previous mesh (1 material per mesh)
  103981. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  103982. isFirstMaterial = false;
  103983. }
  103984. //Keyword for loading the mtl file
  103985. }
  103986. else if (this.mtllib.test(line)) {
  103987. //Get the name of mtl file
  103988. fileToLoad = line.substring(7).trim();
  103989. //Apply smoothing
  103990. }
  103991. else if (this.smooth.test(line)) {
  103992. // smooth shading => apply smoothing
  103993. //Toda y I don't know it work with babylon and with obj.
  103994. //With the obj file an integer is set
  103995. }
  103996. else {
  103997. //If there is another possibility
  103998. console.log("Unhandled expression at line : " + line);
  103999. }
  104000. }
  104001. //At the end of the file, add the last mesh into the meshesFromObj array
  104002. if (hasMeshes) {
  104003. //Set the data for the last mesh
  104004. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  104005. //Reverse indices for displaying faces in the good sens
  104006. indicesForBabylon.reverse();
  104007. //Get the good array
  104008. unwrapData();
  104009. //Set array
  104010. handledMesh.indices = indicesForBabylon;
  104011. handledMesh.positions = unwrappedPositionsForBabylon;
  104012. handledMesh.normals = unwrappedNormalsForBabylon;
  104013. handledMesh.uvs = unwrappedUVForBabylon;
  104014. }
  104015. //If any o or g keyword found, create a mesj with a random id
  104016. if (!hasMeshes) {
  104017. // reverse tab of indices
  104018. indicesForBabylon.reverse();
  104019. //Get positions normals uvs
  104020. unwrapData();
  104021. //Set data for one mesh
  104022. meshesFromObj.push({
  104023. name: BABYLON.Geometry.RandomId(),
  104024. indices: indicesForBabylon,
  104025. positions: unwrappedPositionsForBabylon,
  104026. normals: unwrappedNormalsForBabylon,
  104027. uvs: unwrappedUVForBabylon,
  104028. materialName: materialNameFromObj
  104029. });
  104030. }
  104031. //Create a BABYLON.Mesh list
  104032. var babylonMeshesArray = []; //The mesh for babylon
  104033. var materialToUse = new Array();
  104034. //Set data for each mesh
  104035. for (var j = 0; j < meshesFromObj.length; j++) {
  104036. //check meshesNames (stlFileLoader)
  104037. if (meshesNames && meshesFromObj[j].name) {
  104038. if (meshesNames instanceof Array) {
  104039. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  104040. continue;
  104041. }
  104042. }
  104043. else {
  104044. if (meshesFromObj[j].name !== meshesNames) {
  104045. continue;
  104046. }
  104047. }
  104048. }
  104049. //Get the current mesh
  104050. //Set the data with VertexBuffer for each mesh
  104051. handledMesh = meshesFromObj[j];
  104052. //Create a BABYLON.Mesh with the name of the obj mesh
  104053. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  104054. //Push the name of the material to an array
  104055. //This is indispensable for the importMesh function
  104056. materialToUse.push(meshesFromObj[j].materialName);
  104057. var vertexData = new BABYLON.VertexData(); //The container for the values
  104058. //Set the data for the babylonMesh
  104059. vertexData.positions = handledMesh.positions;
  104060. vertexData.normals = handledMesh.normals;
  104061. vertexData.uvs = handledMesh.uvs;
  104062. vertexData.indices = handledMesh.indices;
  104063. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  104064. vertexData.applyToMesh(babylonMesh);
  104065. if (OBJFileLoader.INVERT_Y) {
  104066. babylonMesh.scaling.y *= -1;
  104067. }
  104068. //Push the mesh into an array
  104069. babylonMeshesArray.push(babylonMesh);
  104070. }
  104071. //load the materials
  104072. //Check if we have a file to load
  104073. if (fileToLoad !== "") {
  104074. //Load the file synchronously
  104075. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  104076. //Create materials thanks MTLLoader function
  104077. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  104078. //Look at each material loaded in the mtl file
  104079. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  104080. //Three variables to get all meshes with the same material
  104081. var startIndex = 0;
  104082. var _indices = [];
  104083. var _index;
  104084. //The material from MTL file is used in the meshes loaded
  104085. //Push the indice in an array
  104086. //Check if the material is not used for another mesh
  104087. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  104088. _indices.push(_index);
  104089. startIndex = _index + 1;
  104090. }
  104091. //If the material is not used dispose it
  104092. if (_index == -1 && _indices.length == 0) {
  104093. //If the material is not needed, remove it
  104094. materialsFromMTLFile.materials[n].dispose();
  104095. }
  104096. else {
  104097. for (var o = 0; o < _indices.length; o++) {
  104098. //Apply the material to the BABYLON.Mesh for each mesh with the material
  104099. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  104100. }
  104101. }
  104102. }
  104103. });
  104104. }
  104105. //Return an array with all BABYLON.Mesh
  104106. return babylonMeshesArray;
  104107. };
  104108. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  104109. OBJFileLoader.INVERT_Y = false;
  104110. return OBJFileLoader;
  104111. }());
  104112. BABYLON.OBJFileLoader = OBJFileLoader;
  104113. if (BABYLON.SceneLoader) {
  104114. //Add this loader into the register plugin
  104115. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  104116. }
  104117. })(BABYLON || (BABYLON = {}));
  104118. //# sourceMappingURL=babylon.objFileLoader.js.map
  104119. var BABYLON;
  104120. (function (BABYLON) {
  104121. /**
  104122. * Mode that determines the coordinate system to use.
  104123. */
  104124. var GLTFLoaderCoordinateSystemMode;
  104125. (function (GLTFLoaderCoordinateSystemMode) {
  104126. /**
  104127. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  104128. */
  104129. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  104130. /**
  104131. * Sets the useRightHandedSystem flag on the scene.
  104132. */
  104133. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  104134. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  104135. /**
  104136. * Mode that determines what animations will start.
  104137. */
  104138. var GLTFLoaderAnimationStartMode;
  104139. (function (GLTFLoaderAnimationStartMode) {
  104140. /**
  104141. * No animation will start.
  104142. */
  104143. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  104144. /**
  104145. * The first animation will start.
  104146. */
  104147. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  104148. /**
  104149. * All animations will start.
  104150. */
  104151. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  104152. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  104153. /**
  104154. * Loader state.
  104155. */
  104156. var GLTFLoaderState;
  104157. (function (GLTFLoaderState) {
  104158. /**
  104159. * The asset is loading.
  104160. */
  104161. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  104162. /**
  104163. * The asset is ready for rendering.
  104164. */
  104165. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  104166. /**
  104167. * The asset is completely loaded.
  104168. */
  104169. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  104170. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  104171. /**
  104172. * File loader for loading glTF files into a scene.
  104173. */
  104174. var GLTFFileLoader = /** @class */ (function () {
  104175. function GLTFFileLoader() {
  104176. // #region Common options
  104177. /**
  104178. * Raised when the asset has been parsed
  104179. */
  104180. this.onParsedObservable = new BABYLON.Observable();
  104181. // #endregion
  104182. // #region V2 options
  104183. /**
  104184. * The coordinate system mode. Defaults to AUTO.
  104185. */
  104186. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  104187. /**
  104188. * The animation start mode. Defaults to FIRST.
  104189. */
  104190. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  104191. /**
  104192. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  104193. */
  104194. this.compileMaterials = false;
  104195. /**
  104196. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  104197. */
  104198. this.useClipPlane = false;
  104199. /**
  104200. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  104201. */
  104202. this.compileShadowGenerators = false;
  104203. /**
  104204. * Defines if the Alpha blended materials are only applied as coverage.
  104205. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  104206. * If true, no extra effects are applied to transparent pixels.
  104207. */
  104208. this.transparencyAsCoverage = false;
  104209. /** @hidden */
  104210. this._normalizeAnimationGroupsToBeginAtZero = true;
  104211. /**
  104212. * Function called before loading a url referenced by the asset.
  104213. */
  104214. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  104215. /**
  104216. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  104217. */
  104218. this.onMeshLoadedObservable = new BABYLON.Observable();
  104219. /**
  104220. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  104221. */
  104222. this.onTextureLoadedObservable = new BABYLON.Observable();
  104223. /**
  104224. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  104225. */
  104226. this.onMaterialLoadedObservable = new BABYLON.Observable();
  104227. /**
  104228. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  104229. */
  104230. this.onCameraLoadedObservable = new BABYLON.Observable();
  104231. /**
  104232. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  104233. * For assets with LODs, raised when all of the LODs are complete.
  104234. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  104235. */
  104236. this.onCompleteObservable = new BABYLON.Observable();
  104237. /**
  104238. * Observable raised after the loader is disposed.
  104239. */
  104240. this.onDisposeObservable = new BABYLON.Observable();
  104241. /**
  104242. * Observable raised after a loader extension is created.
  104243. * Set additional options for a loader extension in this event.
  104244. */
  104245. this.onExtensionLoadedObservable = new BABYLON.Observable();
  104246. // #endregion
  104247. this._loader = null;
  104248. /**
  104249. * Name of the loader ("gltf")
  104250. */
  104251. this.name = "gltf";
  104252. /**
  104253. * Supported file extensions of the loader (.gltf, .glb)
  104254. */
  104255. this.extensions = {
  104256. ".gltf": { isBinary: false },
  104257. ".glb": { isBinary: true }
  104258. };
  104259. }
  104260. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  104261. /**
  104262. * Raised when the asset has been parsed
  104263. */
  104264. set: function (callback) {
  104265. if (this._onParsedObserver) {
  104266. this.onParsedObservable.remove(this._onParsedObserver);
  104267. }
  104268. this._onParsedObserver = this.onParsedObservable.add(callback);
  104269. },
  104270. enumerable: true,
  104271. configurable: true
  104272. });
  104273. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  104274. /**
  104275. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  104276. */
  104277. set: function (callback) {
  104278. if (this._onMeshLoadedObserver) {
  104279. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  104280. }
  104281. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  104282. },
  104283. enumerable: true,
  104284. configurable: true
  104285. });
  104286. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  104287. /**
  104288. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  104289. */
  104290. set: function (callback) {
  104291. if (this._onTextureLoadedObserver) {
  104292. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  104293. }
  104294. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  104295. },
  104296. enumerable: true,
  104297. configurable: true
  104298. });
  104299. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  104300. /**
  104301. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  104302. */
  104303. set: function (callback) {
  104304. if (this._onMaterialLoadedObserver) {
  104305. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  104306. }
  104307. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  104308. },
  104309. enumerable: true,
  104310. configurable: true
  104311. });
  104312. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  104313. /**
  104314. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  104315. */
  104316. set: function (callback) {
  104317. if (this._onCameraLoadedObserver) {
  104318. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  104319. }
  104320. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  104321. },
  104322. enumerable: true,
  104323. configurable: true
  104324. });
  104325. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  104326. /**
  104327. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  104328. */
  104329. set: function (callback) {
  104330. if (this._onCompleteObserver) {
  104331. this.onCompleteObservable.remove(this._onCompleteObserver);
  104332. }
  104333. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  104334. },
  104335. enumerable: true,
  104336. configurable: true
  104337. });
  104338. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  104339. /**
  104340. * Callback raised after the loader is disposed.
  104341. */
  104342. set: function (callback) {
  104343. if (this._onDisposeObserver) {
  104344. this.onDisposeObservable.remove(this._onDisposeObserver);
  104345. }
  104346. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  104347. },
  104348. enumerable: true,
  104349. configurable: true
  104350. });
  104351. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  104352. /**
  104353. * Callback raised after a loader extension is created.
  104354. */
  104355. set: function (callback) {
  104356. if (this._onExtensionLoadedObserver) {
  104357. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  104358. }
  104359. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  104360. },
  104361. enumerable: true,
  104362. configurable: true
  104363. });
  104364. /**
  104365. * Returns a promise that resolves when the asset is completely loaded.
  104366. * @returns a promise that resolves when the asset is completely loaded.
  104367. */
  104368. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  104369. var _this = this;
  104370. return new Promise(function (resolve) {
  104371. _this.onCompleteObservable.addOnce(function () {
  104372. resolve();
  104373. });
  104374. });
  104375. };
  104376. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  104377. /**
  104378. * The loader state or null if the loader is not active.
  104379. */
  104380. get: function () {
  104381. return this._loader ? this._loader.state : null;
  104382. },
  104383. enumerable: true,
  104384. configurable: true
  104385. });
  104386. /**
  104387. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  104388. */
  104389. GLTFFileLoader.prototype.dispose = function () {
  104390. if (this._loader) {
  104391. this._loader.dispose();
  104392. this._loader = null;
  104393. }
  104394. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  104395. this.onMeshLoadedObservable.clear();
  104396. this.onTextureLoadedObservable.clear();
  104397. this.onMaterialLoadedObservable.clear();
  104398. this.onCameraLoadedObservable.clear();
  104399. this.onCompleteObservable.clear();
  104400. this.onExtensionLoadedObservable.clear();
  104401. this.onDisposeObservable.notifyObservers(this);
  104402. this.onDisposeObservable.clear();
  104403. };
  104404. /**
  104405. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  104406. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  104407. * @param scene the scene the meshes should be added to
  104408. * @param data the glTF data to load
  104409. * @param rootUrl root url to load from
  104410. * @param onProgress event that fires when loading progress has occured
  104411. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  104412. */
  104413. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  104414. var _this = this;
  104415. return Promise.resolve().then(function () {
  104416. var loaderData = _this._parse(data);
  104417. _this._loader = _this._getLoader(loaderData);
  104418. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  104419. });
  104420. };
  104421. /**
  104422. * Imports all objects from the loaded glTF data and adds them to the scene
  104423. * @param scene the scene the objects should be added to
  104424. * @param data the glTF data to load
  104425. * @param rootUrl root url to load from
  104426. * @param onProgress event that fires when loading progress has occured
  104427. * @returns a promise which completes when objects have been loaded to the scene
  104428. */
  104429. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  104430. var _this = this;
  104431. return Promise.resolve().then(function () {
  104432. var loaderData = _this._parse(data);
  104433. _this._loader = _this._getLoader(loaderData);
  104434. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  104435. });
  104436. };
  104437. /**
  104438. * Load into an asset container.
  104439. * @param scene The scene to load into
  104440. * @param data The data to import
  104441. * @param rootUrl The root url for scene and resources
  104442. * @param onProgress The callback when the load progresses
  104443. * @returns The loaded asset container
  104444. */
  104445. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  104446. var _this = this;
  104447. return Promise.resolve().then(function () {
  104448. var loaderData = _this._parse(data);
  104449. _this._loader = _this._getLoader(loaderData);
  104450. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  104451. var container = new BABYLON.AssetContainer(scene);
  104452. Array.prototype.push.apply(container.meshes, result.meshes);
  104453. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  104454. Array.prototype.push.apply(container.skeletons, result.skeletons);
  104455. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  104456. container.removeAllFromScene();
  104457. return container;
  104458. });
  104459. });
  104460. };
  104461. /**
  104462. * If the data string can be loaded directly.
  104463. * @param data string contianing the file data
  104464. * @returns if the data can be loaded directly
  104465. */
  104466. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  104467. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  104468. };
  104469. /**
  104470. * Instantiates a glTF file loader plugin.
  104471. * @returns the created plugin
  104472. */
  104473. GLTFFileLoader.prototype.createPlugin = function () {
  104474. return new GLTFFileLoader();
  104475. };
  104476. GLTFFileLoader.prototype._parse = function (data) {
  104477. var parsedData;
  104478. if (data instanceof ArrayBuffer) {
  104479. parsedData = GLTFFileLoader._parseBinary(data);
  104480. }
  104481. else {
  104482. parsedData = {
  104483. json: JSON.parse(data),
  104484. bin: null
  104485. };
  104486. }
  104487. this.onParsedObservable.notifyObservers(parsedData);
  104488. this.onParsedObservable.clear();
  104489. return parsedData;
  104490. };
  104491. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  104492. var _this = this;
  104493. var loaderVersion = { major: 2, minor: 0 };
  104494. var asset = loaderData.json.asset || {};
  104495. var version = GLTFFileLoader._parseVersion(asset.version);
  104496. if (!version) {
  104497. throw new Error("Invalid version: " + asset.version);
  104498. }
  104499. if (asset.minVersion !== undefined) {
  104500. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  104501. if (!minVersion) {
  104502. throw new Error("Invalid minimum version: " + asset.minVersion);
  104503. }
  104504. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  104505. throw new Error("Incompatible minimum version: " + asset.minVersion);
  104506. }
  104507. }
  104508. var createLoaders = {
  104509. 1: GLTFFileLoader._CreateGLTFLoaderV1,
  104510. 2: GLTFFileLoader._CreateGLTFLoaderV2
  104511. };
  104512. var createLoader = createLoaders[version.major];
  104513. if (!createLoader) {
  104514. throw new Error("Unsupported version: " + asset.version);
  104515. }
  104516. var loader = createLoader();
  104517. loader.coordinateSystemMode = this.coordinateSystemMode;
  104518. loader.animationStartMode = this.animationStartMode;
  104519. loader.compileMaterials = this.compileMaterials;
  104520. loader.useClipPlane = this.useClipPlane;
  104521. loader.compileShadowGenerators = this.compileShadowGenerators;
  104522. loader.transparencyAsCoverage = this.transparencyAsCoverage;
  104523. loader._normalizeAnimationGroupsToBeginAtZero = this._normalizeAnimationGroupsToBeginAtZero;
  104524. loader.preprocessUrlAsync = this.preprocessUrlAsync;
  104525. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  104526. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  104527. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  104528. loader.onCameraLoadedObservable.add(function (camera) { return _this.onCameraLoadedObservable.notifyObservers(camera); });
  104529. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  104530. loader.onCompleteObservable.add(function () {
  104531. _this.onMeshLoadedObservable.clear();
  104532. _this.onTextureLoadedObservable.clear();
  104533. _this.onMaterialLoadedObservable.clear();
  104534. _this.onCameraLoadedObservable.clear();
  104535. _this.onExtensionLoadedObservable.clear();
  104536. _this.onCompleteObservable.notifyObservers(_this);
  104537. _this.onCompleteObservable.clear();
  104538. });
  104539. return loader;
  104540. };
  104541. GLTFFileLoader._parseBinary = function (data) {
  104542. var Binary = {
  104543. Magic: 0x46546C67
  104544. };
  104545. var binaryReader = new BinaryReader(data);
  104546. var magic = binaryReader.readUint32();
  104547. if (magic !== Binary.Magic) {
  104548. throw new Error("Unexpected magic: " + magic);
  104549. }
  104550. var version = binaryReader.readUint32();
  104551. switch (version) {
  104552. case 1: return GLTFFileLoader._parseV1(binaryReader);
  104553. case 2: return GLTFFileLoader._parseV2(binaryReader);
  104554. }
  104555. throw new Error("Unsupported version: " + version);
  104556. };
  104557. GLTFFileLoader._parseV1 = function (binaryReader) {
  104558. var ContentFormat = {
  104559. JSON: 0
  104560. };
  104561. var length = binaryReader.readUint32();
  104562. if (length != binaryReader.getLength()) {
  104563. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  104564. }
  104565. var contentLength = binaryReader.readUint32();
  104566. var contentFormat = binaryReader.readUint32();
  104567. var content;
  104568. switch (contentFormat) {
  104569. case ContentFormat.JSON: {
  104570. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  104571. break;
  104572. }
  104573. default: {
  104574. throw new Error("Unexpected content format: " + contentFormat);
  104575. }
  104576. }
  104577. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  104578. var body = binaryReader.readUint8Array(bytesRemaining);
  104579. return {
  104580. json: content,
  104581. bin: body
  104582. };
  104583. };
  104584. GLTFFileLoader._parseV2 = function (binaryReader) {
  104585. var ChunkFormat = {
  104586. JSON: 0x4E4F534A,
  104587. BIN: 0x004E4942
  104588. };
  104589. var length = binaryReader.readUint32();
  104590. if (length !== binaryReader.getLength()) {
  104591. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  104592. }
  104593. // JSON chunk
  104594. var chunkLength = binaryReader.readUint32();
  104595. var chunkFormat = binaryReader.readUint32();
  104596. if (chunkFormat !== ChunkFormat.JSON) {
  104597. throw new Error("First chunk format is not JSON");
  104598. }
  104599. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  104600. // Look for BIN chunk
  104601. var bin = null;
  104602. while (binaryReader.getPosition() < binaryReader.getLength()) {
  104603. var chunkLength_1 = binaryReader.readUint32();
  104604. var chunkFormat_1 = binaryReader.readUint32();
  104605. switch (chunkFormat_1) {
  104606. case ChunkFormat.JSON: {
  104607. throw new Error("Unexpected JSON chunk");
  104608. }
  104609. case ChunkFormat.BIN: {
  104610. bin = binaryReader.readUint8Array(chunkLength_1);
  104611. break;
  104612. }
  104613. default: {
  104614. // ignore unrecognized chunkFormat
  104615. binaryReader.skipBytes(chunkLength_1);
  104616. break;
  104617. }
  104618. }
  104619. }
  104620. return {
  104621. json: json,
  104622. bin: bin
  104623. };
  104624. };
  104625. GLTFFileLoader._parseVersion = function (version) {
  104626. if (version === "1.0" || version === "1.0.1") {
  104627. return {
  104628. major: 1,
  104629. minor: 0
  104630. };
  104631. }
  104632. var match = (version + "").match(/^(\d+)\.(\d+)/);
  104633. if (!match) {
  104634. return null;
  104635. }
  104636. return {
  104637. major: parseInt(match[1]),
  104638. minor: parseInt(match[2])
  104639. };
  104640. };
  104641. GLTFFileLoader._compareVersion = function (a, b) {
  104642. if (a.major > b.major)
  104643. return 1;
  104644. if (a.major < b.major)
  104645. return -1;
  104646. if (a.minor > b.minor)
  104647. return 1;
  104648. if (a.minor < b.minor)
  104649. return -1;
  104650. return 0;
  104651. };
  104652. GLTFFileLoader._decodeBufferToText = function (buffer) {
  104653. var result = "";
  104654. var length = buffer.byteLength;
  104655. for (var i = 0; i < length; i++) {
  104656. result += String.fromCharCode(buffer[i]);
  104657. }
  104658. return result;
  104659. };
  104660. // #endregion
  104661. // #region V1 options
  104662. /**
  104663. * 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.
  104664. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  104665. * Defaults to true.
  104666. * @hidden
  104667. */
  104668. GLTFFileLoader.IncrementalLoading = true;
  104669. /**
  104670. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  104671. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  104672. * @hidden
  104673. */
  104674. GLTFFileLoader.HomogeneousCoordinates = false;
  104675. return GLTFFileLoader;
  104676. }());
  104677. BABYLON.GLTFFileLoader = GLTFFileLoader;
  104678. var BinaryReader = /** @class */ (function () {
  104679. function BinaryReader(arrayBuffer) {
  104680. this._arrayBuffer = arrayBuffer;
  104681. this._dataView = new DataView(arrayBuffer);
  104682. this._byteOffset = 0;
  104683. }
  104684. BinaryReader.prototype.getPosition = function () {
  104685. return this._byteOffset;
  104686. };
  104687. BinaryReader.prototype.getLength = function () {
  104688. return this._arrayBuffer.byteLength;
  104689. };
  104690. BinaryReader.prototype.readUint32 = function () {
  104691. var value = this._dataView.getUint32(this._byteOffset, true);
  104692. this._byteOffset += 4;
  104693. return value;
  104694. };
  104695. BinaryReader.prototype.readUint8Array = function (length) {
  104696. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  104697. this._byteOffset += length;
  104698. return value;
  104699. };
  104700. BinaryReader.prototype.skipBytes = function (length) {
  104701. this._byteOffset += length;
  104702. };
  104703. return BinaryReader;
  104704. }());
  104705. if (BABYLON.SceneLoader) {
  104706. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  104707. }
  104708. })(BABYLON || (BABYLON = {}));
  104709. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  104710. var BABYLON;
  104711. (function (BABYLON) {
  104712. var GLTF1;
  104713. (function (GLTF1) {
  104714. /**
  104715. * Enums
  104716. */
  104717. var EComponentType;
  104718. (function (EComponentType) {
  104719. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  104720. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  104721. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  104722. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  104723. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  104724. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  104725. var EShaderType;
  104726. (function (EShaderType) {
  104727. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  104728. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  104729. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  104730. var EParameterType;
  104731. (function (EParameterType) {
  104732. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  104733. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  104734. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  104735. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  104736. EParameterType[EParameterType["INT"] = 5124] = "INT";
  104737. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  104738. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  104739. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  104740. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  104741. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  104742. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  104743. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  104744. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  104745. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  104746. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  104747. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  104748. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  104749. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  104750. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  104751. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  104752. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  104753. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  104754. var ETextureWrapMode;
  104755. (function (ETextureWrapMode) {
  104756. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  104757. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  104758. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  104759. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  104760. var ETextureFilterType;
  104761. (function (ETextureFilterType) {
  104762. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  104763. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  104764. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  104765. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  104766. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  104767. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  104768. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  104769. var ETextureFormat;
  104770. (function (ETextureFormat) {
  104771. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  104772. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  104773. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  104774. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  104775. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  104776. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  104777. var ECullingType;
  104778. (function (ECullingType) {
  104779. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  104780. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  104781. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  104782. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  104783. var EBlendingFunction;
  104784. (function (EBlendingFunction) {
  104785. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  104786. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  104787. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  104788. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  104789. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  104790. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  104791. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  104792. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  104793. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  104794. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  104795. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  104796. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  104797. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  104798. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  104799. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  104800. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  104801. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  104802. })(BABYLON || (BABYLON = {}));
  104803. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  104804. var BABYLON;
  104805. (function (BABYLON) {
  104806. var GLTF1;
  104807. (function (GLTF1) {
  104808. /**
  104809. * Tokenizer. Used for shaders compatibility
  104810. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  104811. */
  104812. var ETokenType;
  104813. (function (ETokenType) {
  104814. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  104815. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  104816. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  104817. })(ETokenType || (ETokenType = {}));
  104818. var Tokenizer = /** @class */ (function () {
  104819. function Tokenizer(toParse) {
  104820. this._pos = 0;
  104821. this.currentToken = ETokenType.UNKNOWN;
  104822. this.currentIdentifier = "";
  104823. this.currentString = "";
  104824. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  104825. this._toParse = toParse;
  104826. this._maxPos = toParse.length;
  104827. }
  104828. Tokenizer.prototype.getNextToken = function () {
  104829. if (this.isEnd())
  104830. return ETokenType.END_OF_INPUT;
  104831. this.currentString = this.read();
  104832. this.currentToken = ETokenType.UNKNOWN;
  104833. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  104834. this.currentToken = ETokenType.IDENTIFIER;
  104835. this.currentIdentifier = this.currentString;
  104836. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  104837. this.currentIdentifier += this.currentString;
  104838. this.forward();
  104839. }
  104840. }
  104841. return this.currentToken;
  104842. };
  104843. Tokenizer.prototype.peek = function () {
  104844. return this._toParse[this._pos];
  104845. };
  104846. Tokenizer.prototype.read = function () {
  104847. return this._toParse[this._pos++];
  104848. };
  104849. Tokenizer.prototype.forward = function () {
  104850. this._pos++;
  104851. };
  104852. Tokenizer.prototype.isEnd = function () {
  104853. return this._pos >= this._maxPos;
  104854. };
  104855. return Tokenizer;
  104856. }());
  104857. /**
  104858. * Values
  104859. */
  104860. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  104861. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  104862. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  104863. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  104864. /**
  104865. * Parse
  104866. */
  104867. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  104868. for (var buf in parsedBuffers) {
  104869. var parsedBuffer = parsedBuffers[buf];
  104870. gltfRuntime.buffers[buf] = parsedBuffer;
  104871. gltfRuntime.buffersCount++;
  104872. }
  104873. };
  104874. var parseShaders = function (parsedShaders, gltfRuntime) {
  104875. for (var sha in parsedShaders) {
  104876. var parsedShader = parsedShaders[sha];
  104877. gltfRuntime.shaders[sha] = parsedShader;
  104878. gltfRuntime.shaderscount++;
  104879. }
  104880. };
  104881. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  104882. for (var object in parsedObjects) {
  104883. var parsedObject = parsedObjects[object];
  104884. gltfRuntime[runtimeProperty][object] = parsedObject;
  104885. }
  104886. };
  104887. /**
  104888. * Utils
  104889. */
  104890. var normalizeUVs = function (buffer) {
  104891. if (!buffer) {
  104892. return;
  104893. }
  104894. for (var i = 0; i < buffer.length / 2; i++) {
  104895. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  104896. }
  104897. };
  104898. var getAttribute = function (attributeParameter) {
  104899. if (attributeParameter.semantic === "NORMAL") {
  104900. return "normal";
  104901. }
  104902. else if (attributeParameter.semantic === "POSITION") {
  104903. return "position";
  104904. }
  104905. else if (attributeParameter.semantic === "JOINT") {
  104906. return "matricesIndices";
  104907. }
  104908. else if (attributeParameter.semantic === "WEIGHT") {
  104909. return "matricesWeights";
  104910. }
  104911. else if (attributeParameter.semantic === "COLOR") {
  104912. return "color";
  104913. }
  104914. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  104915. var channel = Number(attributeParameter.semantic.split("_")[1]);
  104916. return "uv" + (channel === 0 ? "" : channel + 1);
  104917. }
  104918. return null;
  104919. };
  104920. /**
  104921. * Loads and creates animations
  104922. */
  104923. var loadAnimations = function (gltfRuntime) {
  104924. for (var anim in gltfRuntime.animations) {
  104925. var animation = gltfRuntime.animations[anim];
  104926. if (!animation.channels || !animation.samplers) {
  104927. continue;
  104928. }
  104929. var lastAnimation = null;
  104930. for (var i = 0; i < animation.channels.length; i++) {
  104931. // Get parameters and load buffers
  104932. var channel = animation.channels[i];
  104933. var sampler = animation.samplers[channel.sampler];
  104934. if (!sampler) {
  104935. continue;
  104936. }
  104937. var inputData = null;
  104938. var outputData = null;
  104939. if (animation.parameters) {
  104940. inputData = animation.parameters[sampler.input];
  104941. outputData = animation.parameters[sampler.output];
  104942. }
  104943. else {
  104944. inputData = sampler.input;
  104945. outputData = sampler.output;
  104946. }
  104947. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  104948. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  104949. var targetID = channel.target.id;
  104950. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  104951. if (targetNode === null) {
  104952. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  104953. }
  104954. if (targetNode === null) {
  104955. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  104956. continue;
  104957. }
  104958. var isBone = targetNode instanceof BABYLON.Bone;
  104959. // Get target path (position, rotation or scaling)
  104960. var targetPath = channel.target.path;
  104961. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  104962. if (targetPathIndex !== -1) {
  104963. targetPath = babylonAnimationPaths[targetPathIndex];
  104964. }
  104965. // Determine animation type
  104966. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  104967. if (!isBone) {
  104968. if (targetPath === "rotationQuaternion") {
  104969. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  104970. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  104971. }
  104972. else {
  104973. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  104974. }
  104975. }
  104976. // Create animation and key frames
  104977. var babylonAnimation = null;
  104978. var keys = [];
  104979. var arrayOffset = 0;
  104980. var modifyKey = false;
  104981. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  104982. babylonAnimation = lastAnimation;
  104983. modifyKey = true;
  104984. }
  104985. if (!modifyKey) {
  104986. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  104987. }
  104988. // For each frame
  104989. for (var j = 0; j < bufferInput.length; j++) {
  104990. var value = null;
  104991. if (targetPath === "rotationQuaternion") { // VEC4
  104992. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  104993. arrayOffset += 4;
  104994. }
  104995. else { // Position and scaling are VEC3
  104996. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  104997. arrayOffset += 3;
  104998. }
  104999. if (isBone) {
  105000. var bone = targetNode;
  105001. var translation = BABYLON.Vector3.Zero();
  105002. var rotationQuaternion = new BABYLON.Quaternion();
  105003. var scaling = BABYLON.Vector3.Zero();
  105004. // Warning on decompose
  105005. var mat = bone.getBaseMatrix();
  105006. if (modifyKey && lastAnimation) {
  105007. mat = lastAnimation.getKeys()[j].value;
  105008. }
  105009. mat.decompose(scaling, rotationQuaternion, translation);
  105010. if (targetPath === "position") {
  105011. translation = value;
  105012. }
  105013. else if (targetPath === "rotationQuaternion") {
  105014. rotationQuaternion = value;
  105015. }
  105016. else {
  105017. scaling = value;
  105018. }
  105019. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  105020. }
  105021. if (!modifyKey) {
  105022. keys.push({
  105023. frame: bufferInput[j],
  105024. value: value
  105025. });
  105026. }
  105027. else if (lastAnimation) {
  105028. lastAnimation.getKeys()[j].value = value;
  105029. }
  105030. }
  105031. // Finish
  105032. if (!modifyKey && babylonAnimation) {
  105033. babylonAnimation.setKeys(keys);
  105034. targetNode.animations.push(babylonAnimation);
  105035. }
  105036. lastAnimation = babylonAnimation;
  105037. gltfRuntime.scene.stopAnimation(targetNode);
  105038. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  105039. }
  105040. }
  105041. };
  105042. /**
  105043. * Returns the bones transformation matrix
  105044. */
  105045. var configureBoneTransformation = function (node) {
  105046. var mat = null;
  105047. if (node.translation || node.rotation || node.scale) {
  105048. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  105049. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  105050. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  105051. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  105052. }
  105053. else {
  105054. mat = BABYLON.Matrix.FromArray(node.matrix);
  105055. }
  105056. return mat;
  105057. };
  105058. /**
  105059. * Returns the parent bone
  105060. */
  105061. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  105062. // Try to find
  105063. for (var i = 0; i < newSkeleton.bones.length; i++) {
  105064. if (newSkeleton.bones[i].name === jointName) {
  105065. return newSkeleton.bones[i];
  105066. }
  105067. }
  105068. // Not found, search in gltf nodes
  105069. var nodes = gltfRuntime.nodes;
  105070. for (var nde in nodes) {
  105071. var node = nodes[nde];
  105072. if (!node.jointName) {
  105073. continue;
  105074. }
  105075. var children = node.children;
  105076. for (var i = 0; i < children.length; i++) {
  105077. var child = gltfRuntime.nodes[children[i]];
  105078. if (!child.jointName) {
  105079. continue;
  105080. }
  105081. if (child.jointName === jointName) {
  105082. var mat = configureBoneTransformation(node);
  105083. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  105084. bone.id = nde;
  105085. return bone;
  105086. }
  105087. }
  105088. }
  105089. return null;
  105090. };
  105091. /**
  105092. * Returns the appropriate root node
  105093. */
  105094. var getNodeToRoot = function (nodesToRoot, id) {
  105095. for (var i = 0; i < nodesToRoot.length; i++) {
  105096. var nodeToRoot = nodesToRoot[i];
  105097. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  105098. var child = nodeToRoot.node.children[j];
  105099. if (child === id) {
  105100. return nodeToRoot.bone;
  105101. }
  105102. }
  105103. }
  105104. return null;
  105105. };
  105106. /**
  105107. * Returns the node with the joint name
  105108. */
  105109. var getJointNode = function (gltfRuntime, jointName) {
  105110. var nodes = gltfRuntime.nodes;
  105111. var node = nodes[jointName];
  105112. if (node) {
  105113. return {
  105114. node: node,
  105115. id: jointName
  105116. };
  105117. }
  105118. for (var nde in nodes) {
  105119. node = nodes[nde];
  105120. if (node.jointName === jointName) {
  105121. return {
  105122. node: node,
  105123. id: nde
  105124. };
  105125. }
  105126. }
  105127. return null;
  105128. };
  105129. /**
  105130. * Checks if a nodes is in joints
  105131. */
  105132. var nodeIsInJoints = function (skins, id) {
  105133. for (var i = 0; i < skins.jointNames.length; i++) {
  105134. if (skins.jointNames[i] === id) {
  105135. return true;
  105136. }
  105137. }
  105138. return false;
  105139. };
  105140. /**
  105141. * Fills the nodes to root for bones and builds hierarchy
  105142. */
  105143. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  105144. // Creates nodes for root
  105145. for (var nde in gltfRuntime.nodes) {
  105146. var node = gltfRuntime.nodes[nde];
  105147. var id = nde;
  105148. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  105149. continue;
  105150. }
  105151. // Create node to root bone
  105152. var mat = configureBoneTransformation(node);
  105153. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  105154. bone.id = id;
  105155. nodesToRoot.push({ bone: bone, node: node, id: id });
  105156. }
  105157. // Parenting
  105158. for (var i = 0; i < nodesToRoot.length; i++) {
  105159. var nodeToRoot = nodesToRoot[i];
  105160. var children = nodeToRoot.node.children;
  105161. for (var j = 0; j < children.length; j++) {
  105162. var child = null;
  105163. for (var k = 0; k < nodesToRoot.length; k++) {
  105164. if (nodesToRoot[k].id === children[j]) {
  105165. child = nodesToRoot[k];
  105166. break;
  105167. }
  105168. }
  105169. if (child) {
  105170. child.bone._parent = nodeToRoot.bone;
  105171. nodeToRoot.bone.children.push(child.bone);
  105172. }
  105173. }
  105174. }
  105175. };
  105176. /**
  105177. * Imports a skeleton
  105178. */
  105179. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  105180. if (!newSkeleton) {
  105181. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  105182. }
  105183. if (!skins.babylonSkeleton) {
  105184. return newSkeleton;
  105185. }
  105186. // Find the root bones
  105187. var nodesToRoot = [];
  105188. var nodesToRootToAdd = [];
  105189. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  105190. newSkeleton.bones = [];
  105191. // Joints
  105192. for (var i = 0; i < skins.jointNames.length; i++) {
  105193. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  105194. if (!jointNode) {
  105195. continue;
  105196. }
  105197. var node = jointNode.node;
  105198. if (!node) {
  105199. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  105200. continue;
  105201. }
  105202. var id = jointNode.id;
  105203. // Optimize, if the bone already exists...
  105204. var existingBone = gltfRuntime.scene.getBoneByID(id);
  105205. if (existingBone) {
  105206. newSkeleton.bones.push(existingBone);
  105207. continue;
  105208. }
  105209. // Search for parent bone
  105210. var foundBone = false;
  105211. var parentBone = null;
  105212. for (var j = 0; j < i; j++) {
  105213. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  105214. if (!jointNode_1) {
  105215. continue;
  105216. }
  105217. var joint = jointNode_1.node;
  105218. if (!joint) {
  105219. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  105220. continue;
  105221. }
  105222. var children = joint.children;
  105223. if (!children) {
  105224. continue;
  105225. }
  105226. foundBone = false;
  105227. for (var k = 0; k < children.length; k++) {
  105228. if (children[k] === id) {
  105229. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  105230. foundBone = true;
  105231. break;
  105232. }
  105233. }
  105234. if (foundBone) {
  105235. break;
  105236. }
  105237. }
  105238. // Create bone
  105239. var mat = configureBoneTransformation(node);
  105240. if (!parentBone && nodesToRoot.length > 0) {
  105241. parentBone = getNodeToRoot(nodesToRoot, id);
  105242. if (parentBone) {
  105243. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  105244. nodesToRootToAdd.push(parentBone);
  105245. }
  105246. }
  105247. }
  105248. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  105249. bone.id = id;
  105250. }
  105251. // Polish
  105252. var bones = newSkeleton.bones;
  105253. newSkeleton.bones = [];
  105254. for (var i = 0; i < skins.jointNames.length; i++) {
  105255. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  105256. if (!jointNode) {
  105257. continue;
  105258. }
  105259. for (var j = 0; j < bones.length; j++) {
  105260. if (bones[j].id === jointNode.id) {
  105261. newSkeleton.bones.push(bones[j]);
  105262. break;
  105263. }
  105264. }
  105265. }
  105266. newSkeleton.prepare();
  105267. // Finish
  105268. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  105269. newSkeleton.bones.push(nodesToRootToAdd[i]);
  105270. }
  105271. return newSkeleton;
  105272. };
  105273. /**
  105274. * Imports a mesh and its geometries
  105275. */
  105276. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  105277. if (!newMesh) {
  105278. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  105279. newMesh.id = id;
  105280. }
  105281. if (!node.babylonNode) {
  105282. return newMesh;
  105283. }
  105284. var subMaterials = [];
  105285. var vertexData = null;
  105286. var verticesStarts = new Array();
  105287. var verticesCounts = new Array();
  105288. var indexStarts = new Array();
  105289. var indexCounts = new Array();
  105290. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  105291. var meshID = meshes[meshIndex];
  105292. var mesh = gltfRuntime.meshes[meshID];
  105293. if (!mesh) {
  105294. continue;
  105295. }
  105296. // Positions, normals and UVs
  105297. for (var i = 0; i < mesh.primitives.length; i++) {
  105298. // Temporary vertex data
  105299. var tempVertexData = new BABYLON.VertexData();
  105300. var primitive = mesh.primitives[i];
  105301. if (primitive.mode !== 4) {
  105302. // continue;
  105303. }
  105304. var attributes = primitive.attributes;
  105305. var accessor = null;
  105306. var buffer = null;
  105307. // Set positions, normal and uvs
  105308. for (var semantic in attributes) {
  105309. // Link accessor and buffer view
  105310. accessor = gltfRuntime.accessors[attributes[semantic]];
  105311. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  105312. if (semantic === "NORMAL") {
  105313. tempVertexData.normals = new Float32Array(buffer.length);
  105314. tempVertexData.normals.set(buffer);
  105315. }
  105316. else if (semantic === "POSITION") {
  105317. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  105318. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  105319. for (var j = 0; j < buffer.length; j += 4) {
  105320. tempVertexData.positions[j] = buffer[j];
  105321. tempVertexData.positions[j + 1] = buffer[j + 1];
  105322. tempVertexData.positions[j + 2] = buffer[j + 2];
  105323. }
  105324. }
  105325. else {
  105326. tempVertexData.positions = new Float32Array(buffer.length);
  105327. tempVertexData.positions.set(buffer);
  105328. }
  105329. verticesCounts.push(tempVertexData.positions.length);
  105330. }
  105331. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  105332. var channel = Number(semantic.split("_")[1]);
  105333. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  105334. var uvs = new Float32Array(buffer.length);
  105335. uvs.set(buffer);
  105336. normalizeUVs(uvs);
  105337. tempVertexData.set(uvs, uvKind);
  105338. }
  105339. else if (semantic === "JOINT") {
  105340. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  105341. tempVertexData.matricesIndices.set(buffer);
  105342. }
  105343. else if (semantic === "WEIGHT") {
  105344. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  105345. tempVertexData.matricesWeights.set(buffer);
  105346. }
  105347. else if (semantic === "COLOR") {
  105348. tempVertexData.colors = new Float32Array(buffer.length);
  105349. tempVertexData.colors.set(buffer);
  105350. }
  105351. }
  105352. // Indices
  105353. accessor = gltfRuntime.accessors[primitive.indices];
  105354. if (accessor) {
  105355. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  105356. tempVertexData.indices = new Int32Array(buffer.length);
  105357. tempVertexData.indices.set(buffer);
  105358. indexCounts.push(tempVertexData.indices.length);
  105359. }
  105360. else {
  105361. // Set indices on the fly
  105362. var indices = [];
  105363. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  105364. indices.push(j);
  105365. }
  105366. tempVertexData.indices = new Int32Array(indices);
  105367. indexCounts.push(tempVertexData.indices.length);
  105368. }
  105369. if (!vertexData) {
  105370. vertexData = tempVertexData;
  105371. }
  105372. else {
  105373. vertexData.merge(tempVertexData);
  105374. }
  105375. // Sub material
  105376. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  105377. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  105378. // Update vertices start and index start
  105379. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  105380. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  105381. }
  105382. }
  105383. var material;
  105384. if (subMaterials.length > 1) {
  105385. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  105386. material.subMaterials = subMaterials;
  105387. }
  105388. else {
  105389. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  105390. }
  105391. if (subMaterials.length === 1) {
  105392. material = subMaterials[0];
  105393. }
  105394. if (!newMesh.material) {
  105395. newMesh.material = material;
  105396. }
  105397. // Apply geometry
  105398. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  105399. newMesh.computeWorldMatrix(true);
  105400. // Apply submeshes
  105401. newMesh.subMeshes = [];
  105402. var index = 0;
  105403. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  105404. var meshID = meshes[meshIndex];
  105405. var mesh = gltfRuntime.meshes[meshID];
  105406. if (!mesh) {
  105407. continue;
  105408. }
  105409. for (var i = 0; i < mesh.primitives.length; i++) {
  105410. if (mesh.primitives[i].mode !== 4) {
  105411. //continue;
  105412. }
  105413. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  105414. index++;
  105415. }
  105416. }
  105417. // Finish
  105418. return newMesh;
  105419. };
  105420. /**
  105421. * Configure node transformation from position, rotation and scaling
  105422. */
  105423. var configureNode = function (newNode, position, rotation, scaling) {
  105424. if (newNode.position) {
  105425. newNode.position = position;
  105426. }
  105427. if (newNode.rotationQuaternion || newNode.rotation) {
  105428. newNode.rotationQuaternion = rotation;
  105429. }
  105430. if (newNode.scaling) {
  105431. newNode.scaling = scaling;
  105432. }
  105433. };
  105434. /**
  105435. * Configures node from transformation matrix
  105436. */
  105437. var configureNodeFromMatrix = function (newNode, node, parent) {
  105438. if (node.matrix) {
  105439. var position = new BABYLON.Vector3(0, 0, 0);
  105440. var rotation = new BABYLON.Quaternion();
  105441. var scaling = new BABYLON.Vector3(0, 0, 0);
  105442. var mat = BABYLON.Matrix.FromArray(node.matrix);
  105443. mat.decompose(scaling, rotation, position);
  105444. configureNode(newNode, position, rotation, scaling);
  105445. }
  105446. else if (node.translation && node.rotation && node.scale) {
  105447. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  105448. }
  105449. newNode.computeWorldMatrix(true);
  105450. };
  105451. /**
  105452. * Imports a node
  105453. */
  105454. var importNode = function (gltfRuntime, node, id, parent) {
  105455. var lastNode = null;
  105456. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  105457. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  105458. return null;
  105459. }
  105460. }
  105461. // Meshes
  105462. if (node.skin) {
  105463. if (node.meshes) {
  105464. var skin = gltfRuntime.skins[node.skin];
  105465. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  105466. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  105467. if (newMesh.skeleton === null) {
  105468. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  105469. if (!skin.babylonSkeleton) {
  105470. skin.babylonSkeleton = newMesh.skeleton;
  105471. }
  105472. }
  105473. lastNode = newMesh;
  105474. }
  105475. }
  105476. else if (node.meshes) {
  105477. /**
  105478. * Improve meshes property
  105479. */
  105480. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  105481. lastNode = newMesh;
  105482. }
  105483. // Lights
  105484. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  105485. var light = gltfRuntime.lights[node.light];
  105486. if (light) {
  105487. if (light.type === "ambient") {
  105488. var ambienLight = light[light.type];
  105489. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  105490. hemiLight.name = node.name || "";
  105491. if (ambienLight.color) {
  105492. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  105493. }
  105494. lastNode = hemiLight;
  105495. }
  105496. else if (light.type === "directional") {
  105497. var directionalLight = light[light.type];
  105498. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  105499. dirLight.name = node.name || "";
  105500. if (directionalLight.color) {
  105501. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  105502. }
  105503. lastNode = dirLight;
  105504. }
  105505. else if (light.type === "point") {
  105506. var pointLight = light[light.type];
  105507. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  105508. ptLight.name = node.name || "";
  105509. if (pointLight.color) {
  105510. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  105511. }
  105512. lastNode = ptLight;
  105513. }
  105514. else if (light.type === "spot") {
  105515. var spotLight = light[light.type];
  105516. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  105517. spLight.name = node.name || "";
  105518. if (spotLight.color) {
  105519. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  105520. }
  105521. if (spotLight.fallOfAngle) {
  105522. spLight.angle = spotLight.fallOfAngle;
  105523. }
  105524. if (spotLight.fallOffExponent) {
  105525. spLight.exponent = spotLight.fallOffExponent;
  105526. }
  105527. lastNode = spLight;
  105528. }
  105529. }
  105530. }
  105531. // Cameras
  105532. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  105533. var camera = gltfRuntime.cameras[node.camera];
  105534. if (camera) {
  105535. if (camera.type === "orthographic") {
  105536. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  105537. orthoCamera.name = node.name || "";
  105538. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  105539. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  105540. lastNode = orthoCamera;
  105541. }
  105542. else if (camera.type === "perspective") {
  105543. var perspectiveCamera = camera[camera.type];
  105544. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  105545. persCamera.name = node.name || "";
  105546. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  105547. if (!perspectiveCamera.aspectRatio) {
  105548. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  105549. }
  105550. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  105551. persCamera.maxZ = perspectiveCamera.zfar;
  105552. persCamera.minZ = perspectiveCamera.znear;
  105553. }
  105554. lastNode = persCamera;
  105555. }
  105556. }
  105557. }
  105558. // Empty node
  105559. if (!node.jointName) {
  105560. if (node.babylonNode) {
  105561. return node.babylonNode;
  105562. }
  105563. else if (lastNode === null) {
  105564. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  105565. node.babylonNode = dummy;
  105566. lastNode = dummy;
  105567. }
  105568. }
  105569. if (lastNode !== null) {
  105570. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  105571. configureNodeFromMatrix(lastNode, node, parent);
  105572. }
  105573. else {
  105574. var translation = node.translation || [0, 0, 0];
  105575. var rotation = node.rotation || [0, 0, 0, 1];
  105576. var scale = node.scale || [1, 1, 1];
  105577. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  105578. }
  105579. lastNode.updateCache(true);
  105580. node.babylonNode = lastNode;
  105581. }
  105582. return lastNode;
  105583. };
  105584. /**
  105585. * Traverses nodes and creates them
  105586. */
  105587. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  105588. if (meshIncluded === void 0) { meshIncluded = false; }
  105589. var node = gltfRuntime.nodes[id];
  105590. var newNode = null;
  105591. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  105592. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  105593. meshIncluded = true;
  105594. }
  105595. else {
  105596. meshIncluded = false;
  105597. }
  105598. }
  105599. else {
  105600. meshIncluded = true;
  105601. }
  105602. if (!node.jointName && meshIncluded) {
  105603. newNode = importNode(gltfRuntime, node, id, parent);
  105604. if (newNode !== null) {
  105605. newNode.id = id;
  105606. newNode.parent = parent;
  105607. }
  105608. }
  105609. if (node.children) {
  105610. for (var i = 0; i < node.children.length; i++) {
  105611. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  105612. }
  105613. }
  105614. };
  105615. /**
  105616. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  105617. */
  105618. var postLoad = function (gltfRuntime) {
  105619. // Nodes
  105620. var currentScene = gltfRuntime.currentScene;
  105621. if (currentScene) {
  105622. for (var i = 0; i < currentScene.nodes.length; i++) {
  105623. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  105624. }
  105625. }
  105626. else {
  105627. for (var thing in gltfRuntime.scenes) {
  105628. currentScene = gltfRuntime.scenes[thing];
  105629. for (var i = 0; i < currentScene.nodes.length; i++) {
  105630. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  105631. }
  105632. }
  105633. }
  105634. // Set animations
  105635. loadAnimations(gltfRuntime);
  105636. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  105637. var skeleton = gltfRuntime.scene.skeletons[i];
  105638. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  105639. }
  105640. };
  105641. /**
  105642. * onBind shaderrs callback to set uniforms and matrices
  105643. */
  105644. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  105645. var materialValues = material.values || technique.parameters;
  105646. for (var unif in unTreatedUniforms) {
  105647. var uniform = unTreatedUniforms[unif];
  105648. var type = uniform.type;
  105649. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  105650. if (uniform.semantic && !uniform.source && !uniform.node) {
  105651. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  105652. }
  105653. else if (uniform.semantic && (uniform.source || uniform.node)) {
  105654. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  105655. if (source === null) {
  105656. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  105657. }
  105658. if (source === null) {
  105659. continue;
  105660. }
  105661. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  105662. }
  105663. }
  105664. else {
  105665. var value = materialValues[technique.uniforms[unif]];
  105666. if (!value) {
  105667. continue;
  105668. }
  105669. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  105670. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  105671. if (texture === null || texture === undefined) {
  105672. continue;
  105673. }
  105674. shaderMaterial.getEffect().setTexture(unif, texture);
  105675. }
  105676. else {
  105677. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  105678. }
  105679. }
  105680. }
  105681. onSuccess(shaderMaterial);
  105682. };
  105683. /**
  105684. * Prepare uniforms to send the only one time
  105685. * Loads the appropriate textures
  105686. */
  105687. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  105688. var materialValues = material.values || technique.parameters;
  105689. var techniqueUniforms = technique.uniforms;
  105690. /**
  105691. * Prepare values here (not matrices)
  105692. */
  105693. for (var unif in unTreatedUniforms) {
  105694. var uniform = unTreatedUniforms[unif];
  105695. var type = uniform.type;
  105696. var value = materialValues[techniqueUniforms[unif]];
  105697. if (value === undefined) {
  105698. // In case the value is the same for all materials
  105699. value = uniform.value;
  105700. }
  105701. if (!value) {
  105702. continue;
  105703. }
  105704. var onLoadTexture = function (uniformName) {
  105705. return function (texture) {
  105706. if (uniform.value && uniformName) {
  105707. // Static uniform
  105708. shaderMaterial.setTexture(uniformName, texture);
  105709. delete unTreatedUniforms[uniformName];
  105710. }
  105711. };
  105712. };
  105713. // Texture (sampler2D)
  105714. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  105715. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  105716. }
  105717. // Others
  105718. else {
  105719. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  105720. // Static uniform
  105721. delete unTreatedUniforms[unif];
  105722. }
  105723. }
  105724. }
  105725. };
  105726. /**
  105727. * Shader compilation failed
  105728. */
  105729. var onShaderCompileError = function (program, shaderMaterial, onError) {
  105730. return function (effect, error) {
  105731. shaderMaterial.dispose(true);
  105732. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  105733. };
  105734. };
  105735. /**
  105736. * Shader compilation success
  105737. */
  105738. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  105739. return function (_) {
  105740. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  105741. shaderMaterial.onBind = function (mesh) {
  105742. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  105743. };
  105744. };
  105745. };
  105746. /**
  105747. * Returns the appropriate uniform if already handled by babylon
  105748. */
  105749. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  105750. for (var unif in technique.uniforms) {
  105751. var uniform = technique.uniforms[unif];
  105752. var uniformParameter = technique.parameters[uniform];
  105753. if (tokenizer.currentIdentifier === unif) {
  105754. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  105755. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  105756. if (transformIndex !== -1) {
  105757. delete unTreatedUniforms[unif];
  105758. return babylonTransforms[transformIndex];
  105759. }
  105760. }
  105761. }
  105762. }
  105763. return tokenizer.currentIdentifier;
  105764. };
  105765. /**
  105766. * All shaders loaded. Create materials one by one
  105767. */
  105768. var importMaterials = function (gltfRuntime) {
  105769. // Create materials
  105770. for (var mat in gltfRuntime.materials) {
  105771. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  105772. }
  105773. };
  105774. /**
  105775. * Implementation of the base glTF spec
  105776. */
  105777. var GLTFLoaderBase = /** @class */ (function () {
  105778. function GLTFLoaderBase() {
  105779. }
  105780. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  105781. var gltfRuntime = {
  105782. extensions: {},
  105783. accessors: {},
  105784. buffers: {},
  105785. bufferViews: {},
  105786. meshes: {},
  105787. lights: {},
  105788. cameras: {},
  105789. nodes: {},
  105790. images: {},
  105791. textures: {},
  105792. shaders: {},
  105793. programs: {},
  105794. samplers: {},
  105795. techniques: {},
  105796. materials: {},
  105797. animations: {},
  105798. skins: {},
  105799. extensionsUsed: [],
  105800. scenes: {},
  105801. buffersCount: 0,
  105802. shaderscount: 0,
  105803. scene: scene,
  105804. rootUrl: rootUrl,
  105805. loadedBufferCount: 0,
  105806. loadedBufferViews: {},
  105807. loadedShaderCount: 0,
  105808. importOnlyMeshes: false,
  105809. dummyNodes: []
  105810. };
  105811. // Parse
  105812. if (parsedData.extensions) {
  105813. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  105814. }
  105815. if (parsedData.extensionsUsed) {
  105816. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  105817. }
  105818. if (parsedData.buffers) {
  105819. parseBuffers(parsedData.buffers, gltfRuntime);
  105820. }
  105821. if (parsedData.bufferViews) {
  105822. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  105823. }
  105824. if (parsedData.accessors) {
  105825. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  105826. }
  105827. if (parsedData.meshes) {
  105828. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  105829. }
  105830. if (parsedData.lights) {
  105831. parseObject(parsedData.lights, "lights", gltfRuntime);
  105832. }
  105833. if (parsedData.cameras) {
  105834. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  105835. }
  105836. if (parsedData.nodes) {
  105837. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  105838. }
  105839. if (parsedData.images) {
  105840. parseObject(parsedData.images, "images", gltfRuntime);
  105841. }
  105842. if (parsedData.textures) {
  105843. parseObject(parsedData.textures, "textures", gltfRuntime);
  105844. }
  105845. if (parsedData.shaders) {
  105846. parseShaders(parsedData.shaders, gltfRuntime);
  105847. }
  105848. if (parsedData.programs) {
  105849. parseObject(parsedData.programs, "programs", gltfRuntime);
  105850. }
  105851. if (parsedData.samplers) {
  105852. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  105853. }
  105854. if (parsedData.techniques) {
  105855. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  105856. }
  105857. if (parsedData.materials) {
  105858. parseObject(parsedData.materials, "materials", gltfRuntime);
  105859. }
  105860. if (parsedData.animations) {
  105861. parseObject(parsedData.animations, "animations", gltfRuntime);
  105862. }
  105863. if (parsedData.skins) {
  105864. parseObject(parsedData.skins, "skins", gltfRuntime);
  105865. }
  105866. if (parsedData.scenes) {
  105867. gltfRuntime.scenes = parsedData.scenes;
  105868. }
  105869. if (parsedData.scene && parsedData.scenes) {
  105870. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  105871. }
  105872. return gltfRuntime;
  105873. };
  105874. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  105875. var buffer = gltfRuntime.buffers[id];
  105876. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  105877. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  105878. }
  105879. else {
  105880. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  105881. if (request) {
  105882. onError(request.status + " " + request.statusText);
  105883. }
  105884. });
  105885. }
  105886. };
  105887. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  105888. var texture = gltfRuntime.textures[id];
  105889. if (!texture || !texture.source) {
  105890. onError("");
  105891. return;
  105892. }
  105893. if (texture.babylonTexture) {
  105894. onSuccess(null);
  105895. return;
  105896. }
  105897. var source = gltfRuntime.images[texture.source];
  105898. if (BABYLON.Tools.IsBase64(source.uri)) {
  105899. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  105900. }
  105901. else {
  105902. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  105903. if (request) {
  105904. onError(request.status + " " + request.statusText);
  105905. }
  105906. });
  105907. }
  105908. };
  105909. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  105910. var texture = gltfRuntime.textures[id];
  105911. if (texture.babylonTexture) {
  105912. onSuccess(texture.babylonTexture);
  105913. return;
  105914. }
  105915. var sampler = gltfRuntime.samplers[texture.sampler];
  105916. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  105917. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  105918. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  105919. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  105920. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  105921. var blob = new Blob([buffer]);
  105922. var blobURL = URL.createObjectURL(blob);
  105923. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  105924. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  105925. if (sampler.wrapS !== undefined) {
  105926. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  105927. }
  105928. if (sampler.wrapT !== undefined) {
  105929. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  105930. }
  105931. newTexture.name = id;
  105932. texture.babylonTexture = newTexture;
  105933. onSuccess(newTexture);
  105934. };
  105935. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  105936. var shader = gltfRuntime.shaders[id];
  105937. if (BABYLON.Tools.IsBase64(shader.uri)) {
  105938. var shaderString = atob(shader.uri.split(",")[1]);
  105939. if (onSuccess) {
  105940. onSuccess(shaderString);
  105941. }
  105942. }
  105943. else {
  105944. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  105945. if (request && onError) {
  105946. onError(request.status + " " + request.statusText);
  105947. }
  105948. });
  105949. }
  105950. };
  105951. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  105952. var material = gltfRuntime.materials[id];
  105953. if (!material.technique) {
  105954. if (onError) {
  105955. onError("No technique found.");
  105956. }
  105957. return;
  105958. }
  105959. var technique = gltfRuntime.techniques[material.technique];
  105960. if (!technique) {
  105961. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  105962. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  105963. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  105964. onSuccess(defaultMaterial);
  105965. return;
  105966. }
  105967. var program = gltfRuntime.programs[technique.program];
  105968. var states = technique.states;
  105969. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  105970. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  105971. var newVertexShader = "";
  105972. var newPixelShader = "";
  105973. var vertexTokenizer = new Tokenizer(vertexShader);
  105974. var pixelTokenizer = new Tokenizer(pixelShader);
  105975. var unTreatedUniforms = {};
  105976. var uniforms = [];
  105977. var attributes = [];
  105978. var samplers = [];
  105979. // Fill uniform, sampler2D and attributes
  105980. for (var unif in technique.uniforms) {
  105981. var uniform = technique.uniforms[unif];
  105982. var uniformParameter = technique.parameters[uniform];
  105983. unTreatedUniforms[unif] = uniformParameter;
  105984. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  105985. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  105986. if (transformIndex !== -1) {
  105987. uniforms.push(babylonTransforms[transformIndex]);
  105988. delete unTreatedUniforms[unif];
  105989. }
  105990. else {
  105991. uniforms.push(unif);
  105992. }
  105993. }
  105994. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  105995. samplers.push(unif);
  105996. }
  105997. else {
  105998. uniforms.push(unif);
  105999. }
  106000. }
  106001. for (var attr in technique.attributes) {
  106002. var attribute = technique.attributes[attr];
  106003. var attributeParameter = technique.parameters[attribute];
  106004. if (attributeParameter.semantic) {
  106005. attributes.push(getAttribute(attributeParameter));
  106006. }
  106007. }
  106008. // Configure vertex shader
  106009. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  106010. var tokenType = vertexTokenizer.currentToken;
  106011. if (tokenType !== ETokenType.IDENTIFIER) {
  106012. newVertexShader += vertexTokenizer.currentString;
  106013. continue;
  106014. }
  106015. var foundAttribute = false;
  106016. for (var attr in technique.attributes) {
  106017. var attribute = technique.attributes[attr];
  106018. var attributeParameter = technique.parameters[attribute];
  106019. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  106020. newVertexShader += getAttribute(attributeParameter);
  106021. foundAttribute = true;
  106022. break;
  106023. }
  106024. }
  106025. if (foundAttribute) {
  106026. continue;
  106027. }
  106028. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  106029. }
  106030. // Configure pixel shader
  106031. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  106032. var tokenType = pixelTokenizer.currentToken;
  106033. if (tokenType !== ETokenType.IDENTIFIER) {
  106034. newPixelShader += pixelTokenizer.currentString;
  106035. continue;
  106036. }
  106037. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  106038. }
  106039. // Create shader material
  106040. var shaderPath = {
  106041. vertex: program.vertexShader + id,
  106042. fragment: program.fragmentShader + id
  106043. };
  106044. var options = {
  106045. attributes: attributes,
  106046. uniforms: uniforms,
  106047. samplers: samplers,
  106048. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  106049. };
  106050. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  106051. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  106052. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  106053. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  106054. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  106055. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  106056. if (states && states.functions) {
  106057. var functions = states.functions;
  106058. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  106059. shaderMaterial.backFaceCulling = false;
  106060. }
  106061. var blendFunc = functions.blendFuncSeparate;
  106062. if (blendFunc) {
  106063. 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) {
  106064. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  106065. }
  106066. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  106067. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  106068. }
  106069. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  106070. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  106071. }
  106072. 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) {
  106073. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  106074. }
  106075. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  106076. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  106077. }
  106078. 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) {
  106079. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  106080. }
  106081. }
  106082. }
  106083. };
  106084. return GLTFLoaderBase;
  106085. }());
  106086. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  106087. /**
  106088. * glTF V1 Loader
  106089. */
  106090. var GLTFLoader = /** @class */ (function () {
  106091. function GLTFLoader() {
  106092. // #region Stubs for IGLTFLoader interface
  106093. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  106094. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  106095. this.compileMaterials = false;
  106096. this.useClipPlane = false;
  106097. this.compileShadowGenerators = false;
  106098. this.transparencyAsCoverage = false;
  106099. this._normalizeAnimationGroupsToBeginAtZero = true;
  106100. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  106101. this.onMeshLoadedObservable = new BABYLON.Observable();
  106102. this.onTextureLoadedObservable = new BABYLON.Observable();
  106103. this.onMaterialLoadedObservable = new BABYLON.Observable();
  106104. this.onCameraLoadedObservable = new BABYLON.Observable();
  106105. this.onCompleteObservable = new BABYLON.Observable();
  106106. this.onDisposeObservable = new BABYLON.Observable();
  106107. this.onExtensionLoadedObservable = new BABYLON.Observable();
  106108. this.state = null;
  106109. }
  106110. GLTFLoader.RegisterExtension = function (extension) {
  106111. if (GLTFLoader.Extensions[extension.name]) {
  106112. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  106113. return;
  106114. }
  106115. GLTFLoader.Extensions[extension.name] = extension;
  106116. };
  106117. GLTFLoader.prototype.dispose = function () { };
  106118. // #endregion
  106119. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  106120. var _this = this;
  106121. scene.useRightHandedSystem = true;
  106122. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  106123. gltfRuntime.importOnlyMeshes = true;
  106124. if (meshesNames === "") {
  106125. gltfRuntime.importMeshesNames = [];
  106126. }
  106127. else if (typeof meshesNames === "string") {
  106128. gltfRuntime.importMeshesNames = [meshesNames];
  106129. }
  106130. else if (meshesNames && !(meshesNames instanceof Array)) {
  106131. gltfRuntime.importMeshesNames = [meshesNames];
  106132. }
  106133. else {
  106134. gltfRuntime.importMeshesNames = [];
  106135. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  106136. }
  106137. // Create nodes
  106138. _this._createNodes(gltfRuntime);
  106139. var meshes = new Array();
  106140. var skeletons = new Array();
  106141. // Fill arrays of meshes and skeletons
  106142. for (var nde in gltfRuntime.nodes) {
  106143. var node = gltfRuntime.nodes[nde];
  106144. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  106145. meshes.push(node.babylonNode);
  106146. }
  106147. }
  106148. for (var skl in gltfRuntime.skins) {
  106149. var skin = gltfRuntime.skins[skl];
  106150. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  106151. skeletons.push(skin.babylonSkeleton);
  106152. }
  106153. }
  106154. // Load buffers, shaders, materials, etc.
  106155. _this._loadBuffersAsync(gltfRuntime, function () {
  106156. _this._loadShadersAsync(gltfRuntime, function () {
  106157. importMaterials(gltfRuntime);
  106158. postLoad(gltfRuntime);
  106159. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  106160. onSuccess(meshes, skeletons);
  106161. }
  106162. });
  106163. }, onProgress);
  106164. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  106165. onSuccess(meshes, skeletons);
  106166. }
  106167. }, onError);
  106168. return true;
  106169. };
  106170. /**
  106171. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  106172. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  106173. * @param scene the scene the meshes should be added to
  106174. * @param data gltf data containing information of the meshes in a loaded file
  106175. * @param rootUrl root url to load from
  106176. * @param onProgress event that fires when loading progress has occured
  106177. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  106178. */
  106179. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  106180. var _this = this;
  106181. return new Promise(function (resolve, reject) {
  106182. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  106183. resolve({
  106184. meshes: meshes,
  106185. particleSystems: [],
  106186. skeletons: skeletons,
  106187. animationGroups: []
  106188. });
  106189. }, onProgress, function (message) {
  106190. reject(new Error(message));
  106191. });
  106192. });
  106193. };
  106194. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  106195. var _this = this;
  106196. scene.useRightHandedSystem = true;
  106197. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  106198. // Load runtime extensios
  106199. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  106200. // Create nodes
  106201. _this._createNodes(gltfRuntime);
  106202. // Load buffers, shaders, materials, etc.
  106203. _this._loadBuffersAsync(gltfRuntime, function () {
  106204. _this._loadShadersAsync(gltfRuntime, function () {
  106205. importMaterials(gltfRuntime);
  106206. postLoad(gltfRuntime);
  106207. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  106208. onSuccess();
  106209. }
  106210. });
  106211. });
  106212. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  106213. onSuccess();
  106214. }
  106215. }, onError);
  106216. }, onError);
  106217. };
  106218. /**
  106219. * Imports all objects from a loaded gltf file and adds them to the scene
  106220. * @param scene the scene the objects should be added to
  106221. * @param data gltf data containing information of the meshes in a loaded file
  106222. * @param rootUrl root url to load from
  106223. * @param onProgress event that fires when loading progress has occured
  106224. * @returns a promise which completes when objects have been loaded to the scene
  106225. */
  106226. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  106227. var _this = this;
  106228. return new Promise(function (resolve, reject) {
  106229. _this._loadAsync(scene, data, rootUrl, function () {
  106230. resolve();
  106231. }, onProgress, function (message) {
  106232. reject(new Error(message));
  106233. });
  106234. });
  106235. };
  106236. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  106237. var hasShaders = false;
  106238. var processShader = function (sha, shader) {
  106239. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  106240. if (shaderString instanceof ArrayBuffer) {
  106241. return;
  106242. }
  106243. gltfRuntime.loadedShaderCount++;
  106244. if (shaderString) {
  106245. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  106246. }
  106247. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  106248. onload();
  106249. }
  106250. }, function () {
  106251. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  106252. });
  106253. };
  106254. for (var sha in gltfRuntime.shaders) {
  106255. hasShaders = true;
  106256. var shader = gltfRuntime.shaders[sha];
  106257. if (shader) {
  106258. processShader.bind(this, sha, shader)();
  106259. }
  106260. else {
  106261. BABYLON.Tools.Error("No shader named: " + sha);
  106262. }
  106263. }
  106264. if (!hasShaders) {
  106265. onload();
  106266. }
  106267. };
  106268. ;
  106269. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  106270. var hasBuffers = false;
  106271. var processBuffer = function (buf, buffer) {
  106272. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  106273. gltfRuntime.loadedBufferCount++;
  106274. if (bufferView) {
  106275. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  106276. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  106277. }
  106278. gltfRuntime.loadedBufferViews[buf] = bufferView;
  106279. }
  106280. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  106281. onLoad();
  106282. }
  106283. }, function () {
  106284. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  106285. });
  106286. };
  106287. for (var buf in gltfRuntime.buffers) {
  106288. hasBuffers = true;
  106289. var buffer = gltfRuntime.buffers[buf];
  106290. if (buffer) {
  106291. processBuffer.bind(this, buf, buffer)();
  106292. }
  106293. else {
  106294. BABYLON.Tools.Error("No buffer named: " + buf);
  106295. }
  106296. }
  106297. if (!hasBuffers) {
  106298. onLoad();
  106299. }
  106300. };
  106301. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  106302. var currentScene = gltfRuntime.currentScene;
  106303. if (currentScene) {
  106304. // Only one scene even if multiple scenes are defined
  106305. for (var i = 0; i < currentScene.nodes.length; i++) {
  106306. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  106307. }
  106308. }
  106309. else {
  106310. // Load all scenes
  106311. for (var thing in gltfRuntime.scenes) {
  106312. currentScene = gltfRuntime.scenes[thing];
  106313. for (var i = 0; i < currentScene.nodes.length; i++) {
  106314. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  106315. }
  106316. }
  106317. }
  106318. };
  106319. GLTFLoader.Extensions = {};
  106320. return GLTFLoader;
  106321. }());
  106322. GLTF1.GLTFLoader = GLTFLoader;
  106323. ;
  106324. BABYLON.GLTFFileLoader._CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  106325. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106326. })(BABYLON || (BABYLON = {}));
  106327. //# sourceMappingURL=babylon.glTFLoader.js.map
  106328. var BABYLON;
  106329. (function (BABYLON) {
  106330. var GLTF1;
  106331. (function (GLTF1) {
  106332. /**
  106333. * Utils functions for GLTF
  106334. */
  106335. var GLTFUtils = /** @class */ (function () {
  106336. function GLTFUtils() {
  106337. }
  106338. /**
  106339. * Sets the given "parameter" matrix
  106340. * @param scene: the {BABYLON.Scene} object
  106341. * @param source: the source node where to pick the matrix
  106342. * @param parameter: the GLTF technique parameter
  106343. * @param uniformName: the name of the shader's uniform
  106344. * @param shaderMaterial: the shader material
  106345. */
  106346. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  106347. var mat = null;
  106348. if (parameter.semantic === "MODEL") {
  106349. mat = source.getWorldMatrix();
  106350. }
  106351. else if (parameter.semantic === "PROJECTION") {
  106352. mat = scene.getProjectionMatrix();
  106353. }
  106354. else if (parameter.semantic === "VIEW") {
  106355. mat = scene.getViewMatrix();
  106356. }
  106357. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  106358. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  106359. }
  106360. else if (parameter.semantic === "MODELVIEW") {
  106361. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  106362. }
  106363. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  106364. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  106365. }
  106366. else if (parameter.semantic === "MODELINVERSE") {
  106367. mat = source.getWorldMatrix().invert();
  106368. }
  106369. else if (parameter.semantic === "VIEWINVERSE") {
  106370. mat = scene.getViewMatrix().invert();
  106371. }
  106372. else if (parameter.semantic === "PROJECTIONINVERSE") {
  106373. mat = scene.getProjectionMatrix().invert();
  106374. }
  106375. else if (parameter.semantic === "MODELVIEWINVERSE") {
  106376. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  106377. }
  106378. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  106379. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  106380. }
  106381. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  106382. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  106383. }
  106384. else {
  106385. debugger;
  106386. }
  106387. if (mat) {
  106388. switch (parameter.type) {
  106389. case GLTF1.EParameterType.FLOAT_MAT2:
  106390. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  106391. break;
  106392. case GLTF1.EParameterType.FLOAT_MAT3:
  106393. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  106394. break;
  106395. case GLTF1.EParameterType.FLOAT_MAT4:
  106396. shaderMaterial.setMatrix(uniformName, mat);
  106397. break;
  106398. default: break;
  106399. }
  106400. }
  106401. };
  106402. /**
  106403. * Sets the given "parameter" matrix
  106404. * @param shaderMaterial: the shader material
  106405. * @param uniform: the name of the shader's uniform
  106406. * @param value: the value of the uniform
  106407. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  106408. */
  106409. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  106410. switch (type) {
  106411. case GLTF1.EParameterType.FLOAT:
  106412. shaderMaterial.setFloat(uniform, value);
  106413. return true;
  106414. case GLTF1.EParameterType.FLOAT_VEC2:
  106415. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  106416. return true;
  106417. case GLTF1.EParameterType.FLOAT_VEC3:
  106418. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  106419. return true;
  106420. case GLTF1.EParameterType.FLOAT_VEC4:
  106421. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  106422. return true;
  106423. default: return false;
  106424. }
  106425. };
  106426. /**
  106427. * Returns the wrap mode of the texture
  106428. * @param mode: the mode value
  106429. */
  106430. GLTFUtils.GetWrapMode = function (mode) {
  106431. switch (mode) {
  106432. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  106433. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  106434. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  106435. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  106436. }
  106437. };
  106438. /**
  106439. * Returns the byte stride giving an accessor
  106440. * @param accessor: the GLTF accessor objet
  106441. */
  106442. GLTFUtils.GetByteStrideFromType = function (accessor) {
  106443. // Needs this function since "byteStride" isn't requiered in glTF format
  106444. var type = accessor.type;
  106445. switch (type) {
  106446. case "VEC2": return 2;
  106447. case "VEC3": return 3;
  106448. case "VEC4": return 4;
  106449. case "MAT2": return 4;
  106450. case "MAT3": return 9;
  106451. case "MAT4": return 16;
  106452. default: return 1;
  106453. }
  106454. };
  106455. /**
  106456. * Returns the texture filter mode giving a mode value
  106457. * @param mode: the filter mode value
  106458. */
  106459. GLTFUtils.GetTextureFilterMode = function (mode) {
  106460. switch (mode) {
  106461. case GLTF1.ETextureFilterType.LINEAR:
  106462. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  106463. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  106464. case GLTF1.ETextureFilterType.NEAREST:
  106465. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  106466. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  106467. }
  106468. };
  106469. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  106470. var byteOffset = bufferView.byteOffset + byteOffset;
  106471. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  106472. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  106473. throw new Error("Buffer access is out of range");
  106474. }
  106475. var buffer = loadedBufferView.buffer;
  106476. byteOffset += loadedBufferView.byteOffset;
  106477. switch (componentType) {
  106478. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  106479. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  106480. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  106481. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  106482. default: return new Float32Array(buffer, byteOffset, byteLength);
  106483. }
  106484. };
  106485. /**
  106486. * Returns a buffer from its accessor
  106487. * @param gltfRuntime: the GLTF runtime
  106488. * @param accessor: the GLTF accessor
  106489. */
  106490. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  106491. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  106492. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  106493. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  106494. };
  106495. /**
  106496. * Decodes a buffer view into a string
  106497. * @param view: the buffer view
  106498. */
  106499. GLTFUtils.DecodeBufferToText = function (view) {
  106500. var result = "";
  106501. var length = view.byteLength;
  106502. for (var i = 0; i < length; ++i) {
  106503. result += String.fromCharCode(view[i]);
  106504. }
  106505. return result;
  106506. };
  106507. /**
  106508. * Returns the default material of gltf. Related to
  106509. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  106510. * @param scene: the Babylon.js scene
  106511. */
  106512. GLTFUtils.GetDefaultMaterial = function (scene) {
  106513. if (!GLTFUtils._DefaultMaterial) {
  106514. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  106515. "precision highp float;",
  106516. "",
  106517. "uniform mat4 worldView;",
  106518. "uniform mat4 projection;",
  106519. "",
  106520. "attribute vec3 position;",
  106521. "",
  106522. "void main(void)",
  106523. "{",
  106524. " gl_Position = projection * worldView * vec4(position, 1.0);",
  106525. "}"
  106526. ].join("\n");
  106527. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  106528. "precision highp float;",
  106529. "",
  106530. "uniform vec4 u_emission;",
  106531. "",
  106532. "void main(void)",
  106533. "{",
  106534. " gl_FragColor = u_emission;",
  106535. "}"
  106536. ].join("\n");
  106537. var shaderPath = {
  106538. vertex: "GLTFDefaultMaterial",
  106539. fragment: "GLTFDefaultMaterial"
  106540. };
  106541. var options = {
  106542. attributes: ["position"],
  106543. uniforms: ["worldView", "projection", "u_emission"],
  106544. samplers: new Array(),
  106545. needAlphaBlending: false
  106546. };
  106547. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  106548. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  106549. }
  106550. return GLTFUtils._DefaultMaterial;
  106551. };
  106552. // The GLTF default material
  106553. GLTFUtils._DefaultMaterial = null;
  106554. return GLTFUtils;
  106555. }());
  106556. GLTF1.GLTFUtils = GLTFUtils;
  106557. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106558. })(BABYLON || (BABYLON = {}));
  106559. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  106560. var BABYLON;
  106561. (function (BABYLON) {
  106562. var GLTF1;
  106563. (function (GLTF1) {
  106564. var GLTFLoaderExtension = /** @class */ (function () {
  106565. function GLTFLoaderExtension(name) {
  106566. this._name = name;
  106567. }
  106568. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  106569. get: function () {
  106570. return this._name;
  106571. },
  106572. enumerable: true,
  106573. configurable: true
  106574. });
  106575. /**
  106576. * Defines an override for loading the runtime
  106577. * Return true to stop further extensions from loading the runtime
  106578. */
  106579. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  106580. return false;
  106581. };
  106582. /**
  106583. * Defines an onverride for creating gltf runtime
  106584. * Return true to stop further extensions from creating the runtime
  106585. */
  106586. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  106587. return false;
  106588. };
  106589. /**
  106590. * Defines an override for loading buffers
  106591. * Return true to stop further extensions from loading this buffer
  106592. */
  106593. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  106594. return false;
  106595. };
  106596. /**
  106597. * Defines an override for loading texture buffers
  106598. * Return true to stop further extensions from loading this texture data
  106599. */
  106600. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  106601. return false;
  106602. };
  106603. /**
  106604. * Defines an override for creating textures
  106605. * Return true to stop further extensions from loading this texture
  106606. */
  106607. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  106608. return false;
  106609. };
  106610. /**
  106611. * Defines an override for loading shader strings
  106612. * Return true to stop further extensions from loading this shader data
  106613. */
  106614. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  106615. return false;
  106616. };
  106617. /**
  106618. * Defines an override for loading materials
  106619. * Return true to stop further extensions from loading this material
  106620. */
  106621. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  106622. return false;
  106623. };
  106624. // ---------
  106625. // Utilities
  106626. // ---------
  106627. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  106628. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106629. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  106630. }, function () {
  106631. setTimeout(function () {
  106632. if (!onSuccess) {
  106633. return;
  106634. }
  106635. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  106636. });
  106637. });
  106638. };
  106639. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  106640. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106641. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  106642. }, function () {
  106643. setTimeout(function () {
  106644. onSuccess();
  106645. });
  106646. });
  106647. };
  106648. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  106649. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106650. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  106651. }, function () {
  106652. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  106653. });
  106654. };
  106655. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  106656. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  106657. if (buffer) {
  106658. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  106659. }
  106660. }, onError);
  106661. };
  106662. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  106663. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106664. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  106665. }, function () {
  106666. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  106667. });
  106668. };
  106669. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  106670. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106671. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  106672. }, function () {
  106673. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  106674. });
  106675. };
  106676. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  106677. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106678. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  106679. }, function () {
  106680. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  106681. });
  106682. };
  106683. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  106684. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106685. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  106686. }, function () {
  106687. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  106688. });
  106689. };
  106690. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  106691. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  106692. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  106693. if (func(loaderExtension)) {
  106694. return;
  106695. }
  106696. }
  106697. defaultFunc();
  106698. };
  106699. return GLTFLoaderExtension;
  106700. }());
  106701. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  106702. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106703. })(BABYLON || (BABYLON = {}));
  106704. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  106705. var BABYLON;
  106706. (function (BABYLON) {
  106707. var GLTF1;
  106708. (function (GLTF1) {
  106709. var BinaryExtensionBufferName = "binary_glTF";
  106710. ;
  106711. ;
  106712. var GLTFBinaryExtension = /** @class */ (function (_super) {
  106713. __extends(GLTFBinaryExtension, _super);
  106714. function GLTFBinaryExtension() {
  106715. return _super.call(this, "KHR_binary_glTF") || this;
  106716. }
  106717. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  106718. var extensionsUsed = data.json.extensionsUsed;
  106719. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  106720. return false;
  106721. }
  106722. this._bin = data.bin;
  106723. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  106724. return true;
  106725. };
  106726. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  106727. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  106728. return false;
  106729. }
  106730. if (id !== BinaryExtensionBufferName) {
  106731. return false;
  106732. }
  106733. onSuccess(this._bin);
  106734. return true;
  106735. };
  106736. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  106737. var texture = gltfRuntime.textures[id];
  106738. var source = gltfRuntime.images[texture.source];
  106739. if (!source.extensions || !(this.name in source.extensions)) {
  106740. return false;
  106741. }
  106742. var sourceExt = source.extensions[this.name];
  106743. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  106744. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  106745. onSuccess(buffer);
  106746. return true;
  106747. };
  106748. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  106749. var shader = gltfRuntime.shaders[id];
  106750. if (!shader.extensions || !(this.name in shader.extensions)) {
  106751. return false;
  106752. }
  106753. var binaryExtensionShader = shader.extensions[this.name];
  106754. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  106755. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  106756. setTimeout(function () {
  106757. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  106758. onSuccess(shaderString);
  106759. });
  106760. return true;
  106761. };
  106762. return GLTFBinaryExtension;
  106763. }(GLTF1.GLTFLoaderExtension));
  106764. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  106765. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  106766. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106767. })(BABYLON || (BABYLON = {}));
  106768. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  106769. var BABYLON;
  106770. (function (BABYLON) {
  106771. var GLTF1;
  106772. (function (GLTF1) {
  106773. ;
  106774. ;
  106775. ;
  106776. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  106777. __extends(GLTFMaterialsCommonExtension, _super);
  106778. function GLTFMaterialsCommonExtension() {
  106779. return _super.call(this, "KHR_materials_common") || this;
  106780. }
  106781. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  106782. if (!gltfRuntime.extensions)
  106783. return false;
  106784. var extension = gltfRuntime.extensions[this.name];
  106785. if (!extension)
  106786. return false;
  106787. // Create lights
  106788. var lights = extension.lights;
  106789. if (lights) {
  106790. for (var thing in lights) {
  106791. var light = lights[thing];
  106792. switch (light.type) {
  106793. case "ambient":
  106794. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  106795. var ambient = light.ambient;
  106796. if (ambient) {
  106797. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  106798. }
  106799. break;
  106800. case "point":
  106801. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  106802. var point = light.point;
  106803. if (point) {
  106804. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  106805. }
  106806. break;
  106807. case "directional":
  106808. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  106809. var directional = light.directional;
  106810. if (directional) {
  106811. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  106812. }
  106813. break;
  106814. case "spot":
  106815. var spot = light.spot;
  106816. if (spot) {
  106817. 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);
  106818. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  106819. }
  106820. break;
  106821. default:
  106822. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  106823. break;
  106824. }
  106825. }
  106826. }
  106827. return false;
  106828. };
  106829. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  106830. var material = gltfRuntime.materials[id];
  106831. if (!material || !material.extensions)
  106832. return false;
  106833. var extension = material.extensions[this.name];
  106834. if (!extension)
  106835. return false;
  106836. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  106837. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  106838. if (extension.technique === "CONSTANT") {
  106839. standardMaterial.disableLighting = true;
  106840. }
  106841. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  106842. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  106843. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  106844. // Ambient
  106845. if (typeof extension.values.ambient === "string") {
  106846. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  106847. }
  106848. else {
  106849. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  106850. }
  106851. // Diffuse
  106852. if (typeof extension.values.diffuse === "string") {
  106853. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  106854. }
  106855. else {
  106856. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  106857. }
  106858. // Emission
  106859. if (typeof extension.values.emission === "string") {
  106860. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  106861. }
  106862. else {
  106863. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  106864. }
  106865. // Specular
  106866. if (typeof extension.values.specular === "string") {
  106867. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  106868. }
  106869. else {
  106870. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  106871. }
  106872. return true;
  106873. };
  106874. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  106875. // Create buffer from texture url
  106876. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  106877. // Create texture from buffer
  106878. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  106879. }, onError);
  106880. };
  106881. return GLTFMaterialsCommonExtension;
  106882. }(GLTF1.GLTFLoaderExtension));
  106883. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  106884. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  106885. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106886. })(BABYLON || (BABYLON = {}));
  106887. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  106888. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  106889. /**
  106890. * Defines the module used to import/export glTF 2.0 assets
  106891. */
  106892. var BABYLON;
  106893. (function (BABYLON) {
  106894. var GLTF2;
  106895. (function (GLTF2) {
  106896. var _ArrayItem = /** @class */ (function () {
  106897. function _ArrayItem() {
  106898. }
  106899. _ArrayItem.Assign = function (values) {
  106900. if (values) {
  106901. for (var index = 0; index < values.length; index++) {
  106902. values[index]._index = index;
  106903. }
  106904. }
  106905. };
  106906. return _ArrayItem;
  106907. }());
  106908. /**
  106909. * Loader for loading a glTF 2.0 asset
  106910. */
  106911. var GLTFLoader = /** @class */ (function () {
  106912. function GLTFLoader() {
  106913. /** @hidden */
  106914. this._completePromises = new Array();
  106915. /** @hidden */
  106916. this._onReadyObservable = new BABYLON.Observable();
  106917. this._disposed = false;
  106918. this._state = null;
  106919. this._extensions = {};
  106920. this._defaultSampler = {};
  106921. this._defaultBabylonMaterials = {};
  106922. this._requests = new Array();
  106923. /**
  106924. * Mode that determines the coordinate system to use.
  106925. */
  106926. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  106927. /**
  106928. * Mode that determines what animations will start.
  106929. */
  106930. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  106931. /**
  106932. * Defines if the loader should compile materials.
  106933. */
  106934. this.compileMaterials = false;
  106935. /**
  106936. * Defines if the loader should also compile materials with clip planes.
  106937. */
  106938. this.useClipPlane = false;
  106939. /**
  106940. * Defines if the loader should compile shadow generators.
  106941. */
  106942. this.compileShadowGenerators = false;
  106943. /**
  106944. * Defines if the Alpha blended materials are only applied as coverage.
  106945. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  106946. * If true, no extra effects are applied to transparent pixels.
  106947. */
  106948. this.transparencyAsCoverage = false;
  106949. /** @hidden */
  106950. this._normalizeAnimationGroupsToBeginAtZero = true;
  106951. /**
  106952. * Function called before loading a url referenced by the asset.
  106953. */
  106954. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  106955. /**
  106956. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  106957. */
  106958. this.onMeshLoadedObservable = new BABYLON.Observable();
  106959. /**
  106960. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  106961. */
  106962. this.onTextureLoadedObservable = new BABYLON.Observable();
  106963. /**
  106964. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  106965. */
  106966. this.onMaterialLoadedObservable = new BABYLON.Observable();
  106967. /**
  106968. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  106969. */
  106970. this.onCameraLoadedObservable = new BABYLON.Observable();
  106971. /**
  106972. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  106973. * For assets with LODs, raised when all of the LODs are complete.
  106974. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  106975. */
  106976. this.onCompleteObservable = new BABYLON.Observable();
  106977. /**
  106978. * Observable raised after the loader is disposed.
  106979. */
  106980. this.onDisposeObservable = new BABYLON.Observable();
  106981. /**
  106982. * Observable raised after a loader extension is created.
  106983. * Set additional options for a loader extension in this event.
  106984. */
  106985. this.onExtensionLoadedObservable = new BABYLON.Observable();
  106986. }
  106987. /** @hidden */
  106988. GLTFLoader._Register = function (name, factory) {
  106989. if (GLTFLoader._ExtensionFactories[name]) {
  106990. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  106991. return;
  106992. }
  106993. GLTFLoader._ExtensionFactories[name] = factory;
  106994. // Keep the order of registration so that extensions registered first are called first.
  106995. GLTFLoader._ExtensionNames.push(name);
  106996. };
  106997. Object.defineProperty(GLTFLoader.prototype, "state", {
  106998. /**
  106999. * Loader state or null if the loader is not active.
  107000. */
  107001. get: function () {
  107002. return this._state;
  107003. },
  107004. enumerable: true,
  107005. configurable: true
  107006. });
  107007. /**
  107008. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  107009. */
  107010. GLTFLoader.prototype.dispose = function () {
  107011. if (this._disposed) {
  107012. return;
  107013. }
  107014. this._disposed = true;
  107015. this.onDisposeObservable.notifyObservers(this);
  107016. this.onDisposeObservable.clear();
  107017. this._clear();
  107018. };
  107019. /**
  107020. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  107021. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  107022. * @param scene the scene the meshes should be added to
  107023. * @param data the glTF data to load
  107024. * @param rootUrl root url to load from
  107025. * @param onProgress event that fires when loading progress has occured
  107026. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  107027. */
  107028. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  107029. var _this = this;
  107030. return Promise.resolve().then(function () {
  107031. _this._babylonScene = scene;
  107032. _this._rootUrl = rootUrl;
  107033. _this._progressCallback = onProgress;
  107034. _this._loadData(data);
  107035. var nodes = null;
  107036. if (meshesNames) {
  107037. var nodeMap_1 = {};
  107038. if (_this._gltf.nodes) {
  107039. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  107040. var node = _a[_i];
  107041. if (node.name) {
  107042. nodeMap_1[node.name] = node;
  107043. }
  107044. }
  107045. }
  107046. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  107047. nodes = names.map(function (name) {
  107048. var node = nodeMap_1[name];
  107049. if (!node) {
  107050. throw new Error("Failed to find node '" + name + "'");
  107051. }
  107052. return node;
  107053. });
  107054. }
  107055. return _this._loadAsync(nodes).then(function () {
  107056. return {
  107057. meshes: _this._getMeshes(),
  107058. particleSystems: [],
  107059. skeletons: _this._getSkeletons(),
  107060. animationGroups: _this._getAnimationGroups()
  107061. };
  107062. });
  107063. });
  107064. };
  107065. /**
  107066. * Imports all objects from the loaded glTF data and adds them to the scene
  107067. * @param scene the scene the objects should be added to
  107068. * @param data the glTF data to load
  107069. * @param rootUrl root url to load from
  107070. * @param onProgress event that fires when loading progress has occured
  107071. * @returns a promise which completes when objects have been loaded to the scene
  107072. */
  107073. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  107074. var _this = this;
  107075. return Promise.resolve().then(function () {
  107076. _this._babylonScene = scene;
  107077. _this._rootUrl = rootUrl;
  107078. _this._progressCallback = onProgress;
  107079. _this._loadData(data);
  107080. return _this._loadAsync(null);
  107081. });
  107082. };
  107083. GLTFLoader.prototype._loadAsync = function (nodes) {
  107084. var _this = this;
  107085. return Promise.resolve().then(function () {
  107086. _this._state = BABYLON.GLTFLoaderState.LOADING;
  107087. _this._loadExtensions();
  107088. _this._checkExtensions();
  107089. var promises = new Array();
  107090. if (nodes) {
  107091. promises.push(_this._loadNodesAsync(nodes));
  107092. }
  107093. else {
  107094. var scene = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  107095. promises.push(_this._loadSceneAsync("#/scenes/" + scene._index, scene));
  107096. }
  107097. if (_this.compileMaterials) {
  107098. promises.push(_this._compileMaterialsAsync());
  107099. }
  107100. if (_this.compileShadowGenerators) {
  107101. promises.push(_this._compileShadowGeneratorsAsync());
  107102. }
  107103. var resultPromise = Promise.all(promises).then(function () {
  107104. _this._state = BABYLON.GLTFLoaderState.READY;
  107105. _this._onReadyObservable.notifyObservers(_this);
  107106. _this._startAnimations();
  107107. });
  107108. resultPromise.then(function () {
  107109. if (_this._rootBabylonMesh) {
  107110. _this._rootBabylonMesh.setEnabled(true);
  107111. }
  107112. BABYLON.Tools.SetImmediate(function () {
  107113. if (!_this._disposed) {
  107114. Promise.all(_this._completePromises).then(function () {
  107115. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  107116. _this.onCompleteObservable.notifyObservers(_this);
  107117. _this.onCompleteObservable.clear();
  107118. _this._clear();
  107119. }).catch(function (error) {
  107120. BABYLON.Tools.Error("glTF Loader: " + error.message);
  107121. _this._clear();
  107122. });
  107123. }
  107124. });
  107125. });
  107126. return resultPromise;
  107127. }).catch(function (error) {
  107128. if (!_this._disposed) {
  107129. BABYLON.Tools.Error("glTF Loader: " + error.message);
  107130. _this._clear();
  107131. throw error;
  107132. }
  107133. });
  107134. };
  107135. GLTFLoader.prototype._loadData = function (data) {
  107136. this._gltf = data.json;
  107137. this._setupData();
  107138. if (data.bin) {
  107139. var buffers = this._gltf.buffers;
  107140. if (buffers && buffers[0] && !buffers[0].uri) {
  107141. var binaryBuffer = buffers[0];
  107142. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  107143. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  107144. }
  107145. binaryBuffer._data = Promise.resolve(data.bin);
  107146. }
  107147. else {
  107148. BABYLON.Tools.Warn("Unexpected BIN chunk");
  107149. }
  107150. }
  107151. };
  107152. GLTFLoader.prototype._setupData = function () {
  107153. _ArrayItem.Assign(this._gltf.accessors);
  107154. _ArrayItem.Assign(this._gltf.animations);
  107155. _ArrayItem.Assign(this._gltf.buffers);
  107156. _ArrayItem.Assign(this._gltf.bufferViews);
  107157. _ArrayItem.Assign(this._gltf.cameras);
  107158. _ArrayItem.Assign(this._gltf.images);
  107159. _ArrayItem.Assign(this._gltf.materials);
  107160. _ArrayItem.Assign(this._gltf.meshes);
  107161. _ArrayItem.Assign(this._gltf.nodes);
  107162. _ArrayItem.Assign(this._gltf.samplers);
  107163. _ArrayItem.Assign(this._gltf.scenes);
  107164. _ArrayItem.Assign(this._gltf.skins);
  107165. _ArrayItem.Assign(this._gltf.textures);
  107166. if (this._gltf.nodes) {
  107167. var nodeParents = {};
  107168. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  107169. var node = _a[_i];
  107170. if (node.children) {
  107171. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  107172. var index = _c[_b];
  107173. nodeParents[index] = node._index;
  107174. }
  107175. }
  107176. }
  107177. var rootNode = this._createRootNode();
  107178. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  107179. var node = _e[_d];
  107180. var parentIndex = nodeParents[node._index];
  107181. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  107182. }
  107183. }
  107184. };
  107185. GLTFLoader.prototype._loadExtensions = function () {
  107186. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  107187. var name_1 = _a[_i];
  107188. var extension = GLTFLoader._ExtensionFactories[name_1](this);
  107189. this._extensions[name_1] = extension;
  107190. this.onExtensionLoadedObservable.notifyObservers(extension);
  107191. }
  107192. this.onExtensionLoadedObservable.clear();
  107193. };
  107194. GLTFLoader.prototype._checkExtensions = function () {
  107195. if (this._gltf.extensionsRequired) {
  107196. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  107197. var name_2 = _a[_i];
  107198. var extension = this._extensions[name_2];
  107199. if (!extension || !extension.enabled) {
  107200. throw new Error("Require extension " + name_2 + " is not available");
  107201. }
  107202. }
  107203. }
  107204. };
  107205. GLTFLoader.prototype._createRootNode = function () {
  107206. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  107207. this._rootBabylonMesh.setEnabled(false);
  107208. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  107209. switch (this.coordinateSystemMode) {
  107210. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  107211. if (!this._babylonScene.useRightHandedSystem) {
  107212. rootNode.rotation = [0, 1, 0, 0];
  107213. rootNode.scale = [1, 1, -1];
  107214. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  107215. }
  107216. break;
  107217. }
  107218. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  107219. this._babylonScene.useRightHandedSystem = true;
  107220. break;
  107221. }
  107222. default: {
  107223. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  107224. }
  107225. }
  107226. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  107227. return rootNode;
  107228. };
  107229. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  107230. var promises = new Array();
  107231. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  107232. var node = nodes_1[_i];
  107233. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  107234. }
  107235. promises.push(this._loadAnimationsAsync());
  107236. return Promise.all(promises).then(function () { });
  107237. };
  107238. /** @hidden */
  107239. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  107240. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  107241. if (promise) {
  107242. return promise;
  107243. }
  107244. var promises = new Array();
  107245. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  107246. var index = _a[_i];
  107247. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  107248. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  107249. }
  107250. promises.push(this._loadAnimationsAsync());
  107251. return Promise.all(promises).then(function () { });
  107252. };
  107253. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  107254. if (node._primitiveBabylonMeshes) {
  107255. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  107256. var babylonMesh = _a[_i];
  107257. callback(babylonMesh);
  107258. }
  107259. }
  107260. else {
  107261. callback(node._babylonMesh);
  107262. }
  107263. };
  107264. GLTFLoader.prototype._getMeshes = function () {
  107265. var meshes = new Array();
  107266. // Root mesh is always first.
  107267. meshes.push(this._rootBabylonMesh);
  107268. var nodes = this._gltf.nodes;
  107269. if (nodes) {
  107270. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  107271. var node = nodes_2[_i];
  107272. if (node._babylonMesh) {
  107273. meshes.push(node._babylonMesh);
  107274. }
  107275. if (node._primitiveBabylonMeshes) {
  107276. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  107277. var babylonMesh = _b[_a];
  107278. meshes.push(babylonMesh);
  107279. }
  107280. }
  107281. }
  107282. }
  107283. return meshes;
  107284. };
  107285. GLTFLoader.prototype._getSkeletons = function () {
  107286. var skeletons = new Array();
  107287. var skins = this._gltf.skins;
  107288. if (skins) {
  107289. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  107290. var skin = skins_1[_i];
  107291. if (skin._babylonSkeleton) {
  107292. skeletons.push(skin._babylonSkeleton);
  107293. }
  107294. }
  107295. }
  107296. return skeletons;
  107297. };
  107298. GLTFLoader.prototype._getAnimationGroups = function () {
  107299. var animationGroups = new Array();
  107300. var animations = this._gltf.animations;
  107301. if (animations) {
  107302. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  107303. var animation = animations_1[_i];
  107304. if (animation._babylonAnimationGroup) {
  107305. animationGroups.push(animation._babylonAnimationGroup);
  107306. }
  107307. }
  107308. }
  107309. return animationGroups;
  107310. };
  107311. GLTFLoader.prototype._startAnimations = function () {
  107312. switch (this.animationStartMode) {
  107313. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  107314. // do nothing
  107315. break;
  107316. }
  107317. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  107318. var babylonAnimationGroups = this._getAnimationGroups();
  107319. if (babylonAnimationGroups.length !== 0) {
  107320. babylonAnimationGroups[0].start(true);
  107321. }
  107322. break;
  107323. }
  107324. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  107325. var babylonAnimationGroups = this._getAnimationGroups();
  107326. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  107327. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  107328. babylonAnimationGroup.start(true);
  107329. }
  107330. break;
  107331. }
  107332. default: {
  107333. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  107334. return;
  107335. }
  107336. }
  107337. };
  107338. /** @hidden */
  107339. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  107340. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  107341. if (promise) {
  107342. return promise;
  107343. }
  107344. if (node._babylonMesh) {
  107345. throw new Error(context + ": Invalid recursive node hierarchy");
  107346. }
  107347. var promises = new Array();
  107348. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent ? node._parent._babylonMesh : null);
  107349. node._babylonMesh = babylonMesh;
  107350. GLTFLoader._LoadTransform(node, babylonMesh);
  107351. if (node.mesh != undefined) {
  107352. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  107353. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  107354. }
  107355. if (node.camera != undefined) {
  107356. var camera = GLTFLoader._GetProperty(context + "/camera", this._gltf.cameras, node.camera);
  107357. this._loadCamera("#/cameras/" + camera._index, camera, babylonMesh);
  107358. }
  107359. if (node.children) {
  107360. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  107361. var index = _a[_i];
  107362. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  107363. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  107364. }
  107365. }
  107366. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  107367. return Promise.all(promises).then(function () { });
  107368. };
  107369. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  107370. var _this = this;
  107371. var promises = new Array();
  107372. var primitives = mesh.primitives;
  107373. if (!primitives || primitives.length === 0) {
  107374. throw new Error(context + ": Primitives are missing");
  107375. }
  107376. _ArrayItem.Assign(primitives);
  107377. if (primitives.length === 1) {
  107378. var primitive = primitives[0];
  107379. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  107380. }
  107381. else {
  107382. node._primitiveBabylonMeshes = [];
  107383. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  107384. var primitive = primitives_1[_i];
  107385. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  107386. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  107387. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  107388. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  107389. }
  107390. }
  107391. if (node.skin != undefined) {
  107392. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  107393. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  107394. }
  107395. return Promise.all(promises).then(function () {
  107396. _this._forEachPrimitive(node, function (babylonMesh) {
  107397. babylonMesh._refreshBoundingInfo(true);
  107398. });
  107399. });
  107400. };
  107401. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  107402. var _this = this;
  107403. var promises = new Array();
  107404. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  107405. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  107406. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  107407. babylonGeometry.applyToMesh(babylonMesh);
  107408. });
  107409. }));
  107410. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  107411. if (primitive.material == undefined) {
  107412. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  107413. }
  107414. else {
  107415. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  107416. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  107417. babylonMesh.material = babylonMaterial;
  107418. }));
  107419. }
  107420. return Promise.all(promises).then(function () { });
  107421. };
  107422. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  107423. var _this = this;
  107424. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  107425. if (promise) {
  107426. return promise;
  107427. }
  107428. var attributes = primitive.attributes;
  107429. if (!attributes) {
  107430. throw new Error(context + ": Attributes are missing");
  107431. }
  107432. var promises = new Array();
  107433. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  107434. if (primitive.indices == undefined) {
  107435. babylonMesh.isUnIndexed = true;
  107436. }
  107437. else {
  107438. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  107439. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  107440. babylonGeometry.setIndices(data);
  107441. }));
  107442. }
  107443. var loadAttribute = function (attribute, kind, callback) {
  107444. if (attributes[attribute] == undefined) {
  107445. return;
  107446. }
  107447. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  107448. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  107449. babylonMesh._delayInfo.push(kind);
  107450. }
  107451. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  107452. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  107453. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  107454. }));
  107455. if (callback) {
  107456. callback(accessor);
  107457. }
  107458. };
  107459. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  107460. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  107461. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  107462. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  107463. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  107464. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  107465. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  107466. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  107467. if (accessor.type === "VEC4" /* VEC4 */) {
  107468. babylonMesh.hasVertexAlpha = true;
  107469. }
  107470. });
  107471. return Promise.all(promises).then(function () {
  107472. return babylonGeometry;
  107473. });
  107474. };
  107475. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  107476. if (!primitive.targets) {
  107477. return;
  107478. }
  107479. if (node._numMorphTargets == undefined) {
  107480. node._numMorphTargets = primitive.targets.length;
  107481. }
  107482. else if (primitive.targets.length !== node._numMorphTargets) {
  107483. throw new Error(context + ": Primitives do not have the same number of targets");
  107484. }
  107485. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  107486. for (var index = 0; index < primitive.targets.length; index++) {
  107487. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  107488. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  107489. // TODO: tell the target whether it has positions, normals, tangents
  107490. }
  107491. };
  107492. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  107493. if (!primitive.targets) {
  107494. return Promise.resolve();
  107495. }
  107496. var promises = new Array();
  107497. var morphTargetManager = babylonMesh.morphTargetManager;
  107498. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  107499. var babylonMorphTarget = morphTargetManager.getTarget(index);
  107500. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  107501. }
  107502. return Promise.all(promises).then(function () { });
  107503. };
  107504. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  107505. var _this = this;
  107506. var promises = new Array();
  107507. var loadAttribute = function (attribute, kind, setData) {
  107508. if (attributes[attribute] == undefined) {
  107509. return;
  107510. }
  107511. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  107512. if (!babylonVertexBuffer) {
  107513. return;
  107514. }
  107515. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  107516. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  107517. setData(babylonVertexBuffer, data);
  107518. }));
  107519. };
  107520. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  107521. babylonVertexBuffer.forEach(data.length, function (value, index) {
  107522. data[index] += value;
  107523. });
  107524. babylonMorphTarget.setPositions(data);
  107525. });
  107526. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  107527. babylonVertexBuffer.forEach(data.length, function (value, index) {
  107528. data[index] += value;
  107529. });
  107530. babylonMorphTarget.setNormals(data);
  107531. });
  107532. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  107533. var dataIndex = 0;
  107534. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  107535. // Tangent data for morph targets is stored as xyz delta.
  107536. // The vertexData.tangent is stored as xyzw.
  107537. // So we need to skip every fourth vertexData.tangent.
  107538. if (((index + 1) % 4) !== 0) {
  107539. data[dataIndex++] += value;
  107540. }
  107541. });
  107542. babylonMorphTarget.setTangents(data);
  107543. });
  107544. return Promise.all(promises).then(function () { });
  107545. };
  107546. GLTFLoader._LoadTransform = function (node, babylonNode) {
  107547. var position = BABYLON.Vector3.Zero();
  107548. var rotation = BABYLON.Quaternion.Identity();
  107549. var scaling = BABYLON.Vector3.One();
  107550. if (node.matrix) {
  107551. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  107552. matrix.decompose(scaling, rotation, position);
  107553. }
  107554. else {
  107555. if (node.translation)
  107556. position = BABYLON.Vector3.FromArray(node.translation);
  107557. if (node.rotation)
  107558. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  107559. if (node.scale)
  107560. scaling = BABYLON.Vector3.FromArray(node.scale);
  107561. }
  107562. babylonNode.position = position;
  107563. babylonNode.rotationQuaternion = rotation;
  107564. babylonNode.scaling = scaling;
  107565. };
  107566. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  107567. var _this = this;
  107568. var assignSkeleton = function (skeleton) {
  107569. _this._forEachPrimitive(node, function (babylonMesh) {
  107570. babylonMesh.skeleton = skeleton;
  107571. });
  107572. // Ignore the TRS of skinned nodes.
  107573. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  107574. node._babylonMesh.parent = _this._rootBabylonMesh;
  107575. node._babylonMesh.position = BABYLON.Vector3.Zero();
  107576. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  107577. node._babylonMesh.scaling = BABYLON.Vector3.One();
  107578. };
  107579. if (skin._loaded) {
  107580. return skin._loaded.then(function () {
  107581. assignSkeleton(skin._babylonSkeleton);
  107582. });
  107583. }
  107584. var skeletonId = "skeleton" + skin._index;
  107585. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  107586. skin._babylonSkeleton = babylonSkeleton;
  107587. this._loadBones(context, skin);
  107588. assignSkeleton(babylonSkeleton);
  107589. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  107590. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  107591. }));
  107592. };
  107593. GLTFLoader.prototype._loadBones = function (context, skin) {
  107594. var babylonBones = {};
  107595. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  107596. var index = _a[_i];
  107597. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  107598. this._loadBone(node, skin, babylonBones);
  107599. }
  107600. };
  107601. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  107602. var babylonBone = babylonBones[node._index];
  107603. if (babylonBone) {
  107604. return babylonBone;
  107605. }
  107606. var babylonParentBone = null;
  107607. if (node._parent && node._parent._babylonMesh !== this._rootBabylonMesh) {
  107608. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  107609. }
  107610. var boneIndex = skin.joints.indexOf(node._index);
  107611. babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  107612. babylonBones[node._index] = babylonBone;
  107613. node._babylonBones = node._babylonBones || [];
  107614. node._babylonBones.push(babylonBone);
  107615. return babylonBone;
  107616. };
  107617. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  107618. if (skin.inverseBindMatrices == undefined) {
  107619. return Promise.resolve(null);
  107620. }
  107621. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  107622. return this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor);
  107623. };
  107624. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  107625. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  107626. var babylonBone = _a[_i];
  107627. var baseMatrix = BABYLON.Matrix.Identity();
  107628. var boneIndex = babylonBone._index;
  107629. if (inverseBindMatricesData && boneIndex !== -1) {
  107630. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  107631. baseMatrix.invertToRef(baseMatrix);
  107632. }
  107633. var babylonParentBone = babylonBone.getParent();
  107634. if (babylonParentBone) {
  107635. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  107636. }
  107637. babylonBone.updateMatrix(baseMatrix, false, false);
  107638. babylonBone._updateDifferenceMatrix(undefined, false);
  107639. }
  107640. };
  107641. GLTFLoader.prototype._getNodeMatrix = function (node) {
  107642. return node.matrix ?
  107643. BABYLON.Matrix.FromArray(node.matrix) :
  107644. 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());
  107645. };
  107646. GLTFLoader.prototype._loadCamera = function (context, camera, babylonMesh) {
  107647. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera._index, BABYLON.Vector3.Zero(), this._babylonScene, false);
  107648. babylonCamera.parent = babylonMesh;
  107649. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  107650. switch (camera.type) {
  107651. case "perspective" /* PERSPECTIVE */: {
  107652. var perspective = camera.perspective;
  107653. if (!perspective) {
  107654. throw new Error(context + ": Camera perspective properties are missing");
  107655. }
  107656. babylonCamera.fov = perspective.yfov;
  107657. babylonCamera.minZ = perspective.znear;
  107658. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  107659. break;
  107660. }
  107661. case "orthographic" /* ORTHOGRAPHIC */: {
  107662. if (!camera.orthographic) {
  107663. throw new Error(context + ": Camera orthographic properties are missing");
  107664. }
  107665. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  107666. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  107667. babylonCamera.orthoRight = camera.orthographic.xmag;
  107668. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  107669. babylonCamera.orthoTop = camera.orthographic.ymag;
  107670. babylonCamera.minZ = camera.orthographic.znear;
  107671. babylonCamera.maxZ = camera.orthographic.zfar;
  107672. break;
  107673. }
  107674. default: {
  107675. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  107676. }
  107677. }
  107678. this.onCameraLoadedObservable.notifyObservers(babylonCamera);
  107679. };
  107680. GLTFLoader.prototype._loadAnimationsAsync = function () {
  107681. var animations = this._gltf.animations;
  107682. if (!animations) {
  107683. return Promise.resolve();
  107684. }
  107685. var promises = new Array();
  107686. for (var index = 0; index < animations.length; index++) {
  107687. var animation = animations[index];
  107688. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  107689. }
  107690. return Promise.all(promises).then(function () { });
  107691. };
  107692. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  107693. var _this = this;
  107694. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  107695. animation._babylonAnimationGroup = babylonAnimationGroup;
  107696. var promises = new Array();
  107697. _ArrayItem.Assign(animation.channels);
  107698. _ArrayItem.Assign(animation.samplers);
  107699. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  107700. var channel = _a[_i];
  107701. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  107702. }
  107703. return Promise.all(promises).then(function () {
  107704. babylonAnimationGroup.normalize(_this._normalizeAnimationGroupsToBeginAtZero ? 0 : null);
  107705. });
  107706. };
  107707. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  107708. var _this = this;
  107709. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  107710. // Ignore animations that have no animation targets.
  107711. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  107712. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  107713. return Promise.resolve();
  107714. }
  107715. // Ignore animations targeting TRS of skinned nodes.
  107716. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  107717. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  107718. return Promise.resolve();
  107719. }
  107720. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  107721. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  107722. var targetPath;
  107723. var animationType;
  107724. switch (channel.target.path) {
  107725. case "translation" /* TRANSLATION */: {
  107726. targetPath = "position";
  107727. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  107728. break;
  107729. }
  107730. case "rotation" /* ROTATION */: {
  107731. targetPath = "rotationQuaternion";
  107732. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  107733. break;
  107734. }
  107735. case "scale" /* SCALE */: {
  107736. targetPath = "scaling";
  107737. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  107738. break;
  107739. }
  107740. case "weights" /* WEIGHTS */: {
  107741. targetPath = "influence";
  107742. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  107743. break;
  107744. }
  107745. default: {
  107746. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  107747. }
  107748. }
  107749. var outputBufferOffset = 0;
  107750. var getNextOutputValue;
  107751. switch (targetPath) {
  107752. case "position": {
  107753. getNextOutputValue = function () {
  107754. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  107755. outputBufferOffset += 3;
  107756. return value;
  107757. };
  107758. break;
  107759. }
  107760. case "rotationQuaternion": {
  107761. getNextOutputValue = function () {
  107762. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  107763. outputBufferOffset += 4;
  107764. return value;
  107765. };
  107766. break;
  107767. }
  107768. case "scaling": {
  107769. getNextOutputValue = function () {
  107770. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  107771. outputBufferOffset += 3;
  107772. return value;
  107773. };
  107774. break;
  107775. }
  107776. case "influence": {
  107777. getNextOutputValue = function () {
  107778. var value = new Array(targetNode._numMorphTargets);
  107779. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  107780. value[i] = data.output[outputBufferOffset++];
  107781. }
  107782. return value;
  107783. };
  107784. break;
  107785. }
  107786. }
  107787. var getNextKey;
  107788. switch (data.interpolation) {
  107789. case "STEP" /* STEP */: {
  107790. getNextKey = function (frameIndex) { return ({
  107791. frame: data.input[frameIndex],
  107792. value: getNextOutputValue(),
  107793. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  107794. }); };
  107795. break;
  107796. }
  107797. case "LINEAR" /* LINEAR */: {
  107798. getNextKey = function (frameIndex) { return ({
  107799. frame: data.input[frameIndex],
  107800. value: getNextOutputValue()
  107801. }); };
  107802. break;
  107803. }
  107804. case "CUBICSPLINE" /* CUBICSPLINE */: {
  107805. getNextKey = function (frameIndex) { return ({
  107806. frame: data.input[frameIndex],
  107807. inTangent: getNextOutputValue(),
  107808. value: getNextOutputValue(),
  107809. outTangent: getNextOutputValue()
  107810. }); };
  107811. break;
  107812. }
  107813. }
  107814. var keys = new Array(data.input.length);
  107815. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  107816. keys[frameIndex] = getNextKey(frameIndex);
  107817. }
  107818. if (targetPath === "influence") {
  107819. var _loop_1 = function (targetIndex) {
  107820. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  107821. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  107822. babylonAnimation.setKeys(keys.map(function (key) { return ({
  107823. frame: key.frame,
  107824. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  107825. value: key.value[targetIndex],
  107826. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  107827. }); }));
  107828. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  107829. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  107830. var babylonAnimationClone = babylonAnimation.clone();
  107831. morphTarget.animations.push(babylonAnimationClone);
  107832. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  107833. });
  107834. };
  107835. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  107836. _loop_1(targetIndex);
  107837. }
  107838. }
  107839. else {
  107840. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  107841. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  107842. babylonAnimation.setKeys(keys);
  107843. if (targetNode._babylonBones) {
  107844. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  107845. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  107846. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  107847. babylonAnimationTarget.animations.push(babylonAnimation);
  107848. }
  107849. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  107850. }
  107851. else {
  107852. targetNode._babylonMesh.animations.push(babylonAnimation);
  107853. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  107854. }
  107855. }
  107856. });
  107857. };
  107858. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  107859. if (sampler._data) {
  107860. return sampler._data;
  107861. }
  107862. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  107863. switch (interpolation) {
  107864. case "STEP" /* STEP */:
  107865. case "LINEAR" /* LINEAR */:
  107866. case "CUBICSPLINE" /* CUBICSPLINE */: {
  107867. break;
  107868. }
  107869. default: {
  107870. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  107871. }
  107872. }
  107873. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  107874. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  107875. sampler._data = Promise.all([
  107876. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor),
  107877. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor)
  107878. ]).then(function (_a) {
  107879. var inputData = _a[0], outputData = _a[1];
  107880. return {
  107881. input: inputData,
  107882. interpolation: interpolation,
  107883. output: outputData,
  107884. };
  107885. });
  107886. return sampler._data;
  107887. };
  107888. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  107889. if (buffer._data) {
  107890. return buffer._data;
  107891. }
  107892. if (!buffer.uri) {
  107893. throw new Error(context + ": Uri is missing");
  107894. }
  107895. buffer._data = this._loadUriAsync(context, buffer.uri);
  107896. return buffer._data;
  107897. };
  107898. /** @hidden */
  107899. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  107900. if (bufferView._data) {
  107901. return bufferView._data;
  107902. }
  107903. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  107904. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  107905. try {
  107906. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  107907. }
  107908. catch (e) {
  107909. throw new Error(context + ": " + e.message);
  107910. }
  107911. });
  107912. return bufferView._data;
  107913. };
  107914. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  107915. if (accessor.type !== "SCALAR" /* SCALAR */) {
  107916. throw new Error(context + ": Invalid type " + accessor.type);
  107917. }
  107918. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  107919. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  107920. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  107921. throw new Error(context + ": Invalid component type " + accessor.componentType);
  107922. }
  107923. if (accessor._data) {
  107924. return accessor._data;
  107925. }
  107926. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  107927. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  107928. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  107929. });
  107930. return accessor._data;
  107931. };
  107932. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  107933. // TODO: support normalized and stride
  107934. var _this = this;
  107935. if (accessor.componentType !== 5126 /* FLOAT */) {
  107936. throw new Error("Invalid component type " + accessor.componentType);
  107937. }
  107938. if (accessor._data) {
  107939. return accessor._data;
  107940. }
  107941. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  107942. var length = numComponents * accessor.count;
  107943. if (accessor.bufferView == undefined) {
  107944. accessor._data = Promise.resolve(new Float32Array(length));
  107945. }
  107946. else {
  107947. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  107948. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  107949. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  107950. });
  107951. }
  107952. if (accessor.sparse) {
  107953. var sparse_1 = accessor.sparse;
  107954. accessor._data = accessor._data.then(function (data) {
  107955. var indicesBufferView = GLTFLoader._GetProperty(context + "/sparse/indices/bufferView", _this._gltf.bufferViews, sparse_1.indices.bufferView);
  107956. var valuesBufferView = GLTFLoader._GetProperty(context + "/sparse/values/bufferView", _this._gltf.bufferViews, sparse_1.values.bufferView);
  107957. return Promise.all([
  107958. _this._loadBufferViewAsync("#/bufferViews/" + indicesBufferView._index, indicesBufferView),
  107959. _this._loadBufferViewAsync("#/bufferViews/" + valuesBufferView._index, valuesBufferView)
  107960. ]).then(function (_a) {
  107961. var indicesData = _a[0], valuesData = _a[1];
  107962. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  107963. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  107964. var valuesIndex = 0;
  107965. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  107966. var dataIndex = indices[indicesIndex] * numComponents;
  107967. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  107968. data[dataIndex++] = values[valuesIndex++];
  107969. }
  107970. }
  107971. return data;
  107972. });
  107973. });
  107974. }
  107975. return accessor._data;
  107976. };
  107977. /** @hidden */
  107978. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  107979. var _this = this;
  107980. if (bufferView._babylonBuffer) {
  107981. return bufferView._babylonBuffer;
  107982. }
  107983. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  107984. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  107985. });
  107986. return bufferView._babylonBuffer;
  107987. };
  107988. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  107989. var _this = this;
  107990. if (accessor._babylonVertexBuffer) {
  107991. return accessor._babylonVertexBuffer;
  107992. }
  107993. if (accessor.sparse) {
  107994. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(function (data) {
  107995. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), data, kind, false);
  107996. });
  107997. }
  107998. else {
  107999. var bufferView_1 = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  108000. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView_1._index, bufferView_1, kind).then(function (buffer) {
  108001. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  108002. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  108003. });
  108004. }
  108005. return accessor._babylonVertexBuffer;
  108006. };
  108007. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  108008. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  108009. if (!babylonMaterial) {
  108010. babylonMaterial = this._createMaterial("__gltf_default", drawMode);
  108011. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  108012. babylonMaterial.metallic = 1;
  108013. babylonMaterial.roughness = 1;
  108014. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  108015. }
  108016. return babylonMaterial;
  108017. };
  108018. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  108019. var promises = new Array();
  108020. // Ensure metallic workflow
  108021. babylonMaterial.metallic = 1;
  108022. babylonMaterial.roughness = 1;
  108023. var properties = material.pbrMetallicRoughness;
  108024. if (properties) {
  108025. if (properties.baseColorFactor) {
  108026. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  108027. babylonMaterial.alpha = properties.baseColorFactor[3];
  108028. }
  108029. else {
  108030. babylonMaterial.albedoColor = BABYLON.Color3.White();
  108031. }
  108032. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  108033. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  108034. if (properties.baseColorTexture) {
  108035. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  108036. babylonMaterial.albedoTexture = texture;
  108037. }));
  108038. }
  108039. if (properties.metallicRoughnessTexture) {
  108040. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  108041. babylonMaterial.metallicTexture = texture;
  108042. }));
  108043. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  108044. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  108045. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  108046. }
  108047. }
  108048. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  108049. return Promise.all(promises).then(function () { });
  108050. };
  108051. /** @hidden */
  108052. GLTFLoader.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  108053. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, mesh, babylonMesh, babylonDrawMode, assign);
  108054. if (promise) {
  108055. return promise;
  108056. }
  108057. material._babylonData = material._babylonData || {};
  108058. var babylonData = material._babylonData[babylonDrawMode];
  108059. if (!babylonData) {
  108060. var promises = new Array();
  108061. var name_3 = material.name || "material_" + material._index;
  108062. var babylonMaterial = this._createMaterial(name_3, babylonDrawMode);
  108063. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  108064. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  108065. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  108066. babylonData = {
  108067. material: babylonMaterial,
  108068. meshes: [],
  108069. loaded: Promise.all(promises).then(function () { })
  108070. };
  108071. material._babylonData[babylonDrawMode] = babylonData;
  108072. }
  108073. babylonData.meshes.push(babylonMesh);
  108074. assign(babylonData.material);
  108075. return babylonData.loaded;
  108076. };
  108077. /** @hidden */
  108078. GLTFLoader.prototype._createMaterial = function (name, drawMode) {
  108079. var babylonMaterial = new BABYLON.PBRMaterial(name, this._babylonScene);
  108080. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  108081. babylonMaterial.fillMode = drawMode;
  108082. babylonMaterial.enableSpecularAntiAliasing = true;
  108083. babylonMaterial.useRadianceOverAlpha = !this.transparencyAsCoverage;
  108084. babylonMaterial.useSpecularOverAlpha = !this.transparencyAsCoverage;
  108085. return babylonMaterial;
  108086. };
  108087. /** @hidden */
  108088. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  108089. var promises = new Array();
  108090. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  108091. if (material.doubleSided) {
  108092. babylonMaterial.backFaceCulling = false;
  108093. babylonMaterial.twoSidedLighting = true;
  108094. }
  108095. if (material.normalTexture) {
  108096. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  108097. babylonMaterial.bumpTexture = texture;
  108098. }));
  108099. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  108100. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  108101. if (material.normalTexture.scale != undefined) {
  108102. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  108103. }
  108104. }
  108105. if (material.occlusionTexture) {
  108106. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  108107. babylonMaterial.ambientTexture = texture;
  108108. }));
  108109. babylonMaterial.useAmbientInGrayScale = true;
  108110. if (material.occlusionTexture.strength != undefined) {
  108111. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  108112. }
  108113. }
  108114. if (material.emissiveTexture) {
  108115. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  108116. babylonMaterial.emissiveTexture = texture;
  108117. }));
  108118. }
  108119. return Promise.all(promises).then(function () { });
  108120. };
  108121. /** @hidden */
  108122. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  108123. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  108124. switch (alphaMode) {
  108125. case "OPAQUE" /* OPAQUE */: {
  108126. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  108127. break;
  108128. }
  108129. case "MASK" /* MASK */: {
  108130. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  108131. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  108132. if (babylonMaterial.albedoTexture) {
  108133. babylonMaterial.albedoTexture.hasAlpha = true;
  108134. }
  108135. break;
  108136. }
  108137. case "BLEND" /* BLEND */: {
  108138. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  108139. if (babylonMaterial.albedoTexture) {
  108140. babylonMaterial.albedoTexture.hasAlpha = true;
  108141. babylonMaterial.useAlphaFromAlbedoTexture = true;
  108142. }
  108143. break;
  108144. }
  108145. default: {
  108146. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  108147. }
  108148. }
  108149. };
  108150. /** @hidden */
  108151. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  108152. var _this = this;
  108153. var promise = GLTF2.GLTFLoaderExtension._LoadTextureAsync(this, context, textureInfo, assign);
  108154. if (promise) {
  108155. return promise;
  108156. }
  108157. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  108158. context = "#/textures/" + textureInfo.index;
  108159. var promises = new Array();
  108160. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  108161. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  108162. var deferred = new BABYLON.Deferred();
  108163. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  108164. if (!_this._disposed) {
  108165. deferred.resolve();
  108166. }
  108167. }, function (message, exception) {
  108168. if (!_this._disposed) {
  108169. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  108170. }
  108171. });
  108172. promises.push(deferred.promise);
  108173. babylonTexture.name = texture.name || "texture" + texture._index;
  108174. babylonTexture.wrapU = samplerData.wrapU;
  108175. babylonTexture.wrapV = samplerData.wrapV;
  108176. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  108177. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  108178. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (blob) {
  108179. var dataUrl = "data:" + _this._rootUrl + (image.uri || "image" + image._index);
  108180. babylonTexture.updateURL(dataUrl, blob);
  108181. }));
  108182. assign(babylonTexture);
  108183. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  108184. return Promise.all(promises).then(function () { });
  108185. };
  108186. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  108187. if (!sampler._data) {
  108188. sampler._data = {
  108189. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  108190. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  108191. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  108192. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  108193. };
  108194. }
  108195. ;
  108196. return sampler._data;
  108197. };
  108198. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  108199. if (image._blob) {
  108200. return image._blob;
  108201. }
  108202. var promise;
  108203. if (image.uri) {
  108204. promise = this._loadUriAsync(context, image.uri);
  108205. }
  108206. else {
  108207. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  108208. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  108209. }
  108210. image._blob = promise.then(function (data) {
  108211. return new Blob([data], { type: image.mimeType });
  108212. });
  108213. return image._blob;
  108214. };
  108215. /** @hidden */
  108216. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  108217. var _this = this;
  108218. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  108219. if (promise) {
  108220. return promise;
  108221. }
  108222. if (!GLTFLoader._ValidateUri(uri)) {
  108223. throw new Error(context + ": Uri '" + uri + "' is invalid");
  108224. }
  108225. if (BABYLON.Tools.IsBase64(uri)) {
  108226. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  108227. }
  108228. return this.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  108229. return new Promise(function (resolve, reject) {
  108230. if (!_this._disposed) {
  108231. var request_1 = BABYLON.Tools.LoadFile(url, function (data) {
  108232. if (!_this._disposed) {
  108233. resolve(new Uint8Array(data));
  108234. }
  108235. }, function (event) {
  108236. if (!_this._disposed) {
  108237. try {
  108238. if (request_1 && _this._state === BABYLON.GLTFLoaderState.LOADING) {
  108239. request_1._lengthComputable = event.lengthComputable;
  108240. request_1._loaded = event.loaded;
  108241. request_1._total = event.total;
  108242. _this._onProgress();
  108243. }
  108244. }
  108245. catch (e) {
  108246. reject(e);
  108247. }
  108248. }
  108249. }, _this._babylonScene.database, true, function (request, exception) {
  108250. if (!_this._disposed) {
  108251. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  108252. }
  108253. });
  108254. _this._requests.push(request_1);
  108255. }
  108256. });
  108257. });
  108258. };
  108259. GLTFLoader.prototype._onProgress = function () {
  108260. if (!this._progressCallback) {
  108261. return;
  108262. }
  108263. var lengthComputable = true;
  108264. var loaded = 0;
  108265. var total = 0;
  108266. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  108267. var request = _a[_i];
  108268. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  108269. return;
  108270. }
  108271. lengthComputable = lengthComputable && request._lengthComputable;
  108272. loaded += request._loaded;
  108273. total += request._total;
  108274. }
  108275. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  108276. };
  108277. /** @hidden */
  108278. GLTFLoader._GetProperty = function (context, array, index) {
  108279. if (!array || index == undefined || !array[index]) {
  108280. throw new Error(context + ": Failed to find index (" + index + ")");
  108281. }
  108282. return array[index];
  108283. };
  108284. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  108285. // Set defaults if undefined
  108286. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  108287. switch (mode) {
  108288. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  108289. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  108290. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  108291. default:
  108292. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  108293. return BABYLON.Texture.WRAP_ADDRESSMODE;
  108294. }
  108295. };
  108296. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  108297. // Set defaults if undefined
  108298. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  108299. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  108300. if (magFilter === 9729 /* LINEAR */) {
  108301. switch (minFilter) {
  108302. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  108303. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  108304. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  108305. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  108306. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  108307. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  108308. default:
  108309. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  108310. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  108311. }
  108312. }
  108313. else {
  108314. if (magFilter !== 9728 /* NEAREST */) {
  108315. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  108316. }
  108317. switch (minFilter) {
  108318. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  108319. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  108320. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  108321. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  108322. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  108323. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  108324. default:
  108325. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  108326. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  108327. }
  108328. }
  108329. };
  108330. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  108331. var buffer = bufferView.buffer;
  108332. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  108333. try {
  108334. switch (componentType) {
  108335. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  108336. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  108337. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  108338. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  108339. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  108340. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  108341. default: throw new Error("Invalid component type " + componentType);
  108342. }
  108343. }
  108344. catch (e) {
  108345. throw new Error(context + ": " + e);
  108346. }
  108347. };
  108348. GLTFLoader._GetNumComponents = function (context, type) {
  108349. switch (type) {
  108350. case "SCALAR": return 1;
  108351. case "VEC2": return 2;
  108352. case "VEC3": return 3;
  108353. case "VEC4": return 4;
  108354. case "MAT2": return 4;
  108355. case "MAT3": return 9;
  108356. case "MAT4": return 16;
  108357. }
  108358. throw new Error(context + ": Invalid type (" + type + ")");
  108359. };
  108360. GLTFLoader._ValidateUri = function (uri) {
  108361. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  108362. };
  108363. GLTFLoader._GetDrawMode = function (context, mode) {
  108364. if (mode == undefined) {
  108365. mode = 4 /* TRIANGLES */;
  108366. }
  108367. switch (mode) {
  108368. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  108369. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  108370. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  108371. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  108372. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  108373. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  108374. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  108375. }
  108376. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  108377. };
  108378. GLTFLoader.prototype._compileMaterialsAsync = function () {
  108379. var promises = new Array();
  108380. if (this._gltf.materials) {
  108381. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  108382. var material = _a[_i];
  108383. if (material._babylonData) {
  108384. for (var babylonDrawMode in material._babylonData) {
  108385. var babylonData = material._babylonData[babylonDrawMode];
  108386. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  108387. var babylonMesh = _c[_b];
  108388. // Ensure nonUniformScaling is set if necessary.
  108389. babylonMesh.computeWorldMatrix(true);
  108390. var babylonMaterial = babylonData.material;
  108391. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  108392. if (this.useClipPlane) {
  108393. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  108394. }
  108395. }
  108396. }
  108397. }
  108398. }
  108399. }
  108400. return Promise.all(promises).then(function () { });
  108401. };
  108402. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  108403. var promises = new Array();
  108404. var lights = this._babylonScene.lights;
  108405. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  108406. var light = lights_1[_i];
  108407. var generator = light.getShadowGenerator();
  108408. if (generator) {
  108409. promises.push(generator.forceCompilationAsync());
  108410. }
  108411. }
  108412. return Promise.all(promises).then(function () { });
  108413. };
  108414. GLTFLoader.prototype._clear = function () {
  108415. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  108416. var request = _a[_i];
  108417. request.abort();
  108418. }
  108419. this._requests.length = 0;
  108420. delete this._gltf;
  108421. delete this._babylonScene;
  108422. this._completePromises.length = 0;
  108423. this._onReadyObservable.clear();
  108424. for (var name_4 in this._extensions) {
  108425. this._extensions[name_4].dispose();
  108426. }
  108427. this._extensions = {};
  108428. delete this._rootBabylonMesh;
  108429. delete this._progressCallback;
  108430. this.onMeshLoadedObservable.clear();
  108431. this.onTextureLoadedObservable.clear();
  108432. this.onMaterialLoadedObservable.clear();
  108433. this.onCameraLoadedObservable.clear();
  108434. };
  108435. /** @hidden */
  108436. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  108437. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  108438. var name_5 = _a[_i];
  108439. var extension = this._extensions[name_5];
  108440. if (extension.enabled) {
  108441. var promise = actionAsync(extension);
  108442. if (promise) {
  108443. return promise;
  108444. }
  108445. }
  108446. }
  108447. return null;
  108448. };
  108449. GLTFLoader._ExtensionNames = new Array();
  108450. GLTFLoader._ExtensionFactories = {};
  108451. return GLTFLoader;
  108452. }());
  108453. GLTF2.GLTFLoader = GLTFLoader;
  108454. BABYLON.GLTFFileLoader._CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  108455. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108456. })(BABYLON || (BABYLON = {}));
  108457. //# sourceMappingURL=babylon.glTFLoader.js.map
  108458. var BABYLON;
  108459. (function (BABYLON) {
  108460. var GLTF2;
  108461. (function (GLTF2) {
  108462. /**
  108463. * Abstract class that can be implemented to extend existing glTF loader behavior.
  108464. */
  108465. var GLTFLoaderExtension = /** @class */ (function () {
  108466. /**
  108467. * Creates new GLTFLoaderExtension
  108468. * @param loader defines the GLTFLoader to use
  108469. */
  108470. function GLTFLoaderExtension(loader) {
  108471. /**
  108472. * Gets or sets a boolean indicating if the extension is enabled
  108473. */
  108474. this.enabled = true;
  108475. this._loader = loader;
  108476. }
  108477. /**
  108478. * Release all resources
  108479. */
  108480. GLTFLoaderExtension.prototype.dispose = function () {
  108481. delete this._loader;
  108482. };
  108483. // #region Overridable Methods
  108484. /**
  108485. * Override this method to modify the default behavior for loading scenes.
  108486. * @hidden
  108487. */
  108488. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  108489. /**
  108490. * Override this method to modify the default behavior for loading nodes.
  108491. * @hidden
  108492. */
  108493. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  108494. /**
  108495. * Override this method to modify the default behavior for loading mesh primitive vertex data.
  108496. * @hidden
  108497. */
  108498. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  108499. /**
  108500. * Override this method to modify the default behavior for loading materials.
  108501. * @hidden
  108502. */
  108503. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) { return null; };
  108504. /**
  108505. * Override this method to modify the default behavior for loading textures.
  108506. * @hidden
  108507. */
  108508. GLTFLoaderExtension.prototype._loadTextureAsync = function (context, textureInfo, assign) { return null; };
  108509. /**
  108510. * Override this method to modify the default behavior for loading uris.
  108511. * @hidden
  108512. */
  108513. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  108514. // #endregion
  108515. /**
  108516. * Helper method called by a loader extension to load an glTF extension.
  108517. * @hidden
  108518. */
  108519. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  108520. if (!property.extensions) {
  108521. return null;
  108522. }
  108523. var extensions = property.extensions;
  108524. var extension = extensions[this.name];
  108525. if (!extension) {
  108526. return null;
  108527. }
  108528. // Clear out the extension before executing the action to avoid infinite recursion.
  108529. delete extensions[this.name];
  108530. try {
  108531. return actionAsync(context + "/extensions/" + this.name, extension);
  108532. }
  108533. finally {
  108534. // Restore the extension after executing the action.
  108535. extensions[this.name] = extension;
  108536. }
  108537. };
  108538. /**
  108539. * Helper method called by the loader to allow extensions to override loading scenes.
  108540. * @hidden
  108541. */
  108542. GLTFLoaderExtension.prototype._loadExtrasValueAsync = function (context, property, actionAsync) {
  108543. if (!property.extras) {
  108544. return null;
  108545. }
  108546. var extras = property.extras;
  108547. var value = extras[this.name];
  108548. if (value === undefined) {
  108549. return null;
  108550. }
  108551. // Clear out the extras value before executing the action to avoid infinite recursion.
  108552. delete extras[this.name];
  108553. try {
  108554. return actionAsync(context + "/extras/" + this.name, value);
  108555. }
  108556. finally {
  108557. // Restore the extras value after executing the action.
  108558. extras[this.name] = value;
  108559. }
  108560. };
  108561. /**
  108562. * Helper method called by the loader to allow extensions to override loading scenes.
  108563. * @hidden
  108564. */
  108565. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  108566. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  108567. };
  108568. /**
  108569. * Helper method called by the loader to allow extensions to override loading nodes.
  108570. * @hidden
  108571. */
  108572. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  108573. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  108574. };
  108575. /**
  108576. * Helper method called by the loader to allow extensions to override loading mesh primitive vertex data.
  108577. * @hidden
  108578. */
  108579. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  108580. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  108581. };
  108582. /**
  108583. * Helper method called by the loader to allow extensions to override loading materials.
  108584. * @hidden
  108585. */
  108586. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  108587. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, assign); });
  108588. };
  108589. /**
  108590. * Helper method called by the loader to allow extensions to override loading textures.
  108591. * @hidden
  108592. */
  108593. GLTFLoaderExtension._LoadTextureAsync = function (loader, context, textureInfo, assign) {
  108594. return loader._applyExtensions(function (extension) { return extension._loadTextureAsync(context, textureInfo, assign); });
  108595. };
  108596. /**
  108597. * Helper method called by the loader to allow extensions to override loading uris.
  108598. * @hidden
  108599. */
  108600. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  108601. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  108602. };
  108603. return GLTFLoaderExtension;
  108604. }());
  108605. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  108606. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108607. })(BABYLON || (BABYLON = {}));
  108608. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  108609. var BABYLON;
  108610. (function (BABYLON) {
  108611. var GLTF2;
  108612. (function (GLTF2) {
  108613. var Extensions;
  108614. (function (Extensions) {
  108615. var NAME = "MSFT_lod";
  108616. /**
  108617. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  108618. */
  108619. var MSFT_lod = /** @class */ (function (_super) {
  108620. __extends(MSFT_lod, _super);
  108621. function MSFT_lod(loader) {
  108622. var _this = _super.call(this, loader) || this;
  108623. _this.name = NAME;
  108624. /**
  108625. * Maximum number of LODs to load, starting from the lowest LOD.
  108626. */
  108627. _this.maxLODsToLoad = Number.MAX_VALUE;
  108628. /**
  108629. * Observable raised when all node LODs of one level are loaded.
  108630. * The event data is the index of the loaded LOD starting from zero.
  108631. * Dispose the loader to cancel the loading of the next level of LODs.
  108632. */
  108633. _this.onNodeLODsLoadedObservable = new BABYLON.Observable();
  108634. /**
  108635. * Observable raised when all material LODs of one level are loaded.
  108636. * The event data is the index of the loaded LOD starting from zero.
  108637. * Dispose the loader to cancel the loading of the next level of LODs.
  108638. */
  108639. _this.onMaterialLODsLoadedObservable = new BABYLON.Observable();
  108640. _this._loadingNodeLOD = null;
  108641. _this._loadNodeSignals = {};
  108642. _this._loadNodePromises = new Array();
  108643. _this._loadingMaterialLOD = null;
  108644. _this._loadMaterialSignals = {};
  108645. _this._loadMaterialPromises = new Array();
  108646. _this._loader._onReadyObservable.addOnce(function () {
  108647. var _loop_1 = function (indexLOD) {
  108648. Promise.all(_this._loadNodePromises[indexLOD]).then(function () {
  108649. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  108650. });
  108651. };
  108652. for (var indexLOD = 0; indexLOD < _this._loadNodePromises.length; indexLOD++) {
  108653. _loop_1(indexLOD);
  108654. }
  108655. var _loop_2 = function (indexLOD) {
  108656. Promise.all(_this._loadMaterialPromises[indexLOD]).then(function () {
  108657. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  108658. });
  108659. };
  108660. for (var indexLOD = 0; indexLOD < _this._loadMaterialPromises.length; indexLOD++) {
  108661. _loop_2(indexLOD);
  108662. }
  108663. });
  108664. return _this;
  108665. }
  108666. MSFT_lod.prototype.dispose = function () {
  108667. _super.prototype.dispose.call(this);
  108668. this._loadingNodeLOD = null;
  108669. this._loadNodeSignals = {};
  108670. this._loadingMaterialLOD = null;
  108671. this._loadMaterialSignals = {};
  108672. this.onMaterialLODsLoadedObservable.clear();
  108673. this.onNodeLODsLoadedObservable.clear();
  108674. };
  108675. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  108676. var _this = this;
  108677. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  108678. var firstPromise;
  108679. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  108680. var _loop_3 = function (indexLOD) {
  108681. var nodeLOD = nodeLODs[indexLOD];
  108682. if (indexLOD !== 0) {
  108683. _this._loadingNodeLOD = nodeLOD;
  108684. if (!_this._loadNodeSignals[nodeLOD._index]) {
  108685. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  108686. }
  108687. }
  108688. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  108689. if (indexLOD !== 0) {
  108690. var previousNodeLOD = nodeLODs[indexLOD - 1];
  108691. if (previousNodeLOD._babylonMesh) {
  108692. previousNodeLOD._babylonMesh.dispose(false, true);
  108693. delete previousNodeLOD._babylonMesh;
  108694. }
  108695. }
  108696. if (indexLOD !== nodeLODs.length - 1) {
  108697. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  108698. if (_this._loadNodeSignals[nodeIndex]) {
  108699. _this._loadNodeSignals[nodeIndex].resolve();
  108700. delete _this._loadNodeSignals[nodeIndex];
  108701. }
  108702. }
  108703. });
  108704. if (indexLOD === 0) {
  108705. firstPromise = promise;
  108706. }
  108707. else {
  108708. _this._loader._completePromises.push(promise);
  108709. _this._loadingNodeLOD = null;
  108710. }
  108711. _this._loadNodePromises[indexLOD] = _this._loadNodePromises[indexLOD] || [];
  108712. _this._loadNodePromises[indexLOD].push(promise);
  108713. };
  108714. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  108715. _loop_3(indexLOD);
  108716. }
  108717. return firstPromise;
  108718. });
  108719. };
  108720. MSFT_lod.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  108721. var _this = this;
  108722. // Don't load material LODs if already loading a node LOD.
  108723. if (this._loadingNodeLOD) {
  108724. return null;
  108725. }
  108726. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  108727. var firstPromise;
  108728. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  108729. var _loop_4 = function (indexLOD) {
  108730. var materialLOD = materialLODs[indexLOD];
  108731. if (indexLOD !== 0) {
  108732. _this._loadingMaterialLOD = materialLOD;
  108733. if (!_this._loadMaterialSignals[materialLOD._index]) {
  108734. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  108735. }
  108736. }
  108737. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, mesh, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  108738. if (indexLOD !== 0) {
  108739. var babylonDataLOD = materialLOD._babylonData;
  108740. assign(babylonDataLOD[babylonDrawMode].material);
  108741. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  108742. if (previousBabylonDataLOD[babylonDrawMode]) {
  108743. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  108744. delete previousBabylonDataLOD[babylonDrawMode];
  108745. }
  108746. }
  108747. if (indexLOD !== materialLODs.length - 1) {
  108748. var materialIndex = materialLODs[indexLOD + 1]._index;
  108749. if (_this._loadMaterialSignals[materialIndex]) {
  108750. _this._loadMaterialSignals[materialIndex].resolve();
  108751. delete _this._loadMaterialSignals[materialIndex];
  108752. }
  108753. }
  108754. });
  108755. if (indexLOD === 0) {
  108756. firstPromise = promise;
  108757. }
  108758. else {
  108759. _this._loader._completePromises.push(promise);
  108760. _this._loadingMaterialLOD = null;
  108761. }
  108762. _this._loadMaterialPromises[indexLOD] = _this._loadMaterialPromises[indexLOD] || [];
  108763. _this._loadMaterialPromises[indexLOD].push(promise);
  108764. };
  108765. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  108766. _loop_4(indexLOD);
  108767. }
  108768. return firstPromise;
  108769. });
  108770. };
  108771. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  108772. var _this = this;
  108773. // Defer the loading of uris if loading a material or node LOD.
  108774. if (this._loadingMaterialLOD) {
  108775. var index = this._loadingMaterialLOD._index;
  108776. return this._loadMaterialSignals[index].promise.then(function () {
  108777. return _this._loader._loadUriAsync(context, uri);
  108778. });
  108779. }
  108780. else if (this._loadingNodeLOD) {
  108781. var index = this._loadingNodeLOD._index;
  108782. return this._loadNodeSignals[index].promise.then(function () {
  108783. return _this._loader._loadUriAsync(context, uri);
  108784. });
  108785. }
  108786. return null;
  108787. };
  108788. /**
  108789. * Gets an array of LOD properties from lowest to highest.
  108790. */
  108791. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  108792. if (this.maxLODsToLoad <= 0) {
  108793. throw new Error("maxLODsToLoad must be greater than zero");
  108794. }
  108795. var properties = new Array();
  108796. for (var i = ids.length - 1; i >= 0; i--) {
  108797. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  108798. if (properties.length === this.maxLODsToLoad) {
  108799. return properties;
  108800. }
  108801. }
  108802. properties.push(property);
  108803. return properties;
  108804. };
  108805. return MSFT_lod;
  108806. }(GLTF2.GLTFLoaderExtension));
  108807. Extensions.MSFT_lod = MSFT_lod;
  108808. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  108809. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  108810. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108811. })(BABYLON || (BABYLON = {}));
  108812. //# sourceMappingURL=MSFT_lod.js.map
  108813. var BABYLON;
  108814. (function (BABYLON) {
  108815. var GLTF2;
  108816. (function (GLTF2) {
  108817. var Extensions;
  108818. (function (Extensions) {
  108819. var NAME = "MSFT_minecraftMesh";
  108820. /** @hidden */
  108821. var MSFT_minecraftMesh = /** @class */ (function (_super) {
  108822. __extends(MSFT_minecraftMesh, _super);
  108823. function MSFT_minecraftMesh() {
  108824. var _this = _super !== null && _super.apply(this, arguments) || this;
  108825. _this.name = NAME;
  108826. return _this;
  108827. }
  108828. MSFT_minecraftMesh.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  108829. var _this = this;
  108830. return this._loadExtrasValueAsync(context, mesh, function (extensionContext, value) {
  108831. if (value) {
  108832. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  108833. if (babylonMaterial.needAlphaBlending()) {
  108834. babylonMaterial.forceDepthWrite = true;
  108835. babylonMaterial.separateCullingPass = true;
  108836. }
  108837. babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;
  108838. babylonMaterial.twoSidedLighting = true;
  108839. assign(babylonMaterial);
  108840. });
  108841. }
  108842. return null;
  108843. });
  108844. };
  108845. return MSFT_minecraftMesh;
  108846. }(GLTF2.GLTFLoaderExtension));
  108847. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  108848. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  108849. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  108850. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108851. })(BABYLON || (BABYLON = {}));
  108852. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  108853. var BABYLON;
  108854. (function (BABYLON) {
  108855. var GLTF2;
  108856. (function (GLTF2) {
  108857. var Extensions;
  108858. (function (Extensions) {
  108859. var NAME = "MSFT_sRGBFactors";
  108860. /** @hidden */
  108861. var MSFT_sRGBFactors = /** @class */ (function (_super) {
  108862. __extends(MSFT_sRGBFactors, _super);
  108863. function MSFT_sRGBFactors() {
  108864. var _this = _super !== null && _super.apply(this, arguments) || this;
  108865. _this.name = NAME;
  108866. return _this;
  108867. }
  108868. MSFT_sRGBFactors.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  108869. var _this = this;
  108870. return this._loadExtrasValueAsync(context, material, function (extensionContext, value) {
  108871. if (value) {
  108872. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  108873. if (!babylonMaterial.albedoTexture) {
  108874. babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);
  108875. }
  108876. if (!babylonMaterial.reflectivityTexture) {
  108877. babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);
  108878. }
  108879. assign(babylonMaterial);
  108880. });
  108881. }
  108882. return null;
  108883. });
  108884. };
  108885. return MSFT_sRGBFactors;
  108886. }(GLTF2.GLTFLoaderExtension));
  108887. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  108888. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  108889. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  108890. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108891. })(BABYLON || (BABYLON = {}));
  108892. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  108893. var BABYLON;
  108894. (function (BABYLON) {
  108895. var GLTF2;
  108896. (function (GLTF2) {
  108897. var Extensions;
  108898. (function (Extensions) {
  108899. var NAME = "KHR_draco_mesh_compression";
  108900. /**
  108901. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  108902. */
  108903. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  108904. __extends(KHR_draco_mesh_compression, _super);
  108905. function KHR_draco_mesh_compression(loader) {
  108906. var _this = _super.call(this, loader) || this;
  108907. _this.name = NAME;
  108908. _this._dracoCompression = null;
  108909. // Disable extension if decoder is not available.
  108910. if (!BABYLON.DracoCompression.DecoderAvailable) {
  108911. _this.enabled = false;
  108912. }
  108913. return _this;
  108914. }
  108915. KHR_draco_mesh_compression.prototype.dispose = function () {
  108916. if (this._dracoCompression) {
  108917. this._dracoCompression.dispose();
  108918. }
  108919. _super.prototype.dispose.call(this);
  108920. };
  108921. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  108922. var _this = this;
  108923. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  108924. if (primitive.mode != undefined) {
  108925. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  108926. primitive.mode !== 4 /* TRIANGLES */) {
  108927. throw new Error(context + ": Unsupported mode " + primitive.mode);
  108928. }
  108929. // TODO: handle triangle strips
  108930. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  108931. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  108932. }
  108933. }
  108934. var attributes = {};
  108935. var loadAttribute = function (name, kind) {
  108936. var uniqueId = extension.attributes[name];
  108937. if (uniqueId == undefined) {
  108938. return;
  108939. }
  108940. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  108941. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  108942. babylonMesh._delayInfo.push(kind);
  108943. }
  108944. attributes[kind] = uniqueId;
  108945. };
  108946. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  108947. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  108948. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  108949. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  108950. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  108951. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  108952. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  108953. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  108954. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  108955. if (!bufferView._dracoBabylonGeometry) {
  108956. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  108957. if (!_this._dracoCompression) {
  108958. _this._dracoCompression = new BABYLON.DracoCompression();
  108959. }
  108960. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  108961. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  108962. babylonVertexData.applyToGeometry(babylonGeometry);
  108963. return babylonGeometry;
  108964. }).catch(function (error) {
  108965. throw new Error(context + ": " + error.message);
  108966. });
  108967. });
  108968. }
  108969. return bufferView._dracoBabylonGeometry;
  108970. });
  108971. };
  108972. return KHR_draco_mesh_compression;
  108973. }(GLTF2.GLTFLoaderExtension));
  108974. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  108975. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  108976. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  108977. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108978. })(BABYLON || (BABYLON = {}));
  108979. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  108980. var BABYLON;
  108981. (function (BABYLON) {
  108982. var GLTF2;
  108983. (function (GLTF2) {
  108984. var Extensions;
  108985. (function (Extensions) {
  108986. var NAME = "KHR_materials_pbrSpecularGlossiness";
  108987. /**
  108988. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  108989. */
  108990. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  108991. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  108992. function KHR_materials_pbrSpecularGlossiness() {
  108993. var _this = _super !== null && _super.apply(this, arguments) || this;
  108994. _this.name = NAME;
  108995. return _this;
  108996. }
  108997. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  108998. var _this = this;
  108999. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  109000. material._babylonData = material._babylonData || {};
  109001. var babylonData = material._babylonData[babylonDrawMode];
  109002. if (!babylonData) {
  109003. var promises = new Array();
  109004. var name_1 = material.name || "materialSG_" + material._index;
  109005. var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode);
  109006. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  109007. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  109008. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109009. babylonData = {
  109010. material: babylonMaterial,
  109011. meshes: [],
  109012. loaded: Promise.all(promises).then(function () { })
  109013. };
  109014. material._babylonData[babylonDrawMode] = babylonData;
  109015. }
  109016. babylonData.meshes.push(babylonMesh);
  109017. assign(babylonData.material);
  109018. return babylonData.loaded;
  109019. });
  109020. };
  109021. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  109022. var promises = new Array();
  109023. if (properties.diffuseFactor) {
  109024. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  109025. babylonMaterial.alpha = properties.diffuseFactor[3];
  109026. }
  109027. else {
  109028. babylonMaterial.albedoColor = BABYLON.Color3.White();
  109029. }
  109030. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  109031. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  109032. if (properties.diffuseTexture) {
  109033. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  109034. babylonMaterial.albedoTexture = texture;
  109035. }));
  109036. }
  109037. if (properties.specularGlossinessTexture) {
  109038. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  109039. babylonMaterial.reflectivityTexture = texture;
  109040. }));
  109041. babylonMaterial.reflectivityTexture.hasAlpha = true;
  109042. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  109043. }
  109044. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  109045. return Promise.all(promises).then(function () { });
  109046. };
  109047. return KHR_materials_pbrSpecularGlossiness;
  109048. }(GLTF2.GLTFLoaderExtension));
  109049. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  109050. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  109051. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109052. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109053. })(BABYLON || (BABYLON = {}));
  109054. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  109055. var BABYLON;
  109056. (function (BABYLON) {
  109057. var GLTF2;
  109058. (function (GLTF2) {
  109059. var Extensions;
  109060. (function (Extensions) {
  109061. var NAME = "KHR_materials_unlit";
  109062. /**
  109063. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  109064. */
  109065. var KHR_materials_unlit = /** @class */ (function (_super) {
  109066. __extends(KHR_materials_unlit, _super);
  109067. function KHR_materials_unlit() {
  109068. var _this = _super !== null && _super.apply(this, arguments) || this;
  109069. _this.name = NAME;
  109070. return _this;
  109071. }
  109072. KHR_materials_unlit.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  109073. var _this = this;
  109074. return this._loadExtensionAsync(context, material, function () {
  109075. material._babylonData = material._babylonData || {};
  109076. var babylonData = material._babylonData[babylonDrawMode];
  109077. if (!babylonData) {
  109078. var name_1 = material.name || "materialUnlit_" + material._index;
  109079. var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode);
  109080. babylonMaterial.unlit = true;
  109081. var promise = _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  109082. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109083. babylonData = {
  109084. material: babylonMaterial,
  109085. meshes: [],
  109086. loaded: promise
  109087. };
  109088. material._babylonData[babylonDrawMode] = babylonData;
  109089. }
  109090. babylonData.meshes.push(babylonMesh);
  109091. assign(babylonData.material);
  109092. return babylonData.loaded;
  109093. });
  109094. };
  109095. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  109096. var promises = new Array();
  109097. // Ensure metallic workflow
  109098. babylonMaterial.metallic = 1;
  109099. babylonMaterial.roughness = 1;
  109100. var properties = material.pbrMetallicRoughness;
  109101. if (properties) {
  109102. if (properties.baseColorFactor) {
  109103. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  109104. babylonMaterial.alpha = properties.baseColorFactor[3];
  109105. }
  109106. else {
  109107. babylonMaterial.albedoColor = BABYLON.Color3.White();
  109108. }
  109109. if (properties.baseColorTexture) {
  109110. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  109111. babylonMaterial.albedoTexture = texture;
  109112. }));
  109113. }
  109114. }
  109115. if (material.doubleSided) {
  109116. babylonMaterial.backFaceCulling = false;
  109117. babylonMaterial.twoSidedLighting = true;
  109118. }
  109119. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  109120. return Promise.all(promises).then(function () { });
  109121. };
  109122. return KHR_materials_unlit;
  109123. }(GLTF2.GLTFLoaderExtension));
  109124. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  109125. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  109126. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109127. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109128. })(BABYLON || (BABYLON = {}));
  109129. //# sourceMappingURL=KHR_materials_unlit.js.map
  109130. var BABYLON;
  109131. (function (BABYLON) {
  109132. var GLTF2;
  109133. (function (GLTF2) {
  109134. var Extensions;
  109135. (function (Extensions) {
  109136. var NAME = "KHR_lights";
  109137. var LightType;
  109138. (function (LightType) {
  109139. LightType["AMBIENT"] = "ambient";
  109140. LightType["DIRECTIONAL"] = "directional";
  109141. LightType["POINT"] = "point";
  109142. LightType["SPOT"] = "spot";
  109143. })(LightType || (LightType = {}));
  109144. /**
  109145. * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental)
  109146. */
  109147. var KHR_lights = /** @class */ (function (_super) {
  109148. __extends(KHR_lights, _super);
  109149. function KHR_lights() {
  109150. var _this = _super !== null && _super.apply(this, arguments) || this;
  109151. _this.name = NAME;
  109152. return _this;
  109153. }
  109154. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  109155. var _this = this;
  109156. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  109157. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  109158. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  109159. if (light.type !== LightType.AMBIENT) {
  109160. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  109161. }
  109162. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  109163. return promise;
  109164. });
  109165. };
  109166. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  109167. var _this = this;
  109168. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  109169. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  109170. var babylonLight;
  109171. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  109172. var name = node._babylonMesh.name;
  109173. switch (light.type) {
  109174. case LightType.AMBIENT: {
  109175. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  109176. }
  109177. case LightType.DIRECTIONAL: {
  109178. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  109179. break;
  109180. }
  109181. case LightType.POINT: {
  109182. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  109183. break;
  109184. }
  109185. case LightType.SPOT: {
  109186. var spotLight = light;
  109187. // TODO: support inner and outer cone angles
  109188. //const innerConeAngle = spotLight.innerConeAngle || 0;
  109189. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  109190. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  109191. break;
  109192. }
  109193. default: {
  109194. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  109195. }
  109196. }
  109197. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  109198. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  109199. babylonLight.parent = node._babylonMesh;
  109200. return promise;
  109201. });
  109202. };
  109203. Object.defineProperty(KHR_lights.prototype, "_lights", {
  109204. get: function () {
  109205. var extensions = this._loader._gltf.extensions;
  109206. if (!extensions || !extensions[this.name]) {
  109207. throw new Error("#/extensions: '" + this.name + "' not found");
  109208. }
  109209. var extension = extensions[this.name];
  109210. return extension.lights;
  109211. },
  109212. enumerable: true,
  109213. configurable: true
  109214. });
  109215. return KHR_lights;
  109216. }(GLTF2.GLTFLoaderExtension));
  109217. Extensions.KHR_lights = KHR_lights;
  109218. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  109219. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109220. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109221. })(BABYLON || (BABYLON = {}));
  109222. var BABYLON;
  109223. (function (BABYLON) {
  109224. var GLTF2;
  109225. (function (GLTF2) {
  109226. var Extensions;
  109227. (function (Extensions) {
  109228. var NAME = "KHR_texture_transform";
  109229. /**
  109230. * [Specification](https://github.com/AltspaceVR/glTF/blob/avr-sampler-offset-tile/extensions/2.0/Khronos/KHR_texture_transform/README.md) (Experimental)
  109231. */
  109232. var KHR_texture_transform = /** @class */ (function (_super) {
  109233. __extends(KHR_texture_transform, _super);
  109234. function KHR_texture_transform() {
  109235. var _this = _super !== null && _super.apply(this, arguments) || this;
  109236. _this.name = NAME;
  109237. return _this;
  109238. }
  109239. KHR_texture_transform.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  109240. var _this = this;
  109241. return this._loadExtensionAsync(context, textureInfo, function (extensionContext, extension) {
  109242. return _this._loader._loadTextureAsync(context, textureInfo, function (babylonTexture) {
  109243. if (extension.offset) {
  109244. babylonTexture.uOffset = extension.offset[0];
  109245. babylonTexture.vOffset = extension.offset[1];
  109246. }
  109247. // Always rotate around the origin.
  109248. babylonTexture.uRotationCenter = 0;
  109249. babylonTexture.vRotationCenter = 0;
  109250. if (extension.rotation) {
  109251. babylonTexture.wAng = -extension.rotation;
  109252. }
  109253. if (extension.scale) {
  109254. babylonTexture.uScale = extension.scale[0];
  109255. babylonTexture.vScale = extension.scale[1];
  109256. }
  109257. if (extension.texCoord != undefined) {
  109258. babylonTexture.coordinatesIndex = extension.texCoord;
  109259. }
  109260. assign(babylonTexture);
  109261. });
  109262. });
  109263. };
  109264. return KHR_texture_transform;
  109265. }(GLTF2.GLTFLoaderExtension));
  109266. Extensions.KHR_texture_transform = KHR_texture_transform;
  109267. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_texture_transform(loader); });
  109268. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109269. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109270. })(BABYLON || (BABYLON = {}));
  109271. return BABYLON;
  109272. });
  109273. /***/ }),
  109274. /* 15 */
  109275. /***/ (function(module, exports, __webpack_require__) {
  109276. module.exports = __webpack_require__(16);
  109277. /***/ }),
  109278. /* 16 */
  109279. /***/ (function(module, exports, __webpack_require__) {
  109280. "use strict";
  109281. function __export(m) {
  109282. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  109283. }
  109284. Object.defineProperty(exports, "__esModule", { value: true });
  109285. var mappers_1 = __webpack_require__(3);
  109286. exports.mapperManager = mappers_1.mapperManager;
  109287. var globals_1 = __webpack_require__(4);
  109288. exports.viewerGlobals = globals_1.viewerGlobals;
  109289. var viewerManager_1 = __webpack_require__(7);
  109290. exports.viewerManager = viewerManager_1.viewerManager;
  109291. var defaultViewer_1 = __webpack_require__(8);
  109292. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  109293. var viewer_1 = __webpack_require__(9);
  109294. exports.AbstractViewer = viewer_1.AbstractViewer;
  109295. var telemetryManager_1 = __webpack_require__(6);
  109296. exports.telemetryManager = telemetryManager_1.telemetryManager;
  109297. var modelLoader_1 = __webpack_require__(13);
  109298. exports.ModelLoader = modelLoader_1.ModelLoader;
  109299. var viewerModel_1 = __webpack_require__(5);
  109300. exports.ViewerModel = viewerModel_1.ViewerModel;
  109301. exports.ModelState = viewerModel_1.ModelState;
  109302. /**
  109303. * BabylonJS Viewer
  109304. *
  109305. * An HTML-Based viewer for 3D models, based on BabylonJS and its extensions.
  109306. */
  109307. var BABYLON = __webpack_require__(0);
  109308. exports.BABYLON = BABYLON;
  109309. // load needed modules.
  109310. __webpack_require__(14);
  109311. __webpack_require__(64);
  109312. var initializer_1 = __webpack_require__(65);
  109313. exports.InitTags = initializer_1.InitTags;
  109314. // promise polyfill, if needed!
  109315. BABYLON.PromisePolyfill.Apply();
  109316. initializer_1.initListeners();
  109317. //deprectaed, here for backwards compatibility
  109318. var disableInit = globals_1.viewerGlobals.disableInit;
  109319. exports.disableInit = disableInit;
  109320. /**
  109321. * Dispose all viewers currently registered
  109322. */
  109323. function disposeAll() {
  109324. viewerManager_1.viewerManager.dispose();
  109325. mappers_1.mapperManager.dispose();
  109326. telemetryManager_1.telemetryManager.dispose();
  109327. }
  109328. exports.disposeAll = disposeAll;
  109329. var Version = globals_1.viewerGlobals.version;
  109330. exports.Version = Version;
  109331. console.log("Babylon.js viewer (v" + Version + ")");
  109332. // export publicliy all configuration interfaces
  109333. __export(__webpack_require__(10));
  109334. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7QUFBQSxtREFBd0Q7QUE4Q3lFLHdCQTlDeEgsdUJBQWEsQ0E4Q3dIO0FBN0M5SSxtREFBd0Q7QUE2Q1ksd0JBN0MzRCx1QkFBYSxDQTZDMkQ7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yxHQUFHLENBQUMsQ0FBQztBQUlwRCxnREFBZ0Q7QUFDaEQscUNBQWdDIn0=
  109335. /***/ }),
  109336. /* 17 */
  109337. /***/ (function(module, exports) {
  109338. var g;
  109339. // This works in non-strict mode
  109340. g = (function() {
  109341. return this;
  109342. })();
  109343. try {
  109344. // This works if eval is allowed (see CSP)
  109345. g = g || Function("return this")() || (1,eval)("this");
  109346. } catch(e) {
  109347. // This works if the window reference is available
  109348. if(typeof window === "object")
  109349. g = window;
  109350. }
  109351. // g can still be undefined, but nothing to do about it...
  109352. // We return undefined, instead of nothing here, so it's
  109353. // easier to handle this case. if(!global) { ...}
  109354. module.exports = g;
  109355. /***/ }),
  109356. /* 18 */
  109357. /***/ (function(module, exports) {
  109358. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  109359. module.exports = CANNON;
  109360. /***/ }),
  109361. /* 19 */
  109362. /***/ (function(module, exports) {
  109363. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  109364. module.exports = OIMO;
  109365. /***/ }),
  109366. /* 20 */
  109367. /***/ (function(module, exports) {
  109368. if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  109369. module.exports = earcut;
  109370. /***/ }),
  109371. /* 21 */
  109372. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  109373. "use strict";
  109374. Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
  109375. var isMergeableObject = function isMergeableObject(value) {
  109376. return isNonNullObject(value)
  109377. && !isSpecial(value)
  109378. };
  109379. function isNonNullObject(value) {
  109380. return !!value && typeof value === 'object'
  109381. }
  109382. function isSpecial(value) {
  109383. var stringValue = Object.prototype.toString.call(value);
  109384. return stringValue === '[object RegExp]'
  109385. || stringValue === '[object Date]'
  109386. || isReactElement(value)
  109387. }
  109388. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  109389. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  109390. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  109391. function isReactElement(value) {
  109392. return value.$$typeof === REACT_ELEMENT_TYPE
  109393. }
  109394. function emptyTarget(val) {
  109395. return Array.isArray(val) ? [] : {}
  109396. }
  109397. function cloneUnlessOtherwiseSpecified(value, options) {
  109398. return (options.clone !== false && options.isMergeableObject(value))
  109399. ? deepmerge(emptyTarget(value), value, options)
  109400. : value
  109401. }
  109402. function defaultArrayMerge(target, source, options) {
  109403. return target.concat(source).map(function(element) {
  109404. return cloneUnlessOtherwiseSpecified(element, options)
  109405. })
  109406. }
  109407. function mergeObject(target, source, options) {
  109408. var destination = {};
  109409. if (options.isMergeableObject(target)) {
  109410. Object.keys(target).forEach(function(key) {
  109411. destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
  109412. });
  109413. }
  109414. Object.keys(source).forEach(function(key) {
  109415. if (!options.isMergeableObject(source[key]) || !target[key]) {
  109416. destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
  109417. } else {
  109418. destination[key] = deepmerge(target[key], source[key], options);
  109419. }
  109420. });
  109421. return destination
  109422. }
  109423. function deepmerge(target, source, options) {
  109424. options = options || {};
  109425. options.arrayMerge = options.arrayMerge || defaultArrayMerge;
  109426. options.isMergeableObject = options.isMergeableObject || isMergeableObject;
  109427. var sourceIsArray = Array.isArray(source);
  109428. var targetIsArray = Array.isArray(target);
  109429. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  109430. if (!sourceAndTargetTypesMatch) {
  109431. return cloneUnlessOtherwiseSpecified(source, options)
  109432. } else if (sourceIsArray) {
  109433. return options.arrayMerge(target, source, options)
  109434. } else {
  109435. return mergeObject(target, source, options)
  109436. }
  109437. }
  109438. deepmerge.all = function deepmergeAll(array, options) {
  109439. if (!Array.isArray(array)) {
  109440. throw new Error('first argument should be an array')
  109441. }
  109442. return array.reduce(function(prev, next) {
  109443. return deepmerge(prev, next, options)
  109444. }, {})
  109445. };
  109446. var deepmerge_1 = deepmerge;
  109447. /* harmony default export */ __webpack_exports__["default"] = (deepmerge_1);
  109448. /***/ }),
  109449. /* 22 */
  109450. /***/ (function(module, exports, __webpack_require__) {
  109451. "use strict";
  109452. Object.defineProperty(exports, "__esModule", { value: true });
  109453. var babylonjs_1 = __webpack_require__(0);
  109454. var configuration_1 = __webpack_require__(10);
  109455. var viewerModel_1 = __webpack_require__(5);
  109456. var helper_1 = __webpack_require__(1);
  109457. var viewerLabs_1 = __webpack_require__(24);
  109458. var _1 = __webpack_require__(26);
  109459. var SceneManager = /** @class */ (function () {
  109460. function SceneManager(_engine, _configurationContainer, _observablesManager) {
  109461. var _this = this;
  109462. this._engine = _engine;
  109463. this._configurationContainer = _configurationContainer;
  109464. this._observablesManager = _observablesManager;
  109465. this._animationBlendingEnabled = true;
  109466. this._white = babylonjs_1.Color3.White();
  109467. this._forceShadowUpdate = false;
  109468. this._processShadows = true;
  109469. this._groundEnabled = true;
  109470. this._groundMirrorEnabled = true;
  109471. this._defaultRenderingPipelineEnabled = false;
  109472. this._globalConfiguration = {};
  109473. this._defaultRenderingPipelineShouldBuild = true;
  109474. // default from rendering pipeline
  109475. this._bloomEnabled = false;
  109476. // default from rendering pipeline
  109477. this._fxaaEnabled = false;
  109478. this._focusOnModel = function (model) {
  109479. var boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  109480. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  109481. var halfSizeVec = sizeVec.scale(0.5);
  109482. var center = boundingInfo.min.add(halfSizeVec);
  109483. _this.camera.setTarget(center);
  109484. _this.camera.alpha = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.alpha) || _this.camera.alpha;
  109485. _this.camera.beta = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.beta) || _this.camera.beta;
  109486. _this.camera.radius = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.radius) || _this.camera.radius;
  109487. /*this.scene.lights.filter(light => light instanceof ShadowLight).forEach(light => {
  109488. // casting ais safe, due to the constraints tested before
  109489. (<ShadowLight>light).setDirectionToTarget(center);
  109490. });*/
  109491. };
  109492. this._cameraBehaviorMapping = {};
  109493. this.models = [];
  109494. this.onCameraConfiguredObservable = new babylonjs_1.Observable();
  109495. this.onLightsConfiguredObservable = new babylonjs_1.Observable();
  109496. this.onModelsConfiguredObservable = new babylonjs_1.Observable();
  109497. this.onSceneConfiguredObservable = new babylonjs_1.Observable();
  109498. this.onSceneInitObservable = new babylonjs_1.Observable();
  109499. this.onSceneOptimizerConfiguredObservable = new babylonjs_1.Observable();
  109500. this.onEnvironmentConfiguredObservable = new babylonjs_1.Observable();
  109501. //this._viewer.onEngineInitObservable.add(() => {
  109502. this._handleHardwareLimitations();
  109503. //});
  109504. this.onSceneInitObservable.add(function (scene) {
  109505. _this.scene.animationPropertiesOverride = _this.scene.animationPropertiesOverride || new babylonjs_1.AnimationPropertiesOverride();
  109506. _this.labs = new viewerLabs_1.ViewerLabs(scene);
  109507. var updateShadows = function () {
  109508. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  109509. var light = _a[_i];
  109510. var generator = light.getShadowGenerator();
  109511. if (generator) {
  109512. // Processing shadows if animates
  109513. var shadowMap = generator.getShadowMap();
  109514. if (shadowMap) {
  109515. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  109516. }
  109517. }
  109518. }
  109519. };
  109520. scene.registerBeforeRender(function () {
  109521. if (_this._forceShadowUpdate || (scene.animatables && scene.animatables.length > 0)) {
  109522. // make sure all models are loaded
  109523. updateShadows();
  109524. _this._forceShadowUpdate = false;
  109525. }
  109526. else if (!(_this.models.every(function (model) {
  109527. if (!model.shadowsRenderedAfterLoad) {
  109528. model.shadowsRenderedAfterLoad = true;
  109529. return false;
  109530. }
  109531. return model.state === viewerModel_1.ModelState.COMPLETE && !model.currentAnimation;
  109532. }))) {
  109533. updateShadows();
  109534. }
  109535. });
  109536. return _this._observablesManager && _this._observablesManager.onSceneInitObservable.notifyObserversWithPromise(_this.scene);
  109537. });
  109538. if (this._observablesManager) {
  109539. this._observablesManager.onModelLoadedObservable.add(function (model) {
  109540. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  109541. var light = _a[_i];
  109542. var generator = light.getShadowGenerator();
  109543. if (generator) {
  109544. // Processing shadows if animates
  109545. var shadowMap = generator.getShadowMap();
  109546. if (shadowMap) {
  109547. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  109548. }
  109549. }
  109550. }
  109551. _this._focusOnModel(model);
  109552. });
  109553. this._observablesManager.onModelAddedObservable.add(function (model) {
  109554. _this.models.push(model);
  109555. });
  109556. this._observablesManager.onModelRemovedObservable.add(function (model) {
  109557. _this.models.splice(_this.models.indexOf(model), 1);
  109558. });
  109559. }
  109560. }
  109561. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipeline", {
  109562. get: function () {
  109563. return this._defaultRenderingPipeline;
  109564. },
  109565. enumerable: true,
  109566. configurable: true
  109567. });
  109568. Object.defineProperty(SceneManager.prototype, "isHdrSupported", {
  109569. /**
  109570. * Returns a boolean representing HDR support
  109571. */
  109572. get: function () {
  109573. return this._hdrSupport;
  109574. },
  109575. enumerable: true,
  109576. configurable: true
  109577. });
  109578. Object.defineProperty(SceneManager.prototype, "mainColor", {
  109579. /**
  109580. * Return the main color defined in the configuration.
  109581. */
  109582. get: function () {
  109583. return this._configurationContainer.mainColor;
  109584. },
  109585. enumerable: true,
  109586. configurable: true
  109587. });
  109588. Object.defineProperty(SceneManager.prototype, "reflectionColor", {
  109589. get: function () {
  109590. return this._configurationContainer.reflectionColor;
  109591. },
  109592. enumerable: true,
  109593. configurable: true
  109594. });
  109595. Object.defineProperty(SceneManager.prototype, "animationBlendingEnabled", {
  109596. get: function () {
  109597. return this.scene && this.scene.animationPropertiesOverride.enableBlending;
  109598. },
  109599. set: function (value) {
  109600. this.scene.animationPropertiesOverride.enableBlending = value;
  109601. },
  109602. enumerable: true,
  109603. configurable: true
  109604. });
  109605. Object.defineProperty(SceneManager.prototype, "observablesManager", {
  109606. get: function () {
  109607. return this._observablesManager;
  109608. },
  109609. enumerable: true,
  109610. configurable: true
  109611. });
  109612. Object.defineProperty(SceneManager.prototype, "processShadows", {
  109613. /**
  109614. * The flag defining whether shadows are rendered constantly or once.
  109615. */
  109616. get: function () {
  109617. return this._processShadows;
  109618. },
  109619. /**
  109620. * Should shadows be rendered every frame, or only once and stop.
  109621. * This can be used to optimize a scene.
  109622. *
  109623. * Not that the shadows will NOT disapear but will remain in place.
  109624. * @param process if true shadows will be updated once every frame. if false they will stop being updated.
  109625. */
  109626. set: function (process) {
  109627. var refreshType = process ? babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME : babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  109628. for (var _i = 0, _a = this.scene.lights; _i < _a.length; _i++) {
  109629. var light = _a[_i];
  109630. var generator = light.getShadowGenerator();
  109631. if (generator) {
  109632. var shadowMap = generator.getShadowMap();
  109633. if (shadowMap) {
  109634. shadowMap.refreshRate = refreshType;
  109635. }
  109636. }
  109637. }
  109638. this._processShadows = process;
  109639. },
  109640. enumerable: true,
  109641. configurable: true
  109642. });
  109643. Object.defineProperty(SceneManager.prototype, "groundEnabled", {
  109644. get: function () {
  109645. return this._groundEnabled;
  109646. },
  109647. set: function (newValue) {
  109648. if (newValue === this._groundEnabled)
  109649. return;
  109650. this._groundEnabled = newValue;
  109651. if (this.environmentHelper && this.environmentHelper.ground) {
  109652. this.environmentHelper.ground.setEnabled(this._groundEnabled);
  109653. }
  109654. },
  109655. enumerable: true,
  109656. configurable: true
  109657. });
  109658. Object.defineProperty(SceneManager.prototype, "groundMirrorEnabled", {
  109659. /**
  109660. * gets wether the reflection is disabled.
  109661. */
  109662. get: function () {
  109663. return this._groundMirrorEnabled;
  109664. },
  109665. /**
  109666. * sets wether the reflection is disabled.
  109667. */
  109668. set: function (value) {
  109669. if (this._groundMirrorEnabled === value) {
  109670. return;
  109671. }
  109672. this._groundMirrorEnabled = value;
  109673. if (this.environmentHelper && this.environmentHelper.groundMaterial && this.environmentHelper.groundMirror) {
  109674. if (!value) {
  109675. this.environmentHelper.groundMaterial.reflectionTexture = null;
  109676. }
  109677. else {
  109678. this.environmentHelper.groundMaterial.reflectionTexture = this.environmentHelper.groundMirror;
  109679. }
  109680. }
  109681. },
  109682. enumerable: true,
  109683. configurable: true
  109684. });
  109685. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipelineEnabled", {
  109686. get: function () {
  109687. return this._defaultRenderingPipelineEnabled;
  109688. },
  109689. set: function (value) {
  109690. if (value === this._defaultRenderingPipelineEnabled) {
  109691. return;
  109692. }
  109693. this._defaultRenderingPipelineEnabled = value;
  109694. this._rebuildPostprocesses();
  109695. if (this._defaultRenderingPipeline) {
  109696. this._defaultRenderingPipelineShouldBuild = false;
  109697. this._defaultRenderingPipeline.prepare();
  109698. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  109699. }
  109700. },
  109701. enumerable: true,
  109702. configurable: true
  109703. });
  109704. /**
  109705. * Sets the engine flags to unlock all babylon features.
  109706. * Can also be configured using the scene.flags configuration object
  109707. */
  109708. SceneManager.prototype.unlockBabylonFeatures = function () {
  109709. this.scene.shadowsEnabled = true;
  109710. this.scene.particlesEnabled = true;
  109711. this.scene.postProcessesEnabled = true;
  109712. this.scene.collisionsEnabled = true;
  109713. this.scene.lightsEnabled = true;
  109714. this.scene.texturesEnabled = true;
  109715. this.scene.lensFlaresEnabled = true;
  109716. this.scene.proceduralTexturesEnabled = true;
  109717. this.scene.renderTargetsEnabled = true;
  109718. this.scene.spritesEnabled = true;
  109719. this.scene.skeletonsEnabled = true;
  109720. this.scene.audioEnabled = true;
  109721. };
  109722. /**
  109723. * initialize the scene. Calling this function again will dispose the old scene, if exists.
  109724. */
  109725. SceneManager.prototype.initScene = function (sceneConfiguration, optimizerConfiguration) {
  109726. if (sceneConfiguration === void 0) { sceneConfiguration = {}; }
  109727. // if the scen exists, dispose it.
  109728. if (this.scene) {
  109729. this.scene.dispose();
  109730. }
  109731. // create a new scene
  109732. this.scene = new babylonjs_1.Scene(this._engine);
  109733. // set a default PBR material
  109734. if (!sceneConfiguration.defaultMaterial) {
  109735. var defaultMaterial = new BABYLON.PBRMaterial('defaultMaterial', this.scene);
  109736. defaultMaterial.reflectivityColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  109737. defaultMaterial.microSurface = 0.6;
  109738. if (this.scene.defaultMaterial) {
  109739. this.scene.defaultMaterial.dispose();
  109740. }
  109741. this.scene.defaultMaterial = defaultMaterial;
  109742. }
  109743. this.scene.animationPropertiesOverride = new babylonjs_1.AnimationPropertiesOverride();
  109744. babylonjs_1.Animation.AllowMatricesInterpolation = true;
  109745. /*if (sceneConfiguration.glow) {
  109746. let options: Partial<IGlowLayerOptions> = {
  109747. mainTextureFixedSize: 512
  109748. };
  109749. if (typeof sceneConfiguration.glow === 'object') {
  109750. options = sceneConfiguration.glow
  109751. }
  109752. var gl = new BABYLON.GlowLayer("glow", this.scene, options);
  109753. }*/
  109754. return this.onSceneInitObservable.notifyObserversWithPromise(this.scene);
  109755. };
  109756. SceneManager.prototype.clearScene = function (clearModels, clearLights) {
  109757. if (clearModels === void 0) { clearModels = true; }
  109758. if (clearLights === void 0) { clearLights = false; }
  109759. if (clearModels) {
  109760. this.models.forEach(function (m) { return m.dispose(); });
  109761. this.models.length = 0;
  109762. }
  109763. if (clearLights) {
  109764. this.scene.lights.forEach(function (l) { return l.dispose(); });
  109765. }
  109766. };
  109767. /**
  109768. * This will update the scene's configuration, including camera, lights, environment.
  109769. * @param newConfiguration the delta that should be configured. This includes only the changes
  109770. * @param globalConfiguration The global configuration object, after the new configuration was merged into it
  109771. */
  109772. SceneManager.prototype.updateConfiguration = function (newConfiguration) {
  109773. var _this = this;
  109774. if (this._configurationContainer) {
  109775. this._globalConfiguration = this._configurationContainer.configuration;
  109776. }
  109777. else {
  109778. this._globalConfiguration = newConfiguration;
  109779. }
  109780. if (newConfiguration.lab) {
  109781. if (newConfiguration.lab.assetsRootURL) {
  109782. this.labs.assetsRootURL = newConfiguration.lab.assetsRootURL;
  109783. }
  109784. }
  109785. // update scene configuration
  109786. if (newConfiguration.scene) {
  109787. this._configureScene(newConfiguration.scene);
  109788. }
  109789. // optimizer
  109790. if (newConfiguration.optimizer !== undefined) {
  109791. this._configureOptimizer(newConfiguration.optimizer);
  109792. }
  109793. // configure model
  109794. /*if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  109795. this._configureModel(newConfiguration.model);
  109796. }*/
  109797. // lights
  109798. this._configureLights(newConfiguration.lights);
  109799. // environment
  109800. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  109801. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  109802. }
  109803. // camera
  109804. this._configureCamera(newConfiguration.camera);
  109805. if (newConfiguration.lab) {
  109806. if (newConfiguration.lab.environmentMap) {
  109807. var rot_1 = newConfiguration.lab.environmentMap.rotationY;
  109808. this.labs.loadEnvironment(newConfiguration.lab.environmentMap.texture, function () {
  109809. _this.labs.applyEnvironmentMapConfiguration(rot_1);
  109810. });
  109811. if (!newConfiguration.lab.environmentMap.texture && newConfiguration.lab.environmentMap.rotationY) {
  109812. this.labs.applyEnvironmentMapConfiguration(newConfiguration.lab.environmentMap.rotationY);
  109813. }
  109814. }
  109815. // rendering piplines
  109816. if (newConfiguration.lab.defaultRenderingPipelines) {
  109817. var pipelineConfig = newConfiguration.lab.defaultRenderingPipelines;
  109818. if (typeof pipelineConfig === 'boolean') {
  109819. this.defaultRenderingPipelineEnabled = pipelineConfig;
  109820. }
  109821. else {
  109822. this.defaultRenderingPipelineEnabled = true;
  109823. }
  109824. }
  109825. if (newConfiguration.lab.environmentMainColor) {
  109826. var mainColor = new babylonjs_1.Color3().copyFrom(newConfiguration.lab.environmentMainColor);
  109827. this.environmentHelper.setMainColor(mainColor);
  109828. }
  109829. if (newConfiguration.lab.globalLightRotation !== undefined) {
  109830. // rotate all lights that are shadow lights
  109831. this.scene.lights.filter(function (light) { return light instanceof babylonjs_1.ShadowLight; }).forEach(function (light) {
  109832. // casting and '!' are safe, due to the constraints tested before
  109833. _this.labs.rotateShadowLight(light, newConfiguration.lab.globalLightRotation);
  109834. });
  109835. this._forceShadowUpdate = true;
  109836. }
  109837. }
  109838. if (this._defaultRenderingPipeline && this._defaultRenderingPipeline.imageProcessing) {
  109839. this._defaultRenderingPipeline.imageProcessing.fromLinearSpace = true;
  109840. }
  109841. if (this._defaultRenderingPipelineShouldBuild && this._defaultRenderingPipeline) {
  109842. this._defaultRenderingPipelineShouldBuild = false;
  109843. this._defaultRenderingPipeline.prepare();
  109844. }
  109845. };
  109846. SceneManager.prototype._rebuildPostprocesses = function (configuration) {
  109847. if (!this._defaultRenderingPipelineEnabled || !configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", this._globalConfiguration)) {
  109848. if (this._defaultRenderingPipeline) {
  109849. this._defaultRenderingPipeline.dispose();
  109850. this._defaultRenderingPipeline = null;
  109851. this.scene.autoClearDepthAndStencil = true;
  109852. this.scene.autoClear = true;
  109853. this.scene.imageProcessingConfiguration.applyByPostProcess = false;
  109854. }
  109855. return;
  109856. }
  109857. var pipelineConfig = configuration || (this._globalConfiguration.lab && this._globalConfiguration.lab.defaultRenderingPipelines);
  109858. if (pipelineConfig) {
  109859. if (!this._defaultRenderingPipeline) {
  109860. // Create pipeline in manual mode to avoid triggering multiple shader compilations
  109861. this._defaultRenderingPipeline = new babylonjs_1.DefaultRenderingPipeline("default rendering pipeline", this._hdrSupport, this.scene, [this.camera], false);
  109862. }
  109863. this.scene.autoClear = false;
  109864. this.scene.autoClearDepthAndStencil = false;
  109865. this._defaultRenderingPipelineShouldBuild = true;
  109866. var bloomEnabled = this._bloomEnabled;
  109867. if (typeof pipelineConfig !== 'boolean') {
  109868. helper_1.extendClassWithConfig(this._defaultRenderingPipeline, pipelineConfig);
  109869. this._bloomEnabled = !!pipelineConfig.bloomEnabled;
  109870. this._fxaaEnabled = !!pipelineConfig.fxaaEnabled;
  109871. bloomEnabled = this._bloomEnabled && pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight > 0;
  109872. this._defaultRenderingPipeline.bloomWeight = (pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight) || (this._defaultRenderingPipeline.bloomWeight);
  109873. }
  109874. this._defaultRenderingPipeline.bloomEnabled = bloomEnabled;
  109875. this._defaultRenderingPipeline.fxaaEnabled = this.fxaaEnabled;
  109876. }
  109877. };
  109878. Object.defineProperty(SceneManager.prototype, "bloomEnabled", {
  109879. get: function () {
  109880. return this._bloomEnabled;
  109881. },
  109882. set: function (value) {
  109883. if (this._bloomEnabled === value) {
  109884. return;
  109885. }
  109886. this._bloomEnabled = value;
  109887. this._rebuildPostprocesses();
  109888. if (this._defaultRenderingPipeline) {
  109889. this._defaultRenderingPipelineShouldBuild = false;
  109890. this._defaultRenderingPipeline.prepare();
  109891. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  109892. }
  109893. },
  109894. enumerable: true,
  109895. configurable: true
  109896. });
  109897. Object.defineProperty(SceneManager.prototype, "fxaaEnabled", {
  109898. get: function () {
  109899. return this._fxaaEnabled;
  109900. },
  109901. set: function (value) {
  109902. if (this._fxaaEnabled === value) {
  109903. return;
  109904. }
  109905. this._fxaaEnabled = value;
  109906. this._rebuildPostprocesses();
  109907. if (this._defaultRenderingPipeline) {
  109908. this._defaultRenderingPipelineShouldBuild = false;
  109909. this._defaultRenderingPipeline.prepare();
  109910. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  109911. }
  109912. },
  109913. enumerable: true,
  109914. configurable: true
  109915. });
  109916. /**
  109917. * internally configure the scene using the provided configuration.
  109918. * The scene will not be recreated, but just updated.
  109919. * @param sceneConfig the (new) scene configuration
  109920. */
  109921. SceneManager.prototype._configureScene = function (sceneConfig) {
  109922. // sanity check!
  109923. if (!this.scene) {
  109924. return;
  109925. }
  109926. var cc = sceneConfig.clearColor;
  109927. var oldcc = this.scene.clearColor;
  109928. if (cc) {
  109929. if (cc.r !== undefined) {
  109930. oldcc.r = cc.r;
  109931. }
  109932. if (cc.g !== undefined) {
  109933. oldcc.g = cc.g;
  109934. }
  109935. if (cc.b !== undefined) {
  109936. oldcc.b = cc.b;
  109937. }
  109938. if (cc.a !== undefined) {
  109939. oldcc.a = cc.a;
  109940. }
  109941. }
  109942. // image processing configuration - optional.
  109943. if (sceneConfig.imageProcessingConfiguration) {
  109944. helper_1.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  109945. }
  109946. //animation properties override
  109947. if (sceneConfig.animationPropertiesOverride) {
  109948. helper_1.extendClassWithConfig(this.scene.animationPropertiesOverride, sceneConfig.animationPropertiesOverride);
  109949. }
  109950. if (sceneConfig.environmentTexture) {
  109951. if (!(this.scene.environmentTexture && this.scene.environmentTexture.url === sceneConfig.environmentTexture)) {
  109952. if (this.scene.environmentTexture && this.scene.environmentTexture.dispose) {
  109953. this.scene.environmentTexture.dispose();
  109954. }
  109955. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  109956. this.scene.environmentTexture = environmentTexture;
  109957. }
  109958. }
  109959. if (sceneConfig.debug === true) {
  109960. this.scene.debugLayer.show();
  109961. }
  109962. else if (sceneConfig.debug === false) {
  109963. if (this.scene.debugLayer.isVisible()) {
  109964. this.scene.debugLayer.hide();
  109965. }
  109966. }
  109967. if (sceneConfig.disableHdr) {
  109968. this._handleHardwareLimitations(false);
  109969. }
  109970. else {
  109971. this._handleHardwareLimitations(true);
  109972. }
  109973. if (sceneConfig.renderInBackground !== undefined) {
  109974. this._engine.renderEvenInBackground = !!sceneConfig.renderInBackground;
  109975. }
  109976. var canvas = this._engine.getRenderingCanvas();
  109977. if (canvas) {
  109978. if (this.camera && sceneConfig.disableCameraControl) {
  109979. this.camera.detachControl(canvas);
  109980. }
  109981. else if (this.camera && sceneConfig.disableCameraControl === false) {
  109982. this.camera.attachControl(canvas);
  109983. }
  109984. }
  109985. // process mainColor changes:
  109986. if (sceneConfig.mainColor) {
  109987. this._configurationContainer.mainColor = this.mainColor || babylonjs_1.Color3.White();
  109988. var mc = sceneConfig.mainColor;
  109989. if (mc.r !== undefined) {
  109990. this.mainColor.r = mc.r;
  109991. }
  109992. if (mc.g !== undefined) {
  109993. this.mainColor.g = mc.g;
  109994. }
  109995. if (mc.b !== undefined) {
  109996. this.mainColor.b = mc.b;
  109997. }
  109998. this.reflectionColor.copyFrom(this.mainColor);
  109999. var environmentTint = configuration_1.getConfigurationKey("lab.environmentMap.tintLevel", this._globalConfiguration) || 0;
  110000. // reflection color
  110001. this.reflectionColor.toLinearSpaceToRef(this.reflectionColor);
  110002. this.reflectionColor.scaleToRef(1 / this.scene.imageProcessingConfiguration.exposure, this.reflectionColor);
  110003. var tmpColor3 = babylonjs_1.Color3.Lerp(this._white, this.reflectionColor, environmentTint);
  110004. this.reflectionColor.copyFrom(tmpColor3);
  110005. //update the environment, if exists
  110006. if (this.environmentHelper) {
  110007. if (this.environmentHelper.groundMaterial) {
  110008. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  110009. }
  110010. if (this.environmentHelper.skyboxMaterial) {
  110011. this.environmentHelper.skyboxMaterial._perceptualColor = this.mainColor;
  110012. }
  110013. }
  110014. }
  110015. if (sceneConfig.defaultMaterial) {
  110016. var conf = sceneConfig.defaultMaterial;
  110017. if ((conf.materialType === 'standard' && this.scene.defaultMaterial.getClassName() !== 'StandardMaterial') ||
  110018. (conf.materialType === 'pbr' && this.scene.defaultMaterial.getClassName() !== 'PBRMaterial')) {
  110019. this.scene.defaultMaterial.dispose();
  110020. if (conf.materialType === 'standard') {
  110021. this.scene.defaultMaterial = new babylonjs_1.StandardMaterial("defaultMaterial", this.scene);
  110022. }
  110023. else {
  110024. this.scene.defaultMaterial = new babylonjs_1.PBRMaterial("defaultMaterial", this.scene);
  110025. }
  110026. }
  110027. helper_1.extendClassWithConfig(this.scene.defaultMaterial, conf);
  110028. }
  110029. if (sceneConfig.flags) {
  110030. helper_1.extendClassWithConfig(this.scene, sceneConfig.flags);
  110031. }
  110032. this.onSceneConfiguredObservable.notifyObservers({
  110033. sceneManager: this,
  110034. object: this.scene,
  110035. newConfiguration: sceneConfig
  110036. });
  110037. };
  110038. /**
  110039. * Configure the scene optimizer.
  110040. * The existing scene optimizer will be disposed and a new one will be created.
  110041. * @param optimizerConfig the (new) optimizer configuration
  110042. */
  110043. SceneManager.prototype._configureOptimizer = function (optimizerConfig) {
  110044. var _this = this;
  110045. if (typeof optimizerConfig === 'boolean') {
  110046. if (this.sceneOptimizer) {
  110047. this.sceneOptimizer.stop();
  110048. this.sceneOptimizer.dispose();
  110049. delete this.sceneOptimizer;
  110050. }
  110051. if (optimizerConfig) {
  110052. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  110053. this.sceneOptimizer.start();
  110054. }
  110055. }
  110056. else {
  110057. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  110058. // check for degradation
  110059. if (optimizerConfig.degradation) {
  110060. switch (optimizerConfig.degradation) {
  110061. case "low":
  110062. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  110063. break;
  110064. case "moderate":
  110065. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  110066. break;
  110067. case "hight":
  110068. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  110069. break;
  110070. }
  110071. }
  110072. if (this.sceneOptimizer) {
  110073. this.sceneOptimizer.stop();
  110074. this.sceneOptimizer.dispose();
  110075. }
  110076. if (optimizerConfig.custom) {
  110077. var customOptimizer_1 = _1.getCustomOptimizerByName(optimizerConfig.custom, optimizerConfig.improvementMode);
  110078. if (customOptimizer_1) {
  110079. optimizerOptions.addCustomOptimization(function () {
  110080. return customOptimizer_1(_this);
  110081. }, function () {
  110082. return "Babylon Viewer " + optimizerConfig.custom + " custom optimization";
  110083. });
  110084. }
  110085. }
  110086. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  110087. this.sceneOptimizer.start();
  110088. }
  110089. this.onSceneOptimizerConfiguredObservable.notifyObservers({
  110090. sceneManager: this,
  110091. object: this.sceneOptimizer,
  110092. newConfiguration: optimizerConfig
  110093. });
  110094. };
  110095. /**
  110096. * configure all models using the configuration.
  110097. * @param modelConfiguration the configuration to use to reconfigure the models
  110098. */
  110099. /*protected _configureModel(modelConfiguration: Partial<IModelConfiguration>) {
  110100. this.models.forEach(model => {
  110101. model.updateConfiguration(modelConfiguration);
  110102. });
  110103. this.onModelsConfiguredObservable.notifyObservers({
  110104. sceneManager: this,
  110105. object: this.models,
  110106. newConfiguration: modelConfiguration
  110107. });
  110108. }*/
  110109. /**
  110110. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  110111. * @param cameraConfig the new camera configuration
  110112. * @param model optionally use the model to configure the camera.
  110113. */
  110114. SceneManager.prototype._configureCamera = function (cameraConfig) {
  110115. var _this = this;
  110116. if (cameraConfig === void 0) { cameraConfig = {}; }
  110117. if (!this.scene.activeCamera) {
  110118. var attachControl = true;
  110119. if (this._globalConfiguration.scene && this._globalConfiguration.scene.disableCameraControl) {
  110120. attachControl = false;
  110121. }
  110122. this.scene.createDefaultCamera(true, true, attachControl);
  110123. this.camera = this.scene.activeCamera;
  110124. this.camera.setTarget(babylonjs_1.Vector3.Zero());
  110125. }
  110126. if (cameraConfig.position) {
  110127. var newPosition = this.camera.position.clone();
  110128. helper_1.extendClassWithConfig(newPosition, cameraConfig.position);
  110129. this.camera.setPosition(newPosition);
  110130. }
  110131. if (cameraConfig.target) {
  110132. var newTarget = this.camera.target.clone();
  110133. helper_1.extendClassWithConfig(newTarget, cameraConfig.target);
  110134. this.camera.setTarget(newTarget);
  110135. } /*else if (this.models.length && !cameraConfig.disableAutoFocus) {
  110136. this._focusOnModel(this.models[0]);
  110137. }*/
  110138. if (cameraConfig.rotation) {
  110139. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  110140. }
  110141. if (cameraConfig.behaviors) {
  110142. for (var name_1 in cameraConfig.behaviors) {
  110143. if (cameraConfig.behaviors[name_1] !== undefined) {
  110144. this._setCameraBehavior(name_1, cameraConfig.behaviors[name_1]);
  110145. }
  110146. }
  110147. }
  110148. ;
  110149. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  110150. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  110151. });
  110152. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  110153. var sceneDiagonalLenght = sceneDiagonal.length();
  110154. if (isFinite(sceneDiagonalLenght))
  110155. this.camera.upperRadiusLimit = sceneDiagonalLenght * 4;
  110156. else {
  110157. this.camera.upperRadiusLimit = 10;
  110158. }
  110159. // sanity check!
  110160. if (this.scene.imageProcessingConfiguration) {
  110161. this.scene.imageProcessingConfiguration.colorCurvesEnabled = true;
  110162. this.scene.imageProcessingConfiguration.vignetteEnabled = true;
  110163. this.scene.imageProcessingConfiguration.toneMappingEnabled = !!configuration_1.getConfigurationKey("camera.toneMappingEnabled", this._globalConfiguration);
  110164. }
  110165. helper_1.extendClassWithConfig(this.camera, cameraConfig);
  110166. this.onCameraConfiguredObservable.notifyObservers({
  110167. sceneManager: this,
  110168. object: this.camera,
  110169. newConfiguration: cameraConfig
  110170. });
  110171. };
  110172. SceneManager.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  110173. var _this = this;
  110174. if (!skyboxConifguration && !groundConfiguration) {
  110175. if (this.environmentHelper) {
  110176. this.environmentHelper.dispose();
  110177. delete this.environmentHelper;
  110178. }
  110179. ;
  110180. }
  110181. else {
  110182. var options = {
  110183. createGround: !!groundConfiguration && this._groundEnabled,
  110184. createSkybox: !!skyboxConifguration,
  110185. setupImageProcessing: false,
  110186. };
  110187. // will that cause problems with model ground configuration?
  110188. /*if (model) {
  110189. const boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  110190. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  110191. const halfSizeVec = sizeVec.scale(0.5);
  110192. const center = boundingInfo.min.add(halfSizeVec);
  110193. options.groundYBias = -center.y;
  110194. }*/
  110195. if (groundConfiguration) {
  110196. var groundConfig_1 = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  110197. var groundSize = groundConfig_1.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  110198. if (groundSize) {
  110199. options.groundSize = groundSize;
  110200. }
  110201. options.enableGroundShadow = groundConfig_1 === true || groundConfig_1.receiveShadows;
  110202. if (groundConfig_1.shadowLevel !== undefined) {
  110203. options.groundShadowLevel = groundConfig_1.shadowLevel;
  110204. }
  110205. options.enableGroundMirror = !!groundConfig_1.mirror && this.groundMirrorEnabled;
  110206. if (groundConfig_1.texture) {
  110207. options.groundTexture = this.labs.getAssetUrl(groundConfig_1.texture);
  110208. }
  110209. if (groundConfig_1.color) {
  110210. options.groundColor = new babylonjs_1.Color3(groundConfig_1.color.r, groundConfig_1.color.g, groundConfig_1.color.b);
  110211. }
  110212. if (groundConfig_1.opacity !== undefined) {
  110213. options.groundOpacity = groundConfig_1.opacity;
  110214. }
  110215. if (groundConfig_1.mirror) {
  110216. options.enableGroundMirror = true;
  110217. // to prevent undefines
  110218. if (typeof groundConfig_1.mirror === "object") {
  110219. if (groundConfig_1.mirror.amount !== undefined)
  110220. options.groundMirrorAmount = groundConfig_1.mirror.amount;
  110221. if (groundConfig_1.mirror.sizeRatio !== undefined)
  110222. options.groundMirrorSizeRatio = groundConfig_1.mirror.sizeRatio;
  110223. if (groundConfig_1.mirror.blurKernel !== undefined)
  110224. options.groundMirrorBlurKernel = groundConfig_1.mirror.blurKernel;
  110225. if (groundConfig_1.mirror.fresnelWeight !== undefined)
  110226. options.groundMirrorFresnelWeight = groundConfig_1.mirror.fresnelWeight;
  110227. if (groundConfig_1.mirror.fallOffDistance !== undefined)
  110228. options.groundMirrorFallOffDistance = groundConfig_1.mirror.fallOffDistance;
  110229. if (this._defaultPipelineTextureType !== undefined)
  110230. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  110231. }
  110232. }
  110233. }
  110234. var postInitSkyboxMaterial = false;
  110235. if (skyboxConifguration) {
  110236. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  110237. if (conf.material && conf.material.imageProcessingConfiguration) {
  110238. options.setupImageProcessing = false; // will be configured later manually.
  110239. }
  110240. var skyboxSize = conf.scale;
  110241. if (skyboxSize) {
  110242. options.skyboxSize = skyboxSize;
  110243. }
  110244. options.sizeAuto = !options.skyboxSize;
  110245. if (conf.color) {
  110246. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  110247. }
  110248. if (conf.cubeTexture && conf.cubeTexture.url) {
  110249. if (typeof conf.cubeTexture.url === "string") {
  110250. options.skyboxTexture = this.labs.getAssetUrl(conf.cubeTexture.url);
  110251. }
  110252. else {
  110253. // init later!
  110254. postInitSkyboxMaterial = true;
  110255. }
  110256. }
  110257. if (conf.material) {
  110258. postInitSkyboxMaterial = true;
  110259. }
  110260. }
  110261. options.setupImageProcessing = false; // TMP
  110262. if (!this.environmentHelper) {
  110263. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  110264. }
  110265. else {
  110266. // unlikely, but there might be a new scene! we need to dispose.
  110267. // get the scene used by the envHelper
  110268. var scene = this.environmentHelper.rootMesh.getScene();
  110269. // is it a different scene? Oh no!
  110270. if (scene !== this.scene) {
  110271. this.environmentHelper.dispose();
  110272. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  110273. }
  110274. else {
  110275. this.environmentHelper.updateOptions(options);
  110276. }
  110277. }
  110278. if (this.environmentHelper.rootMesh && this._globalConfiguration.scene && this._globalConfiguration.scene.environmentRotationY !== undefined) {
  110279. this.environmentHelper.rootMesh.rotation.y = this._globalConfiguration.scene.environmentRotationY;
  110280. }
  110281. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  110282. if (this.environmentHelper.groundMaterial && groundConfig) {
  110283. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  110284. if (groundConfig.material) {
  110285. helper_1.extendClassWithConfig(this.environmentHelper.groundMaterial, groundConfig.material);
  110286. }
  110287. if (this.environmentHelper.groundMirror) {
  110288. var mirrorClearColor = this.environmentHelper.groundMaterial._perceptualColor.toLinearSpace();
  110289. // TODO user camera exposure value to set the mirror clear color
  110290. var exposure = Math.pow(2.0, -this.scene.imageProcessingConfiguration.exposure) * Math.PI;
  110291. mirrorClearColor.scaleToRef(1 / exposure, mirrorClearColor);
  110292. this.environmentHelper.groundMirror.clearColor.r = babylonjs_1.Scalar.Clamp(mirrorClearColor.r);
  110293. this.environmentHelper.groundMirror.clearColor.g = babylonjs_1.Scalar.Clamp(mirrorClearColor.g);
  110294. this.environmentHelper.groundMirror.clearColor.b = babylonjs_1.Scalar.Clamp(mirrorClearColor.b);
  110295. this.environmentHelper.groundMirror.clearColor.a = 1;
  110296. if (!this.groundMirrorEnabled) {
  110297. this.environmentHelper.groundMaterial.reflectionTexture = null;
  110298. }
  110299. }
  110300. }
  110301. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  110302. if (skyboxMaterial) {
  110303. skyboxMaterial._perceptualColor = this.mainColor;
  110304. if (postInitSkyboxMaterial) {
  110305. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material) {
  110306. helper_1.extendClassWithConfig(skyboxMaterial, skyboxConifguration.material);
  110307. }
  110308. }
  110309. }
  110310. }
  110311. this._observablesManager && this._observablesManager.onModelLoadedObservable.add(function (model) {
  110312. _this._updateGroundMirrorRenderList(model);
  110313. });
  110314. this.onEnvironmentConfiguredObservable.notifyObservers({
  110315. sceneManager: this,
  110316. object: this.environmentHelper,
  110317. newConfiguration: {
  110318. skybox: skyboxConifguration,
  110319. ground: groundConfiguration
  110320. }
  110321. });
  110322. };
  110323. /**
  110324. * configure the lights.
  110325. *
  110326. * @param lightsConfiguration the (new) light(s) configuration
  110327. * @param model optionally use the model to configure the camera.
  110328. */
  110329. SceneManager.prototype._configureLights = function (lightsConfiguration) {
  110330. var _this = this;
  110331. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  110332. // sanity check!
  110333. var lightKeys = Object.keys(lightsConfiguration).filter(function (name) { return name !== 'globalRotation'; });
  110334. if (!lightKeys.length) {
  110335. if (!this.scene.lights.length)
  110336. this.scene.createDefaultLight(true);
  110337. }
  110338. else {
  110339. var lightsAvailable_1 = this.scene.lights.map(function (light) { return light.name; });
  110340. // compare to the global (!) configuration object and dispose unneeded:
  110341. var lightsToConfigure_1 = Object.keys(this._globalConfiguration.lights || []);
  110342. if (Object.keys(lightsToConfigure_1).length !== lightsAvailable_1.length) {
  110343. lightsAvailable_1.forEach(function (lName) {
  110344. if (lightsToConfigure_1.indexOf(lName) === -1) {
  110345. _this.scene.getLightByName(lName).dispose();
  110346. }
  110347. });
  110348. }
  110349. lightKeys.forEach(function (name, idx) {
  110350. var lightConfig = { type: 0 };
  110351. if (typeof lightsConfiguration[name] === 'object') {
  110352. lightConfig = lightsConfiguration[name];
  110353. }
  110354. if (typeof lightsConfiguration[name] === 'number') {
  110355. lightConfig.type = lightsConfiguration[name];
  110356. }
  110357. lightConfig.name = name;
  110358. var light;
  110359. // light is not already available
  110360. if (lightsAvailable_1.indexOf(name) === -1) {
  110361. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  110362. if (!constructor)
  110363. return;
  110364. light = constructor();
  110365. }
  110366. else {
  110367. // available? get it from the scene
  110368. light = _this.scene.getLightByName(name);
  110369. if (typeof lightsConfiguration[name] === 'boolean') {
  110370. lightConfig.type = light.getTypeID();
  110371. }
  110372. lightsAvailable_1 = lightsAvailable_1.filter(function (ln) { return ln !== name; });
  110373. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  110374. light.dispose();
  110375. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  110376. if (!constructor)
  110377. return;
  110378. light = constructor();
  110379. }
  110380. }
  110381. // if config set the light to false, dispose it.
  110382. if (lightsConfiguration[name] === false) {
  110383. light.dispose();
  110384. return;
  110385. }
  110386. //enabled
  110387. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  110388. light.setEnabled(enabled);
  110389. helper_1.extendClassWithConfig(light, lightConfig);
  110390. //position. Some lights don't support shadows
  110391. if (light instanceof babylonjs_1.ShadowLight) {
  110392. // set default values
  110393. light.shadowMinZ = light.shadowMinZ || 0.2;
  110394. light.shadowMaxZ = Math.min(10, light.shadowMaxZ || 10); //large far clips reduce shadow depth precision
  110395. if (lightConfig.target) {
  110396. if (light.setDirectionToTarget) {
  110397. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  110398. light.setDirectionToTarget(target);
  110399. }
  110400. }
  110401. else if (lightConfig.direction) {
  110402. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  110403. light.direction = direction;
  110404. }
  110405. var isShadowEnabled = false;
  110406. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  110407. light.shadowFrustumSize = lightConfig.shadowFrustumSize || 2;
  110408. isShadowEnabled = true;
  110409. }
  110410. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  110411. var spotLight = light;
  110412. if (lightConfig.spotAngle !== undefined) {
  110413. spotLight.angle = lightConfig.spotAngle * Math.PI / 180;
  110414. }
  110415. if (spotLight.angle && lightConfig.shadowFieldOfView) {
  110416. spotLight.shadowAngleScale = lightConfig.shadowFieldOfView / spotLight.angle;
  110417. }
  110418. isShadowEnabled = true;
  110419. }
  110420. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  110421. if (lightConfig.shadowFieldOfView) {
  110422. light.shadowAngle = lightConfig.shadowFieldOfView * Math.PI / 180;
  110423. }
  110424. isShadowEnabled = true;
  110425. }
  110426. var shadowGenerator_1 = light.getShadowGenerator();
  110427. if (isShadowEnabled && lightConfig.shadowEnabled && _this._maxShadows) {
  110428. var bufferSize = lightConfig.shadowBufferSize || 256;
  110429. if (!shadowGenerator_1) {
  110430. shadowGenerator_1 = new babylonjs_1.ShadowGenerator(bufferSize, light);
  110431. }
  110432. var blurKernel = _this.getBlurKernel(light, bufferSize);
  110433. shadowGenerator_1.bias = _this._shadowGeneratorBias;
  110434. shadowGenerator_1.blurKernel = blurKernel;
  110435. //override defaults
  110436. helper_1.extendClassWithConfig(shadowGenerator_1, lightConfig.shadowConfig || {});
  110437. // add the focues meshes to the shadow list
  110438. _this._observablesManager && _this._observablesManager.onModelLoadedObservable.add(function (model) {
  110439. _this._updateShadowRenderList(shadowGenerator_1, model);
  110440. });
  110441. //if (model) {
  110442. _this._updateShadowRenderList(shadowGenerator_1);
  110443. //}
  110444. }
  110445. else if (shadowGenerator_1) {
  110446. shadowGenerator_1.dispose();
  110447. }
  110448. }
  110449. });
  110450. // render priority
  110451. var globalLightsConfiguration_1 = this._globalConfiguration.lights || {};
  110452. Object.keys(globalLightsConfiguration_1).sort().forEach(function (name, idx) {
  110453. var configuration = globalLightsConfiguration_1[name];
  110454. var light = _this.scene.getLightByName(name);
  110455. // sanity check
  110456. if (!light)
  110457. return;
  110458. light.renderPriority = -idx;
  110459. });
  110460. }
  110461. this.onLightsConfiguredObservable.notifyObservers({
  110462. sceneManager: this,
  110463. object: this.scene.lights,
  110464. newConfiguration: lightsConfiguration
  110465. });
  110466. };
  110467. SceneManager.prototype._updateShadowRenderList = function (shadowGenerator, model, resetList) {
  110468. var focusMeshes = model ? model.meshes : this.scene.meshes;
  110469. // add the focues meshes to the shadow list
  110470. var shadownMap = shadowGenerator.getShadowMap();
  110471. if (!shadownMap)
  110472. return;
  110473. if (resetList && shadownMap.renderList) {
  110474. shadownMap.renderList.length = 0;
  110475. }
  110476. else {
  110477. shadownMap.renderList = shadownMap.renderList || [];
  110478. }
  110479. for (var index = 0; index < focusMeshes.length; index++) {
  110480. var mesh = focusMeshes[index];
  110481. if (babylonjs_1.Tags.MatchesQuery(mesh, 'castShadow') && shadownMap.renderList.indexOf(mesh) === -1) {
  110482. shadownMap.renderList.push(mesh);
  110483. }
  110484. }
  110485. if (!this._shadowGroundPlane) {
  110486. if (shadowGenerator.useBlurCloseExponentialShadowMap) {
  110487. var shadowGroundPlane = babylonjs_1.Mesh.CreatePlane("shadowGroundPlane", 100, this.scene, false);
  110488. shadowGroundPlane.useVertexColors = false;
  110489. //material isn't ever used in rendering, just used to set back face culling
  110490. shadowGroundPlane.material = new babylonjs_1.StandardMaterial('shadowGroundPlaneMaterial', this.scene);
  110491. shadowGroundPlane.material.backFaceCulling = false;
  110492. shadowGroundPlane.rotation.x = Math.PI * 0.5;
  110493. shadowGroundPlane.freezeWorldMatrix();
  110494. this._shadowGroundPlane = shadowGroundPlane;
  110495. this.scene.removeMesh(shadowGroundPlane);
  110496. }
  110497. }
  110498. else {
  110499. if (!shadowGenerator.useBlurCloseExponentialShadowMap) {
  110500. this._shadowGroundPlane.dispose();
  110501. this._shadowGroundPlane = null;
  110502. }
  110503. }
  110504. if (this._shadowGroundPlane && shadownMap.renderList.indexOf(this._shadowGroundPlane) === -1) {
  110505. shadownMap.renderList.push(this._shadowGroundPlane);
  110506. }
  110507. };
  110508. SceneManager.prototype._updateGroundMirrorRenderList = function (model, resetList) {
  110509. if (this.environmentHelper.groundMirror && this.environmentHelper.groundMirror.renderList) {
  110510. var focusMeshes = model ? model.meshes : this.scene.meshes;
  110511. var renderList = this.environmentHelper.groundMirror.renderList;
  110512. if (resetList) {
  110513. renderList.length = 0;
  110514. }
  110515. for (var index = 0; index < focusMeshes.length; index++) {
  110516. var mesh = focusMeshes[index];
  110517. if (renderList.indexOf(mesh) === -1) {
  110518. renderList.push(mesh);
  110519. }
  110520. }
  110521. }
  110522. };
  110523. /**
  110524. * Gets the shadow map blur kernel according to the light configuration.
  110525. * @param light The light used to generate the shadows
  110526. * @param bufferSize The size of the shadow map
  110527. * @return the kernel blur size
  110528. */
  110529. SceneManager.prototype.getBlurKernel = function (light, bufferSize) {
  110530. var normalizedBlurKernel = 0.05; // TODO Should come from the config.
  110531. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  110532. normalizedBlurKernel = normalizedBlurKernel / light.shadowFrustumSize;
  110533. }
  110534. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  110535. normalizedBlurKernel = normalizedBlurKernel / light.shadowAngle;
  110536. }
  110537. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  110538. normalizedBlurKernel = normalizedBlurKernel / (light.angle * light.shadowAngleScale);
  110539. }
  110540. var minimumBlurKernel = 5 / (bufferSize / 256); //magic number that aims to keep away sawtooth shadows
  110541. var blurKernel = Math.max(bufferSize * normalizedBlurKernel, minimumBlurKernel);
  110542. return blurKernel;
  110543. };
  110544. /**
  110545. * Alters render settings to reduce features based on hardware feature limitations
  110546. * @param enableHDR Allows the viewer to run in HDR mode.
  110547. */
  110548. SceneManager.prototype._handleHardwareLimitations = function (enableHDR) {
  110549. if (enableHDR === void 0) { enableHDR = true; }
  110550. //flip rendering settings switches based on hardware support
  110551. var maxVaryingRows = this._engine.getCaps().maxVaryingVectors;
  110552. var maxFragmentSamplers = this._engine.getCaps().maxTexturesImageUnits;
  110553. //shadows are disabled if there's not enough varyings for a single shadow
  110554. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  110555. this._maxShadows = 0;
  110556. }
  110557. else {
  110558. this._maxShadows = 3;
  110559. }
  110560. //can we render to any >= 16-bit targets (required for HDR)
  110561. var caps = this._engine.getCaps();
  110562. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  110563. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  110564. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  110565. if (linearHalfFloatTargets) {
  110566. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  110567. this._shadowGeneratorBias = 0.002;
  110568. }
  110569. else if (linearFloatTargets) {
  110570. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  110571. this._shadowGeneratorBias = 0.001;
  110572. }
  110573. else {
  110574. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  110575. this._shadowGeneratorBias = 0.001;
  110576. }
  110577. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  110578. };
  110579. /**
  110580. * Dispoe the entire viewer including the scene and the engine
  110581. */
  110582. SceneManager.prototype.dispose = function () {
  110583. // this.onCameraConfiguredObservable.clear();
  110584. this.onEnvironmentConfiguredObservable.clear();
  110585. this.onLightsConfiguredObservable.clear();
  110586. this.onModelsConfiguredObservable.clear();
  110587. this.onSceneConfiguredObservable.clear();
  110588. this.onSceneInitObservable.clear();
  110589. this.onSceneOptimizerConfiguredObservable.clear();
  110590. if (this.sceneOptimizer) {
  110591. this.sceneOptimizer.stop();
  110592. this.sceneOptimizer.dispose();
  110593. }
  110594. if (this.environmentHelper) {
  110595. this.environmentHelper.dispose();
  110596. }
  110597. this.models.forEach(function (model) {
  110598. model.dispose();
  110599. });
  110600. if (this._defaultRenderingPipeline) {
  110601. this._defaultRenderingPipeline.dispose();
  110602. }
  110603. this.models.length = 0;
  110604. if (this.scene) {
  110605. this.scene.dispose();
  110606. }
  110607. };
  110608. SceneManager.prototype._setCameraBehavior = function (name, behaviorConfig, payload) {
  110609. var behavior;
  110610. var type;
  110611. if (typeof behaviorConfig === 'object') {
  110612. type = behaviorConfig.type;
  110613. }
  110614. else if (typeof behaviorConfig === 'number') {
  110615. type = behaviorConfig;
  110616. }
  110617. else {
  110618. type = this._cameraBehaviorMapping[name];
  110619. }
  110620. if (type === undefined)
  110621. return;
  110622. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  110623. var enabled = true;
  110624. if (typeof behaviorConfig === 'boolean') {
  110625. enabled = behaviorConfig;
  110626. }
  110627. // constructing behavior
  110628. switch (type) {
  110629. case 0 /* AUTOROTATION */:
  110630. this.camera.useAutoRotationBehavior = enabled;
  110631. behavior = this.camera.autoRotationBehavior;
  110632. break;
  110633. case 1 /* BOUNCING */:
  110634. this.camera.useBouncingBehavior = enabled;
  110635. behavior = this.camera.bouncingBehavior;
  110636. break;
  110637. case 2 /* FRAMING */:
  110638. this.camera.useFramingBehavior = enabled;
  110639. behavior = this.camera.framingBehavior;
  110640. break;
  110641. default:
  110642. behavior = null;
  110643. break;
  110644. }
  110645. if (behavior) {
  110646. this._cameraBehaviorMapping[name] = type;
  110647. if (typeof behaviorConfig === "object") {
  110648. helper_1.extendClassWithConfig(behavior, behaviorConfig);
  110649. }
  110650. }
  110651. // post attach configuration. Some functionalities require the attached camera.
  110652. switch (type) {
  110653. case 0 /* AUTOROTATION */:
  110654. break;
  110655. case 1 /* BOUNCING */:
  110656. break;
  110657. case 2 /* FRAMING */:
  110658. this._observablesManager && this._observablesManager.onModelLoadedObservable.add(function (model) {
  110659. if (config.zoomOnBoundingInfo) {
  110660. behavior.zoomOnMeshHierarchy(model.rootMesh);
  110661. }
  110662. });
  110663. break;
  110664. }
  110665. };
  110666. return SceneManager;
  110667. }());
  110668. exports.SceneManager = SceneManager;
  110669. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2NlbmVNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL21hbmFnZXJzL3NjZW5lTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUErakI7QUFDL2pCLGtEQUFtUjtBQUNuUixvREFBK0Q7QUFDL0Qsb0NBQWtEO0FBRWxELGlEQUFnRDtBQUNoRCx5Q0FBZ0U7QUFnQmhFO0lBc0ZJLHNCQUFvQixPQUFlLEVBQVUsdUJBQStDLEVBQVUsbUJBQXdDO1FBQTlJLGlCQXlFQztRQXpFbUIsWUFBTyxHQUFQLE9BQU8sQ0FBUTtRQUFVLDRCQUF1QixHQUF2Qix1QkFBdUIsQ0FBd0I7UUFBVSx3QkFBbUIsR0FBbkIsbUJBQW1CLENBQXFCO1FBakN0SSw4QkFBeUIsR0FBWSxJQUFJLENBQUM7UUFpQmpDLFdBQU0sR0FBRyxrQkFBTSxDQUFDLEtBQUssRUFBRSxDQUFDO1FBRWpDLHVCQUFrQixHQUFZLEtBQUssQ0FBQztRQXVIcEMsb0JBQWUsR0FBWSxJQUFJLENBQUM7UUFrQ2hDLG1CQUFjLEdBQVksSUFBSSxDQUFDO1FBZ0IvQix5QkFBb0IsR0FBRyxJQUFJLENBQUM7UUF5QjVCLHFDQUFnQyxHQUFZLEtBQUssQ0FBQztRQTRGbEQseUJBQW9CLEdBQXdCLEVBQUUsQ0FBQztRQThGL0MseUNBQW9DLEdBQVksSUFBSSxDQUFDO1FBMkM3RCxrQ0FBa0M7UUFDMUIsa0JBQWEsR0FBWSxLQUFLLENBQUM7UUFvQnZDLGtDQUFrQztRQUMxQixpQkFBWSxHQUFZLEtBQUssQ0FBQztR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Q1ksb0NBQVkifQ==
  110670. /***/ }),
  110671. /* 23 */
  110672. /***/ (function(module, exports, __webpack_require__) {
  110673. "use strict";
  110674. Object.defineProperty(exports, "__esModule", { value: true });
  110675. /**
  110676. * The GroupModelAnimation is an implementation of the IModelAnimation interface using BABYLON's
  110677. * native GroupAnimation class.
  110678. */
  110679. var GroupModelAnimation = /** @class */ (function () {
  110680. /**
  110681. * Create a new GroupModelAnimation object using an AnimationGroup object
  110682. * @param _animationGroup The aniamtion group to base the class on
  110683. */
  110684. function GroupModelAnimation(_animationGroup) {
  110685. var _this = this;
  110686. this._animationGroup = _animationGroup;
  110687. this._state = 0 /* INIT */;
  110688. this._playMode = 1 /* LOOP */;
  110689. this._animationGroup.onAnimationEndObservable.add(function () {
  110690. _this.stop();
  110691. _this._state = 4 /* ENDED */;
  110692. });
  110693. }
  110694. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  110695. /**
  110696. * Get the animation's name
  110697. */
  110698. get: function () {
  110699. return this._animationGroup.name;
  110700. },
  110701. enumerable: true,
  110702. configurable: true
  110703. });
  110704. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  110705. /**
  110706. * Get the current animation's state
  110707. */
  110708. get: function () {
  110709. return this._state;
  110710. },
  110711. enumerable: true,
  110712. configurable: true
  110713. });
  110714. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  110715. /**
  110716. * Gets the speed ratio to use for all animations
  110717. */
  110718. get: function () {
  110719. return this._animationGroup.speedRatio;
  110720. },
  110721. /**
  110722. * Sets the speed ratio to use for all animations
  110723. */
  110724. set: function (value) {
  110725. this._animationGroup.speedRatio = value;
  110726. },
  110727. enumerable: true,
  110728. configurable: true
  110729. });
  110730. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  110731. /**
  110732. * Get the max numbers of frame available in the animation group
  110733. *
  110734. * In correlation to an arry, this would be ".length"
  110735. */
  110736. get: function () {
  110737. return this._animationGroup.to - this._animationGroup.from;
  110738. },
  110739. enumerable: true,
  110740. configurable: true
  110741. });
  110742. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  110743. /**
  110744. * Get the current frame playing right now.
  110745. * This can be used to poll the frame currently playing (and, for exmaple, display a progress bar with the data)
  110746. *
  110747. * In correlation to an array, this would be the current index
  110748. */
  110749. get: function () {
  110750. if (this._animationGroup.targetedAnimations[0] && this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0]) {
  110751. return this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0].currentFrame - this._animationGroup.from;
  110752. }
  110753. else {
  110754. return 0;
  110755. }
  110756. },
  110757. enumerable: true,
  110758. configurable: true
  110759. });
  110760. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  110761. /**
  110762. * Get the FPS value of this animation
  110763. */
  110764. get: function () {
  110765. // get the first currentFrame found
  110766. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  110767. var animatable = this._animationGroup.animatables[i];
  110768. var animations = animatable.getAnimations();
  110769. if (!animations || !animations.length) {
  110770. continue;
  110771. }
  110772. for (var idx = 0; idx < animations.length; ++idx) {
  110773. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  110774. return animations[idx].animation.framePerSecond;
  110775. }
  110776. }
  110777. }
  110778. return 0;
  110779. },
  110780. enumerable: true,
  110781. configurable: true
  110782. });
  110783. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  110784. /**
  110785. * What is the animation'S play mode (looping or played once)
  110786. */
  110787. get: function () {
  110788. return this._playMode;
  110789. },
  110790. /**
  110791. * Set the play mode.
  110792. * If the animation is played, it will continue playing at least once more, depending on the new play mode set.
  110793. * If the animation is not set, the will be initialized and will wait for the user to start playing it.
  110794. */
  110795. set: function (value) {
  110796. if (value === this._playMode) {
  110797. return;
  110798. }
  110799. this._playMode = value;
  110800. if (this.state === 1 /* PLAYING */) {
  110801. this._animationGroup.play(this._playMode === 1 /* LOOP */);
  110802. }
  110803. else {
  110804. this._animationGroup.reset();
  110805. this._state = 0 /* INIT */;
  110806. }
  110807. },
  110808. enumerable: true,
  110809. configurable: true
  110810. });
  110811. /**
  110812. * Reset the animation group
  110813. */
  110814. GroupModelAnimation.prototype.reset = function () {
  110815. this._animationGroup.reset();
  110816. };
  110817. /**
  110818. * Restart the animation group
  110819. */
  110820. GroupModelAnimation.prototype.restart = function () {
  110821. if (this.state === 2 /* PAUSED */)
  110822. this._animationGroup.restart();
  110823. else
  110824. this.start();
  110825. };
  110826. /**
  110827. *
  110828. * @param frameNumber Go to a specific frame in the animation
  110829. */
  110830. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  110831. this._animationGroup.goToFrame(frameNumber + this._animationGroup.from);
  110832. };
  110833. /**
  110834. * Start playing the animation.
  110835. */
  110836. GroupModelAnimation.prototype.start = function () {
  110837. this._animationGroup.start(this.playMode === 1 /* LOOP */, this.speedRatio);
  110838. if (this._animationGroup.isStarted) {
  110839. this._state = 1 /* PLAYING */;
  110840. }
  110841. };
  110842. /**
  110843. * Pause the animation
  110844. */
  110845. GroupModelAnimation.prototype.pause = function () {
  110846. this._animationGroup.pause();
  110847. this._state = 2 /* PAUSED */;
  110848. };
  110849. /**
  110850. * Stop the animation.
  110851. * This will fail silently if the animation group is already stopped.
  110852. */
  110853. GroupModelAnimation.prototype.stop = function () {
  110854. this._animationGroup.stop();
  110855. if (!this._animationGroup.isStarted) {
  110856. this._state = 3 /* STOPPED */;
  110857. }
  110858. };
  110859. /**
  110860. * Dispose this animation object.
  110861. */
  110862. GroupModelAnimation.prototype.dispose = function () {
  110863. this._animationGroup.dispose();
  110864. };
  110865. return GroupModelAnimation;
  110866. }());
  110867. exports.GroupModelAnimation = GroupModelAnimation;
  110868. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kZWxBbmltYXRpb24uanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbW9kZWwvbW9kZWxBbmltYXRpb24udHMiXSwibmFtZXMiOltdL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. /***/ }),
  110870. /* 24 */
  110871. /***/ (function(module, exports, __webpack_require__) {
  110872. "use strict";
  110873. Object.defineProperty(exports, "__esModule", { value: true });
  110874. var environmentSerializer_1 = __webpack_require__(25);
  110875. var babylonjs_1 = __webpack_require__(0);
  110876. var texture_1 = __webpack_require__(12);
  110877. /**
  110878. * The ViewerLabs class will hold functions that are not (!) backwards compatible.
  110879. * The APIs in all labs-related classes and configuration might change.
  110880. * Once stable, lab features will be moved to the publis API and configuration object.
  110881. */
  110882. var ViewerLabs = /** @class */ (function () {
  110883. function ViewerLabs(_scene) {
  110884. this._scene = _scene;
  110885. this.environment = {
  110886. //irradiance
  110887. irradiancePolynomialCoefficients: {
  110888. x: new babylonjs_1.Vector3(0, 0, 0),
  110889. y: new babylonjs_1.Vector3(0, 0, 0),
  110890. z: new babylonjs_1.Vector3(0, 0, 0),
  110891. xx: new babylonjs_1.Vector3(0, 0, 0),
  110892. yy: new babylonjs_1.Vector3(0, 0, 0),
  110893. zz: new babylonjs_1.Vector3(0, 0, 0),
  110894. yz: new babylonjs_1.Vector3(0, 0, 0),
  110895. zx: new babylonjs_1.Vector3(0, 0, 0),
  110896. xy: new babylonjs_1.Vector3(0, 0, 0)
  110897. },
  110898. textureIntensityScale: 1.0
  110899. };
  110900. }
  110901. ViewerLabs.prototype.loadEnvironment = function (data, onSuccess, onProgress, onError) {
  110902. var _this = this;
  110903. //@! todo: should loadEnvironment cancel any currently loading environments?
  110904. if (data instanceof ArrayBuffer) {
  110905. this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(data);
  110906. if (onSuccess)
  110907. onSuccess(this.environment);
  110908. }
  110909. else if (typeof data === 'string') {
  110910. var url = this.getAssetUrl(data);
  110911. this._scene._loadFile(url, function (arrayBuffer) {
  110912. _this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(arrayBuffer);
  110913. if (onSuccess)
  110914. onSuccess(_this.environment);
  110915. }, function (progressEvent) { if (onProgress)
  110916. onProgress(progressEvent.loaded, progressEvent.total); }, false, true, function (r, e) {
  110917. if (onError) {
  110918. onError(e);
  110919. }
  110920. });
  110921. }
  110922. else {
  110923. //data assumed to be PBREnvironment object
  110924. this.environment = data;
  110925. if (onSuccess)
  110926. onSuccess(data);
  110927. }
  110928. };
  110929. /**
  110930. * Applies an `EnvironmentMapConfiguration` to the scene
  110931. * @param environmentMapConfiguration Environment map configuration to apply
  110932. */
  110933. ViewerLabs.prototype.applyEnvironmentMapConfiguration = function (rotationY) {
  110934. if (!this.environment)
  110935. return;
  110936. //set orientation
  110937. var rotatquatRotationionY = babylonjs_1.Quaternion.RotationAxis(babylonjs_1.Axis.Y, rotationY || 0);
  110938. // Add env texture to the scene.
  110939. if (this.environment.specularTexture) {
  110940. // IE crashes when disposing the old texture and setting a new one
  110941. if (!this._scene.environmentTexture) {
  110942. this._scene.environmentTexture = texture_1.TextureUtils.GetBabylonCubeTexture(this._scene, this.environment.specularTexture, false, true);
  110943. }
  110944. if (this._scene.environmentTexture) {
  110945. this._scene.environmentTexture.level = this.environment.textureIntensityScale;
  110946. this._scene.environmentTexture.invertZ = true;
  110947. this._scene.environmentTexture.lodLevelInAlpha = true;
  110948. var poly = this._scene.environmentTexture.sphericalPolynomial || new babylonjs_1.SphericalPolynomial();
  110949. poly.x = this.environment.irradiancePolynomialCoefficients.x;
  110950. poly.y = this.environment.irradiancePolynomialCoefficients.y;
  110951. poly.z = this.environment.irradiancePolynomialCoefficients.z;
  110952. poly.xx = this.environment.irradiancePolynomialCoefficients.xx;
  110953. poly.xy = this.environment.irradiancePolynomialCoefficients.xy;
  110954. poly.yy = this.environment.irradiancePolynomialCoefficients.yy;
  110955. poly.yz = this.environment.irradiancePolynomialCoefficients.yz;
  110956. poly.zx = this.environment.irradiancePolynomialCoefficients.zx;
  110957. poly.zz = this.environment.irradiancePolynomialCoefficients.zz;
  110958. this._scene.environmentTexture.sphericalPolynomial = poly;
  110959. //set orientation
  110960. babylonjs_1.Matrix.FromQuaternionToRef(rotatquatRotationionY, this._scene.environmentTexture.getReflectionTextureMatrix());
  110961. }
  110962. }
  110963. };
  110964. /**
  110965. * Get an environment asset url by using the configuration if the path is not absolute.
  110966. * @param url Asset url
  110967. * @returns The Asset url using the `environmentAssetsRootURL` if the url is not an absolute path.
  110968. */
  110969. ViewerLabs.prototype.getAssetUrl = function (url) {
  110970. var returnUrl = url;
  110971. if (url && url.toLowerCase().indexOf("//") === -1) {
  110972. if (!this.assetsRootURL) {
  110973. // Tools.Warn("Please, specify the root url of your assets before loading the configuration (labs.environmentAssetsRootURL) or disable the background through the viewer options.");
  110974. return url;
  110975. }
  110976. returnUrl = this.assetsRootURL + returnUrl;
  110977. }
  110978. return returnUrl;
  110979. };
  110980. ViewerLabs.prototype.rotateShadowLight = function (shadowLight, amount, point, axis, target) {
  110981. if (point === void 0) { point = babylonjs_1.Vector3.Zero(); }
  110982. if (axis === void 0) { axis = babylonjs_1.Axis.Y; }
  110983. if (target === void 0) { target = babylonjs_1.Vector3.Zero(); }
  110984. axis.normalize();
  110985. point.subtractToRef(shadowLight.position, babylonjs_1.Tmp.Vector3[0]);
  110986. babylonjs_1.Matrix.TranslationToRef(babylonjs_1.Tmp.Vector3[0].x, babylonjs_1.Tmp.Vector3[0].y, babylonjs_1.Tmp.Vector3[0].z, babylonjs_1.Tmp.Matrix[0]);
  110987. babylonjs_1.Tmp.Matrix[0].invertToRef(babylonjs_1.Tmp.Matrix[2]);
  110988. babylonjs_1.Matrix.RotationAxisToRef(axis, amount, babylonjs_1.Tmp.Matrix[1]);
  110989. babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[1], babylonjs_1.Tmp.Matrix[2]);
  110990. babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[0], babylonjs_1.Tmp.Matrix[2]);
  110991. babylonjs_1.Tmp.Matrix[2].decompose(babylonjs_1.Tmp.Vector3[0], babylonjs_1.Tmp.Quaternion[0], babylonjs_1.Tmp.Vector3[1]);
  110992. shadowLight.position.addInPlace(babylonjs_1.Tmp.Vector3[1]);
  110993. shadowLight.setDirectionToTarget(target);
  110994. };
  110995. return ViewerLabs;
  110996. }());
  110997. exports.ViewerLabs = ViewerLabs;
  110998. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTGFicy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9sYWJzL3ZpZXdlckxhYnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpRUFBa0Y7QUFFbEYsdUNBQW1IO0FBQ25ILHFDQUF5QztBQUV6Qzs7OztHQUlHO0FBQ0g7SUFFSSxvQkFBb0IsTUFBYTtRQUFiLFdBQU0sR0FBTixNQUFNLENBQU87UUFHMUIsZ0JBQVcsR0FBbUI7WUFDakMsWUFBWTtZQUNaLGdDQUFnQyxFQUFFO2dCQUM5QixDQUFDLEVBQUUsSUFBSSxtQkFBTyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO2dCQUN2QixDQUFDLEVBQUUsSUFBSSxtQkFBTyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO2dCQUN2QixDQUFDLEVBQUUsSUFBSSxtQkFBTyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO2dCQUN2QixFQUFFLEVBQUUsSUFBSSxtQkFBTyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO2dCQUN4QixFQUFFLEVBQUUsSUFBSSxtQkFBTyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO2dCQUN4QixFQUFFLEVBQUUsSUFBSSxtQkFBTyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO2dCQUN4QixFQUFFLEVBQUUsSUFBSSxtQkFBTyx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0FBQyxDQUFDLENBQUM7UUFFMUQsZUFBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQyxTQUFTLENBQUMsZUFBRyxDQUFDLE9BQU8sQ0FBQyxDQUFDLENBQUMsRUFBRSxlQUFHLENBQUMsVUFBVSxDQUFDLENBQUMsQ0FBQyxFQUFFLGVBQUcsQ0FBQyxPQUFPLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQztRQUUzRSxXQUFXLENBQUMsUUFBUSxDQUFDLFVBQVUsQ0FBQyxlQUFHLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFFaEQsV0FBVyxDQUFDLG9CQUFvQixDQUFDLE1BQU0sQ0FBQyxDQUFDO0lBQzdDLENBQUM7SUFFTCxpQkFBQztBQUFELENBQUMsQUFySkQsSUFxSkM7QUFySlksZ0NBQVUifQ==
  110999. /***/ }),
  111000. /* 25 */
  111001. /***/ (function(module, exports, __webpack_require__) {
  111002. "use strict";
  111003. Object.defineProperty(exports, "__esModule", { value: true });
  111004. var babylonjs_1 = __webpack_require__(0);
  111005. var texture_1 = __webpack_require__(12);
  111006. /**
  111007. * A static class proving methods to aid parsing Spectre environment files
  111008. */
  111009. var EnvironmentDeserializer = /** @class */ (function () {
  111010. function EnvironmentDeserializer() {
  111011. }
  111012. /**
  111013. * Parses an arraybuffer into a new PBREnvironment object
  111014. * @param arrayBuffer The arraybuffer of the Spectre environment file
  111015. * @return a PBREnvironment object
  111016. */
  111017. EnvironmentDeserializer.Parse = function (arrayBuffer) {
  111018. var environment = {
  111019. //irradiance
  111020. irradiancePolynomialCoefficients: {
  111021. x: new babylonjs_1.Vector3(0, 0, 0),
  111022. y: new babylonjs_1.Vector3(0, 0, 0),
  111023. z: new babylonjs_1.Vector3(0, 0, 0),
  111024. xx: new babylonjs_1.Vector3(0, 0, 0),
  111025. yy: new babylonjs_1.Vector3(0, 0, 0),
  111026. zz: new babylonjs_1.Vector3(0, 0, 0),
  111027. yz: new babylonjs_1.Vector3(0, 0, 0),
  111028. zx: new babylonjs_1.Vector3(0, 0, 0),
  111029. xy: new babylonjs_1.Vector3(0, 0, 0)
  111030. },
  111031. //specular
  111032. textureIntensityScale: 1.0,
  111033. };
  111034. //read .env
  111035. var littleEndian = false;
  111036. var magicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  111037. var dataView = new DataView(arrayBuffer);
  111038. var pos = 0;
  111039. for (var i = 0; i < magicBytes.length; i++) {
  111040. if (dataView.getUint8(pos++) !== magicBytes[i]) {
  111041. babylonjs_1.Tools.Error('Not a Spectre environment map');
  111042. }
  111043. }
  111044. var version = dataView.getUint16(pos, littleEndian);
  111045. pos += 2;
  111046. if (version !== 1) {
  111047. babylonjs_1.Tools.Warn('Unsupported Spectre environment map version "' + version + '"');
  111048. }
  111049. //read json descriptor - collect characters up to null terminator
  111050. var descriptorString = '';
  111051. var charCode = 0x00;
  111052. while ((charCode = dataView.getUint8(pos++))) {
  111053. descriptorString += String.fromCharCode(charCode);
  111054. }
  111055. var descriptor = JSON.parse(descriptorString);
  111056. var payloadPos = pos;
  111057. //irradiance
  111058. switch (descriptor.irradiance.type) {
  111059. case 'irradiance_sh_coefficients_9':
  111060. //irradiance
  111061. var harmonics = descriptor.irradiance;
  111062. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance(harmonics);
  111063. //harmonics now represent radiance
  111064. EnvironmentDeserializer._ConvertSHToSP(harmonics, environment.irradiancePolynomialCoefficients);
  111065. break;
  111066. default:
  111067. babylonjs_1.Tools.Error('Unhandled MapType descriptor.irradiance.type (' + descriptor.irradiance.type + ')');
  111068. }
  111069. //specular
  111070. switch (descriptor.specular.type) {
  111071. case 'cubemap_faces':
  111072. var specularDescriptor = descriptor.specular;
  111073. var specularTexture = environment.specularTexture = new texture_1.TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */);
  111074. environment.textureIntensityScale = specularDescriptor.multiplier != null ? specularDescriptor.multiplier : 1.0;
  111075. var mipmaps = specularDescriptor.mipmaps;
  111076. var imageType = specularDescriptor.imageType;
  111077. for (var l = 0; l < mipmaps.length; l++) {
  111078. var faceRanges = mipmaps[l];
  111079. specularTexture.source[l] = [];
  111080. for (var i = 0; i < 6; i++) {
  111081. var range = faceRanges[i];
  111082. var bytes = new Uint8Array(arrayBuffer, payloadPos + range.pos, range.length);
  111083. switch (imageType) {
  111084. case 'png':
  111085. //construct image element from bytes
  111086. var image = new Image();
  111087. var src = URL.createObjectURL(new Blob([bytes], { type: 'image/png' }));
  111088. image.src = src;
  111089. specularTexture.source[l][i] = image;
  111090. break;
  111091. default:
  111092. babylonjs_1.Tools.Error('Unhandled ImageType descriptor.specular.imageType (' + imageType + ')');
  111093. }
  111094. }
  111095. }
  111096. break;
  111097. default:
  111098. babylonjs_1.Tools.Error('Unhandled MapType descriptor.specular.type (' + descriptor.specular.type + ')');
  111099. }
  111100. return environment;
  111101. };
  111102. /**
  111103. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  111104. * L = (1/pi) * E * rho
  111105. *
  111106. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  111107. * @param harmonics Spherical harmonic coefficients (9)
  111108. */
  111109. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  111110. EnvironmentDeserializer._ScaleSH(harmonics, 1 / Math.PI);
  111111. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  111112. // (The pixel shader must apply albedo after texture fetches, etc).
  111113. };
  111114. /**
  111115. * Convert spherical harmonics to spherical polynomial coefficients
  111116. * @param harmonics Spherical harmonic coefficients (9)
  111117. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  111118. */
  111119. EnvironmentDeserializer._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  111120. var rPi = 1 / Math.PI;
  111121. //x
  111122. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  111123. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  111124. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  111125. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  111126. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  111127. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  111128. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  111129. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  111130. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  111131. //xx
  111132. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  111133. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  111134. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  111135. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  111136. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  111137. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  111138. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  111139. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  111140. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  111141. //yz
  111142. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  111143. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  111144. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  111145. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  111146. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  111147. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  111148. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  111149. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  111150. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  111151. };
  111152. /**
  111153. * Multiplies harmonic coefficients in place
  111154. * @param harmonics Spherical harmonic coefficients (9)
  111155. * @param scaleFactor Value to multiply by
  111156. */
  111157. EnvironmentDeserializer._ScaleSH = function (harmonics, scaleFactor) {
  111158. harmonics.l00[0] *= scaleFactor;
  111159. harmonics.l00[1] *= scaleFactor;
  111160. harmonics.l00[2] *= scaleFactor;
  111161. harmonics.l1_1[0] *= scaleFactor;
  111162. harmonics.l1_1[1] *= scaleFactor;
  111163. harmonics.l1_1[2] *= scaleFactor;
  111164. harmonics.l10[0] *= scaleFactor;
  111165. harmonics.l10[1] *= scaleFactor;
  111166. harmonics.l10[2] *= scaleFactor;
  111167. harmonics.l11[0] *= scaleFactor;
  111168. harmonics.l11[1] *= scaleFactor;
  111169. harmonics.l11[2] *= scaleFactor;
  111170. harmonics.l2_2[0] *= scaleFactor;
  111171. harmonics.l2_2[1] *= scaleFactor;
  111172. harmonics.l2_2[2] *= scaleFactor;
  111173. harmonics.l2_1[0] *= scaleFactor;
  111174. harmonics.l2_1[1] *= scaleFactor;
  111175. harmonics.l2_1[2] *= scaleFactor;
  111176. harmonics.l20[0] *= scaleFactor;
  111177. harmonics.l20[1] *= scaleFactor;
  111178. harmonics.l20[2] *= scaleFactor;
  111179. harmonics.l21[0] *= scaleFactor;
  111180. harmonics.l21[1] *= scaleFactor;
  111181. harmonics.l21[2] *= scaleFactor;
  111182. harmonics.l22[0] *= scaleFactor;
  111183. harmonics.l22[1] *= scaleFactor;
  111184. harmonics.l22[2] *= scaleFactor;
  111185. };
  111186. return EnvironmentDeserializer;
  111187. }());
  111188. exports.EnvironmentDeserializer = EnvironmentDeserializer;
  111189. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW52aXJvbm1lbnRTZXJpYWxpemVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2xhYnMvZW52aXJvbm1lbnRTZXJpYWxpemVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQTJDO0FBQzNDLHFDQUFnRTtBQW1IaEU7O0dBRUc7QUFDSDtJQUFBO0lBcU5BLENBQUM7SUFuTkc7Ozs7T0FJRztJQUNXLDZCQUFLLEdBQW5CLFVBQW9CLFdBQXdCO1FBQ3hDLElBQUksV0FBVyxHQUFtQjtZQUM5QixZQUFZO1lBQ1osZ0NBQWdDLEVBQUU7Z0JBQzlCLENBQUMsRUFBRSxJQUFJLG1CQUFPLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUM7Z0JBQ3ZCLENBQUMsRUFBRSxJQUFJLG1CQUFPLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUM7Z0JBQ3ZCLENBQUMsRUFBRSxJQUFJLG1CQUFPLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUM7Z0JBQ3ZCLEVBQUUsRUFBRSxJQUFJLG1CQUFPLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUM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FDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztJQUNwQyxDQUFDO0lBQ0wsOEJBQUM7QUFBRCxDQUFDLEFBck5ELElBcU5DO0FBck5ZLDBEQUF1QiJ9
  111190. /***/ }),
  111191. /* 26 */
  111192. /***/ (function(module, exports, __webpack_require__) {
  111193. "use strict";
  111194. Object.defineProperty(exports, "__esModule", { value: true });
  111195. var extended_1 = __webpack_require__(27);
  111196. var cache = {};
  111197. /**
  111198. *
  111199. * @param name the name of the custom optimizer configuration
  111200. * @param upgrade set to true if you want to upgrade optimizer and false if you want to degrade
  111201. */
  111202. function getCustomOptimizerByName(name, upgrade) {
  111203. if (!cache[name]) {
  111204. switch (name) {
  111205. case 'extended':
  111206. if (upgrade) {
  111207. return extended_1.extendedUpgrade;
  111208. }
  111209. else {
  111210. return extended_1.extendedDegrade;
  111211. }
  111212. }
  111213. }
  111214. return cache[name];
  111215. }
  111216. exports.getCustomOptimizerByName = getCustomOptimizerByName;
  111217. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvb3B0aW1pemVyL2N1c3RvbS9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUE4RDtBQUc5RCxJQUFNLEtBQUssR0FBK0QsRUFBRSxDQUFDO0FBRTdFOzs7O0dBSUc7QUFDSCxrQ0FBeUMsSUFBWSxFQUFFLE9BQWlCO0lBQ3BFLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLEVBQUU7UUFDZCxRQUFRLElBQUksRUFBRTtZQUNWLEtBQUssVUFBVTtnQkFDWCxJQUFJLE9BQU8sRUFBRTtvQkFDVCxPQUFPLDBCQUFlLENBQUM7aUJBQzFCO3FCQUNJO29CQUNELE9BQU8sMEJBQWUsQ0FBQztpQkFDMUI7U0FDUjtLQUNKO0lBRUQsT0FBTyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUM7QUFDdkIsQ0FBQztBQWRELDREQWNDIn0=
  111218. /***/ }),
  111219. /* 27 */
  111220. /***/ (function(module, exports, __webpack_require__) {
  111221. "use strict";
  111222. Object.defineProperty(exports, "__esModule", { value: true });
  111223. var babylonjs_1 = __webpack_require__(0);
  111224. /**
  111225. * A custom upgrade-oriented function configuration for the scene optimizer.
  111226. *
  111227. * @param viewer the viewer to optimize
  111228. */
  111229. function extendedUpgrade(sceneManager) {
  111230. var defaultPipeline = sceneManager.defaultRenderingPipeline;
  111231. // if (!this.Scene.BackgroundHelper) {
  111232. // this.Scene.EngineScene.autoClear = false;
  111233. // this.Scene.BackgroundHelper = true;
  111234. // Would require a dedicated clear color;
  111235. // return false;
  111236. // }
  111237. if (sceneManager.scene.getEngine().getHardwareScalingLevel() > 1) {
  111238. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() - 0.25, 0, 1);
  111239. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  111240. return false;
  111241. }
  111242. if (!sceneManager.scene.postProcessesEnabled) {
  111243. sceneManager.scene.postProcessesEnabled = true;
  111244. return false;
  111245. }
  111246. if (!sceneManager.groundEnabled) {
  111247. sceneManager.groundEnabled = true;
  111248. return false;
  111249. }
  111250. if (defaultPipeline && !sceneManager.fxaaEnabled) {
  111251. sceneManager.fxaaEnabled = true;
  111252. return false;
  111253. }
  111254. var hardwareScalingLevel = Math.max(1 / 2, 1 / (window.devicePixelRatio || 2));
  111255. if (sceneManager.scene.getEngine().getHardwareScalingLevel() > hardwareScalingLevel) {
  111256. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() - 0.25, 0, hardwareScalingLevel);
  111257. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  111258. return false;
  111259. }
  111260. if (!sceneManager.processShadows) {
  111261. sceneManager.processShadows = true;
  111262. return false;
  111263. }
  111264. if (defaultPipeline && !sceneManager.bloomEnabled) {
  111265. sceneManager.bloomEnabled = true;
  111266. return false;
  111267. }
  111268. if (!sceneManager.groundMirrorEnabled) {
  111269. sceneManager.groundMirrorEnabled = true;
  111270. return false;
  111271. }
  111272. return true;
  111273. }
  111274. exports.extendedUpgrade = extendedUpgrade;
  111275. /**
  111276. * A custom degrade-oriented function configuration for the scene optimizer.
  111277. *
  111278. * @param viewer the viewer to optimize
  111279. */
  111280. function extendedDegrade(sceneManager) {
  111281. var defaultPipeline = sceneManager.defaultRenderingPipeline;
  111282. if (sceneManager.groundMirrorEnabled) {
  111283. sceneManager.groundMirrorEnabled = false;
  111284. return false;
  111285. }
  111286. if (defaultPipeline && sceneManager.bloomEnabled) {
  111287. sceneManager.bloomEnabled = false;
  111288. return false;
  111289. }
  111290. if (sceneManager.processShadows) {
  111291. sceneManager.processShadows = false;
  111292. return false;
  111293. }
  111294. if (sceneManager.scene.getEngine().getHardwareScalingLevel() < 1) {
  111295. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() + 0.25, 0, 1);
  111296. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  111297. return false;
  111298. }
  111299. if (defaultPipeline && sceneManager.fxaaEnabled) {
  111300. sceneManager.fxaaEnabled = false;
  111301. return false;
  111302. }
  111303. if (sceneManager.groundEnabled) {
  111304. sceneManager.groundEnabled = false;
  111305. return false;
  111306. }
  111307. if (sceneManager.scene.postProcessesEnabled) {
  111308. sceneManager.scene.postProcessesEnabled = false;
  111309. return false;
  111310. }
  111311. if (sceneManager.scene.getEngine().getHardwareScalingLevel() < 1.25) {
  111312. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() + 0.25, 0, 1.25);
  111313. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  111314. return false;
  111315. }
  111316. // if (this.Scene.BackgroundHelper) {
  111317. // this.Scene.EngineScene.autoClear = true;
  111318. // this.Scene.BackgroundHelper = false;
  111319. // Would require a dedicated clear color;
  111320. // return false;
  111321. // }
  111322. return true;
  111323. }
  111324. exports.extendedDegrade = extendedDegrade;
  111325. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvb3B0aW1pemVyL2N1c3RvbS9leHRlbmRlZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUFvRTtBQUdwRTs7OztHQUlHO0FBQ0gseUJBQWdDLFlBQTBCO0lBQ3RELElBQUksZUFBZSxHQUE2QixZQUFZLENBQUMsd0JBQXdCLENBQUM7SUFDdEYsc0NBQXNDO0lBQ3RDLDZDQUE2QztJQUM3QyxzQ0FBc0M7SUFDdEMseUNBQXlDO0lBQ3pDLGdCQUFnQjtJQUNoQixJQUFJO0lBQ0osSUFBSSxZQUFZLENBQUMsS0FBSyxDQUFDLFNBQVMsRUFBRSxDQUFDLHVCQUF1QixFQUFFLEdBQUcsQ0FBQyxFQUFFO1FBQzlELElBQUksT0FBTyxHQUFHLGtCQUFNLENBQUMsS0FBSyxDQUFDLFlBQVksQ0FBQyxLQUFLLENBQUMsU0FBUyxFQUFFLENBQUMsdUJBQXVCLEVBQUUsR0FBRyxJQUFJLEVBQUUsQ0FBQyxFQUFFLENBQUMs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LENBQUMsRUFBRSxJQUFJLENBQUMsQ0FBQztRQUNyRyxZQUFZLENBQUMsS0FBSyxDQUFDLFNBQVMsRUFBRSxDQUFDLHVCQUF1QixDQUFDLE9BQU8sQ0FBQyxDQUFDO1FBQ2hFLE9BQU8sS0FBSyxDQUFDO0tBQ2hCO0lBQ0QscUNBQXFDO0lBQ3JDLDRDQUE0QztJQUM1Qyx1Q0FBdUM7SUFDdkMseUNBQXlDO0lBQ3pDLGdCQUFnQjtJQUNoQixJQUFJO0lBQ0osT0FBTyxJQUFJLENBQUM7QUFDaEIsQ0FBQztBQTVDRCwwQ0E0Q0MifQ==
  111326. /***/ }),
  111327. /* 28 */
  111328. /***/ (function(module, exports, __webpack_require__) {
  111329. "use strict";
  111330. Object.defineProperty(exports, "__esModule", { value: true });
  111331. var mappers_1 = __webpack_require__(3);
  111332. var types_1 = __webpack_require__(29);
  111333. var configurationCompatibility_1 = __webpack_require__(53);
  111334. var _1 = __webpack_require__(1);
  111335. var babylonjs_1 = __webpack_require__(0);
  111336. /**
  111337. * The configuration loader will load the configuration object from any source and will use the defined mapper to
  111338. * parse the object and return a conform ViewerConfiguration.
  111339. * It is a private member of the scene.
  111340. */
  111341. var ConfigurationLoader = /** @class */ (function () {
  111342. function ConfigurationLoader(_enableCache) {
  111343. if (_enableCache === void 0) { _enableCache = false; }
  111344. this._enableCache = _enableCache;
  111345. this._configurationCache = {};
  111346. this._loadRequests = [];
  111347. }
  111348. /**
  111349. * load a configuration object that is defined in the initial configuration provided.
  111350. * The viewer configuration can extend different types of configuration objects and have an extra configuration defined.
  111351. *
  111352. * @param initConfig the initial configuration that has the definitions of further configuration to load.
  111353. * @param callback an optional callback that will be called sync, if noconfiguration needs to be loaded or configuration is payload-only
  111354. * @returns A promise that delivers the extended viewer configuration, when done.
  111355. */
  111356. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  111357. var _this = this;
  111358. if (initConfig === void 0) { initConfig = {}; }
  111359. var loadedConfig = _1.deepmerge({}, initConfig);
  111360. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  111361. if (loadedConfig.configuration) {
  111362. var mapperType_1 = "json";
  111363. return Promise.resolve().then(function () {
  111364. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  111365. // a file to load
  111366. var url = '';
  111367. if (typeof loadedConfig.configuration === "string") {
  111368. url = loadedConfig.configuration;
  111369. }
  111370. // if configuration is an object
  111371. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  111372. url = loadedConfig.configuration.url;
  111373. var type = loadedConfig.configuration.mapper;
  111374. // empty string?
  111375. if (!type) {
  111376. // load mapper type from filename / url
  111377. type = loadedConfig.configuration.url.split('.').pop();
  111378. }
  111379. mapperType_1 = type || mapperType_1;
  111380. }
  111381. return _this._loadFile(url);
  111382. }
  111383. else {
  111384. if (typeof loadedConfig.configuration === "object") {
  111385. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  111386. return loadedConfig.configuration.payload || {};
  111387. }
  111388. return {};
  111389. }
  111390. }).then(function (data) {
  111391. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  111392. var parsed = _1.deepmerge(mapper.map(data), loadedConfig);
  111393. var merged = _1.deepmerge(extendedConfiguration, parsed);
  111394. configurationCompatibility_1.processConfigurationCompatibility(merged);
  111395. if (callback)
  111396. callback(merged);
  111397. return merged;
  111398. });
  111399. }
  111400. else {
  111401. loadedConfig = _1.deepmerge(extendedConfiguration, loadedConfig);
  111402. configurationCompatibility_1.processConfigurationCompatibility(loadedConfig);
  111403. if (callback)
  111404. callback(loadedConfig);
  111405. return Promise.resolve(loadedConfig);
  111406. }
  111407. };
  111408. /**
  111409. * Dispose the configuration loader. This will cancel file requests, if active.
  111410. */
  111411. ConfigurationLoader.prototype.dispose = function () {
  111412. this._loadRequests.forEach(function (request) {
  111413. request.abort();
  111414. });
  111415. this._loadRequests.length = 0;
  111416. };
  111417. ConfigurationLoader.prototype._loadFile = function (url) {
  111418. var _this = this;
  111419. var cacheReference = this._configurationCache;
  111420. if (this._enableCache && cacheReference[url]) {
  111421. return Promise.resolve(cacheReference[url]);
  111422. }
  111423. return new Promise(function (resolve, reject) {
  111424. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  111425. var idx = _this._loadRequests.indexOf(fileRequest);
  111426. if (idx !== -1)
  111427. _this._loadRequests.splice(idx, 1);
  111428. if (_this._enableCache)
  111429. cacheReference[url] = result;
  111430. resolve(result);
  111431. }, undefined, undefined, false, function (request, error) {
  111432. var idx = _this._loadRequests.indexOf(fileRequest);
  111433. if (idx !== -1)
  111434. _this._loadRequests.splice(idx, 1);
  111435. reject(error);
  111436. });
  111437. _this._loadRequests.push(fileRequest);
  111438. });
  111439. };
  111440. return ConfigurationLoader;
  111441. }());
  111442. exports.ConfigurationLoader = ConfigurationLoader;
  111443. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibG9hZGVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2NvbmZpZ3VyYXRpb24vbG9hZGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEscUNBQTBDO0FBRTFDLGlDQUErQztBQUMvQywyRUFBaUY7QUFFakYsK0JBQXVDO0FBQ3ZDLHVDQUFnRDtBQUVoRDs7OztHQUlHO0FBQ0g7SUFNSSw2QkFBb0IsWUFBNkI7UUFBN0IsNkJBQUEsRUFBQSxvQkFBNkI7UUFBN0IsaUJBQVksR0FBWixZQUFZLENBQWlCO1FBQzdDLElBQUksQ0FBQyxtQkFBbUIsR0FBRyxFQUFFLENBQUM7UUFDOUIsSUFBSSxDQUFDLGFBQWEsR0FBRyxFQUFFLENBQUM7SUFDNUIsQ0FBQztJQUVEOzs7Ozs7O09BT0c7SUFDSSwrQ0FBaUIsR0FBeEIsVUFBeUIsVUFBb0MsRUFBRSxRQUFnRDtRQ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HQUFHLEVBQUUsQ0FBQyxDQUFDLENBQUM7Z0JBQ3RDLElBQUksS0FBSSxDQUFDLFlBQVk7b0JBQUUsY0FBYyxDQUFDLEdBQUcsQ0FBQyxHQUFHLE1BQU0sQ0FBQztnQkFDcEQsT0FBTyxDQUFDLE1BQU0sQ0FBQyxDQUFDO1lBQ3BCLENBQUMsRUFBRSxTQUFTLEVBQUUsU0FBUyxFQUFFLEtBQUssRUFBRSxVQUFDLE9BQU8sRUFBRSxLQUFVO2dCQUNoRCxJQUFJLEdBQUcsR0FBRyxLQUFJLENBQUMsYUFBYSxDQUFDLE9BQU8sQ0FBQyxXQUFXLENBQUMsQ0FBQztnQkFDbEQsSUFBSSxHQUFHLEtBQUssQ0FBQyxDQUFDO29CQUNWLEtBQUksQ0FBQyxhQUFhLENBQUMsTUFBTSxDQUFDLEdBQUcsRUFBRSxDQUFDLENBQUMsQ0FBQztnQkFDdEMsTUFBTSxDQUFDLEtBQUssQ0FBQyxDQUFDO1lBQ2xCLENBQUMsQ0FBQyxDQUFDO1lBQ0gsS0FBSSxDQUFDLGFBQWEsQ0FBQyxJQUFJLENBQUMsV0FBVyxDQUFDLENBQUM7UUFDekMsQ0FBQyxDQUFDLENBQUM7SUFDUCxDQUFDO0lBRUwsMEJBQUM7QUFBRCxDQUFDLEFBMUdELElBMEdDO0FBMUdZLGtEQUFtQiJ9
  111444. /***/ }),
  111445. /* 29 */
  111446. /***/ (function(module, exports, __webpack_require__) {
  111447. "use strict";
  111448. Object.defineProperty(exports, "__esModule", { value: true });
  111449. var minimal_1 = __webpack_require__(30);
  111450. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  111451. var default_1 = __webpack_require__(49);
  111452. exports.defaultConfiguration = default_1.defaultConfiguration;
  111453. var extended_1 = __webpack_require__(50);
  111454. var shadowLight_1 = __webpack_require__(51);
  111455. var environmentMap_1 = __webpack_require__(52);
  111456. var _1 = __webpack_require__(1);
  111457. /**
  111458. * Get the configuration type you need to use as the base for your viewer.
  111459. * The types can either be a single string, or comma separated types that will extend each other. for example:
  111460. *
  111461. * "default, environmentMap" will first load the default configuration and will extend it using the environmentMap configuration.
  111462. *
  111463. * @param types a comma-separated string of the type(s) or configuration to load.
  111464. */
  111465. var getConfigurationType = function (types) {
  111466. var config = {};
  111467. var typesSeparated = types.split(",");
  111468. typesSeparated.forEach(function (type) {
  111469. switch (type.trim()) {
  111470. case 'environmentMap':
  111471. config = _1.deepmerge(config, environmentMap_1.environmentMapConfiguration);
  111472. break;
  111473. case 'shadowDirectionalLight':
  111474. config = _1.deepmerge(config, shadowLight_1.shadowDirectionalLightConfiguration);
  111475. break;
  111476. case 'shadowSpotLight':
  111477. config = _1.deepmerge(config, shadowLight_1.shadowSpotlLightConfiguration);
  111478. break;
  111479. case 'extended':
  111480. config = _1.deepmerge(config, extended_1.extendedConfiguration);
  111481. break;
  111482. case 'minimal':
  111483. config = _1.deepmerge(config, minimal_1.minimalConfiguration);
  111484. break;
  111485. case 'none':
  111486. break;
  111487. case 'default':
  111488. default:
  111489. config = _1.deepmerge(config, default_1.defaultConfiguration);
  111490. break;
  111491. }
  111492. if (config.extends) {
  111493. config = _1.deepmerge(config, getConfigurationType(config.extends));
  111494. }
  111495. });
  111496. return config;
  111497. };
  111498. exports.getConfigurationType = getConfigurationType;
  111499. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHFDQUFpRDtBQW9ESSwrQkFwRDVDLDhCQUFvQixDQW9ENEM7QUFuRHpFLHFDQUFpRDtBQW1EbEIsK0JBbkR0Qiw4QkFBb0IsQ0FtRHNCO0FBbERuRCx1Q0FBbUQ7QUFFbkQsNkNBQW1HO0FBQ25HLG1EQUErRDtBQUM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NQUFNLEdBQUcsWUFBUyxDQUFDLE1BQU0sRUFBRSxvQkFBb0IsQ0FBQyxNQUFNLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FBQztTQUNwRTtJQUNMLENBQUMsQ0FBQyxDQUFDO0lBQ0gsT0FBTyxNQUFNLENBQUM7QUFFbEIsQ0FBQyxDQUFBO0FBRVEsb0RBQW9CIn0=
  111500. /***/ }),
  111501. /* 30 */
  111502. /***/ (function(module, exports, __webpack_require__) {
  111503. "use strict";
  111504. Object.defineProperty(exports, "__esModule", { value: true });
  111505. var babylonjs_viewer_assets_1 = __webpack_require__(2);
  111506. var babylonjs_viewer_assets_2 = __webpack_require__(2);
  111507. /**
  111508. * The minimal configuration needed to make the viewer work.
  111509. * Some functionalities might not work correctly (like fill-screen)
  111510. */
  111511. exports.minimalConfiguration = {
  111512. version: "0.1",
  111513. templates: {
  111514. main: {
  111515. html: babylonjs_viewer_assets_1.defaultTemplate
  111516. },
  111517. fillContainer: {
  111518. html: babylonjs_viewer_assets_1.fillContainer,
  111519. params: {
  111520. disable: false
  111521. }
  111522. },
  111523. loadingScreen: {
  111524. html: babylonjs_viewer_assets_1.loadingScreen,
  111525. params: {
  111526. backgroundColor: "#000000",
  111527. loadingImage: babylonjs_viewer_assets_2.loading
  111528. }
  111529. },
  111530. viewer: {
  111531. html: babylonjs_viewer_assets_1.defaultViewer,
  111532. },
  111533. overlay: {
  111534. html: babylonjs_viewer_assets_1.overlay,
  111535. params: {
  111536. closeImage: babylonjs_viewer_assets_2.close,
  111537. closeText: 'Close'
  111538. }
  111539. },
  111540. error: {
  111541. html: babylonjs_viewer_assets_1.error
  111542. }
  111543. },
  111544. engine: {
  111545. antialiasing: true
  111546. }
  111547. };
  111548. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWluaW1hbC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL3R5cGVzL21pbmltYWwudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSxtRUFBdUg7QUFDdkgsbUVBQXlEO0FBRXpEOzs7R0FHRztBQUNRLFFBQUEsb0JBQW9CLEdBQXdCO0lBQ25ELE9BQU8sRUFBRSxLQUFLO0lBQ2QsU0FBUyxFQUFFO1FBQ1AsSUFBSSxFQUFFO1lBQ0YsSUFBSSxFQUFFLHlDQUFlO1NBQ3hCO1FBQ0QsYUFBYSxFQUFFO1lBQ1gsSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixPQUFPLEVBQUUsS0FBSzthQUNqQjtTQUNKO1FBQ0QsYUFBYSxFQUFFO1lBQ1gsSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixlQUFlLEVBQUUsU0FBUztnQkFDMUIsWUFBWSxFQUFFLGlDQUFPO2FBQ3hCO1NBQ0o7UUFDRCxNQUFNLEVBQUU7WUFDSixJQUFJLEVBQUUsdUNBQWE7U0FDdEI7UUFDRCxPQUFPLEVBQUU7WUFDTCxJQUFJLEVBQUUsaUNBQU87WUFDYixNQUFNLEVBQUU7Z0JBQ0osVUFBVSxFQUFFLCtCQUFLO2dCQUNqQixTQUFTLEVBQUUsT0FBTzthQUNyQjtTQUNKO1FBQ0QsS0FBSyxFQUFFO1lBQ0gsSUFBSSxFQUFFLCtCQUFLO1NBQ2Q7S0FFSjtJQUNELE1BQU0sRUFBRTtRQUNKLFlBQVksRUFBRSxJQUFJO0tBQ3JCO0NBQ0osQ0FBQSJ9
  111549. /***/ }),
  111550. /* 31 */
  111551. /***/ (function(module, exports, __webpack_require__) {
  111552. "use strict";
  111553. Object.defineProperty(exports, "__esModule", { value: true });
  111554. exports.babylonFont = __webpack_require__(32);
  111555. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9udC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9hc3NldHMvZm9udC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFhLFFBQUEsV0FBVyxHQUFHLE9BQU8sQ0FBQywyQkFBMkIsQ0FBQyxDQUFDIn0=
  111556. /***/ }),
  111557. /* 32 */
  111558. /***/ (function(module, exports) {
  111559. module.exports = "data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAABIgAA8AAAAAH7gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABPUy8yAAABWAAAAEcAAABgSlp9rlZETVgAAAGgAAACBQAABeCBXolxY21hcAAAA6gAAABxAAAAsqyRvzljdnQgAAAEHAAAACAAAAAqCdkJr2ZwZ20AAAQ8AAAA8AAAAVn8nuaOZ2FzcAAABSwAAAAMAAAADAAIABtnbHlmAAAFOAAABlUAAAh+MHVDHWhlYWQAAAuQAAAAMgAAADb+LvI4aGhlYQAAC8QAAAAVAAAAJBABCAZobXR4AAAL3AAAACYAAAAqErQDvGxvY2EAAAwEAAAAIgAAACIJ6we4bWF4cAAADCgAAAAcAAAAIACJANFuYW1lAAAMRAAABTsAAAvzM/OUeXBvc3QAABGAAAAAEwAAACD/UQB3cHJlcAAAEZQAAACJAAAA03i98g542mNgZk9knMDAysDBOovVmIGBURpCM19kSGMS4mBl5WJkYgQDBiAQYEAA32AFBQYHBt7vwhxgPoRkAKtjgfAUGBgAoqoGywB42hXJUxQYBgAEwclf2qa2bdu2bdu2bdu2bdu2bTtlur15734WAwz4fwYZPHCIgWGoMHQYJqqD+mHDcGH4MEIYMYwURg6jhFHDaGH0MEYYM4wVxg7jhHHDeGH8MEGYMEwUJg6ThEnDZGHyMEWYMkwVpg7ThGnDdGH6MEOYMcwUZg6zhFnDbGH2MEeYM8wV5g7zhHnDfGH+sEBYMCwUFg6LhEXDYmHxsERYMiwVlg7LhGXDcmH5sEJYMawUVg6rhFXDamH1sEZYM6wV1g7rhHXDemH9sEHYM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function(module, exports, __webpack_require__) {
  111563. "use strict";
  111564. Object.defineProperty(exports, "__esModule", { value: true });
  111565. exports.babylonLogo = __webpack_require__(34);
  111566. exports.close = __webpack_require__(35);
  111567. exports.fullscreen = __webpack_require__(36);
  111568. exports.helpCircle = __webpack_require__(37);
  111569. exports.loading = __webpack_require__(38);
  111570. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW1nLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2Fzc2V0cy9pbWcudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBYSxRQUFBLFdBQVcsR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQztBQUNuRSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsNEJBQTRCLENBQUMsQ0FBQztBQUM5QyxRQUFBLFVBQVUsR0FBRyxPQUFPLENBQUMsaUNBQWlDLENBQUMsQ0FBQztBQUN4RCxRQUFBLFVBQVUsR0FBRyxPQUFPLENBQUMsa0NBQWtDLENBQUMsQ0FBQztBQUN6RCxRQUFBLE9BQU8sR0FBRyxPQUFPLENBQUMsOEJBQThCLENBQUMsQ0FBQyJ9
  111571. /***/ }),
  111572. /* 34 */
  111573. /***/ (function(module, exports) {
  111574. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB7MAAAgHCAYAAABZmyd0AAAACXBIWXMAAC4jAAAuIwF4pT92AAAgAElEQVR42uzd7XEb6Zm24Wtc+5/IgO0IyDcCtiMQNwLBEYgTgaAIhhOBpQhMRSAwghEjWCoCixHw/fE0DIKiKAIE+vM4qlDi1I531/fYRDdOPHf/dn9/HwAAAAAmb5bkNMnSKAAAgD74HyMAAAAAmJwqJVyfJqmbP4+a/9m3JIskH40JAADo0m9OZgMAAACM2ukTr6MX/OtEbQAAoFNiNgAAAMB41FkH6yrJ2R7+d4raAABAJ8RsAAAAgOFZP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+YVvDIAAAAASUVORK5CYII="
  111575. /***/ }),
  111576. /* 35 */
  111577. /***/ (function(module, exports) {
  111578. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  111579. /***/ }),
  111580. /* 36 */
  111581. /***/ (function(module, exports) {
  111582. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  111583. /***/ }),
  111584. /* 37 */
  111585. /***/ (function(module, exports) {
  111586. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAB/ElEQVR42u3Xs4JdQRzH8X9sqYrNNnbqtPELxKgWD7AsI71B7BcI21W9rNa+d27zjSac/5kzZ2J8yqPfGUn++xMwis2UcpsGuilQoJt6blHCJkbKt2I+FbSRpJVy5kos5nAVQxrDJWbFfP4wXYTqYL9kwRiuk9VFRksYJvKEGA+ZEPb3+udrOcNaJjGJtZyhTo8IKIVaOXmOMfKrrnsCo1WU+HFE/fxu9dk9asR+f8fswnU08fmTuDo8nZarat2P/DjobtFPP3dY8bGi6jNUE/MxuM58vNsFVvfHiHNqleqjmwo0a+zdW3zutr26Dk2ZPqW1oZli7/fzuT57dQqaFmUaZDNZ9HoDYIMbUEoWt+xb69EVuwG3CdfNcvtWNbqbbkB9ePVgK4DFDKGrcwO6CNPHJvvGdGpI0uEGGELk2WGfn8or33OxAUc/TulP8cnHVVENI5Vhp+mIa+TT9tm9pKkN7ab6tHEDRVo3LUGjTxuNpClyAzaRSiwGSbPeDRhJC99Ls7rno5zvpUw0zMMQQV1wdFzmezgvSZhJR1Aj+3QyW5Jx8JsD9okfV74p4ELIceNudMAjRodtfh8T4yETg7fvEf3pAqMlCw7QQah29kl2zOIiedLkOc9MicVcymkhSQtlzJVvxUg2UMxNaunCYOiihpsUsZ6R8t8f4DUz8hFGPnrb0AAAAABJRU5ErkJggg=="
  111587. /***/ }),
  111588. /* 38 */
  111589. /***/ (function(module, exports) {
  111590. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAStUlEQVR42uyaA7TrShiFn23btm3btm3btm3btm372LWd9+318nSRNk2mtz3trLXX5PbmZOafPT9nxmq1VmuKFggEZs1ms0uVSqUj8vn8Q/SP5nK5lRpMjFYLh8NTZTKZhSBxi2KxeDlEPgh+BQVrhKbfwDNgZf45QZ2J0mrxeHxGtHJRCDoUQm+FpLd4joKc5aKJaDbDNzxuZT3yyLg1FqPVWPip0un0PBCxMUScD+6wtTJr+dz49hdsmh14nMiAKK0WiUSmgbjFC4XCYSz2VeB9/p2wyaxJK9EY93set+dxwhYr1QU9U7B4s4CNIfMM+pvAzyBm1VFjPl+D3cDELdacyVy4kMsdLBMrX0kf4beM1QCt9Ff7hY14nGRpWiIHBgYmU+BDwLMRi3EMJN4KpJUBa5g05OlHthORc4amIJXgZ30EPtXWyiHITFtN0JBziDz6DB6nHtYEI+i04BZQtJqwIfcAOBXM0hCEdXR0TM1k5ydV2Iv+CLTyeXbqgWeeeeY4DmnMOGjxTrw/aDVpkxtirW7Bos09xkns6+ublAlNA3Gr4S+3JCe4ksk9YOeWsdH4nkcTicTMZfLVuXjvrQYmKS54/EZaRReqaQvzz7FrZUYXBocz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bPHSBywngFzzDeiEkB2zovybktEch90C9wcI/zQjSelhUQ3DJTkpdrCxwD+IJroCvCdPXnMAg2PLfDU6qoF/eX6TZVl8Lclzax0dsyrVqBpO4pqAQHcDecz3EvxQwkI16kGkp9m0v2ljxoU/UGfElBUCxYCMK/HKejMj5LpRriWVx1yNIgfmhyz+83U4WzFvDsAZUa1yYwfcLAh4P3kwI+S6RMybBcrHjKg8XQshTiOZESR+bS+prONUK1niITtvezTcAGYEid2zasSpGUY1ekSztpgRcpHpsK5co1er1YRDu6DelsCMOL5d6DmVo78FBgRzcRy+pgTzFeiqVq1Ki43KZo0b/wP23paVqC/D3gAAAABJRU5ErkJggg=="
  111591. /***/ }),
  111592. /* 39 */
  111593. /***/ (function(module, exports, __webpack_require__) {
  111594. "use strict";
  111595. Object.defineProperty(exports, "__esModule", { value: true });
  111596. exports.defaultTemplate = __webpack_require__(40);
  111597. exports.defaultViewer = __webpack_require__(41);
  111598. exports.error = __webpack_require__(42);
  111599. exports.fillContainer = __webpack_require__(43);
  111600. exports.help = __webpack_require__(44);
  111601. exports.loadingScreen = __webpack_require__(45);
  111602. exports.navbar = __webpack_require__(46);
  111603. exports.overlay = __webpack_require__(47);
  111604. exports.share = __webpack_require__(48);
  111605. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVtcGxhdGVzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2Fzc2V0cy90ZW1wbGF0ZXMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBYSxRQUFBLGVBQWUsR0FBRyxPQUFPLENBQUMscURBQXFELENBQUMsQ0FBQztBQUNqRixRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQztBQUM3RCxRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLElBQUksR0FBRyxPQUFPLENBQUMsMENBQTBDLENBQUMsQ0FBQztBQUMzRCxRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLE1BQU0sR0FBRyxPQUFPLENBQUMsNENBQTRDLENBQUMsQ0FBQztBQUMvRCxRQUFBLE9BQU8sR0FBRyxPQUFPLENBQUMsNkNBQTZDLENBQUMsQ0FBQztBQUNqRSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQyJ9
  111606. /***/ }),
  111607. /* 40 */
  111608. /***/ (function(module, exports) {
  111609. 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>";
  111610. /***/ }),
  111611. /* 41 */
  111612. /***/ (function(module, exports) {
  111613. 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>";
  111614. /***/ }),
  111615. /* 42 */
  111616. /***/ (function(module, exports) {
  111617. module.exports = "Error loading the model";
  111618. /***/ }),
  111619. /* 43 */
  111620. /***/ (function(module, exports) {
  111621. 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>";
  111622. /***/ }),
  111623. /* 44 */
  111624. /***/ (function(module, exports) {
  111625. module.exports = "HELP";
  111626. /***/ }),
  111627. /* 45 */
  111628. /***/ (function(module, exports) {
  111629. 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}}>";
  111630. /***/ }),
  111631. /* 46 */
  111632. /***/ (function(module, exports) {
  111633. 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:\"\\EF4E\"}.progress-control{display:flex;flex:1;position:relative;overflow:hidden;cursor:pointer;align-items:center}.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}.fullscreen{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}.fullscreen{display:block}}@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;height:30px;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>";
  111634. /***/ }),
  111635. /* 47 */
  111636. /***/ (function(module, exports) {
  111637. 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>";
  111638. /***/ }),
  111639. /* 48 */
  111640. /***/ (function(module, exports) {
  111641. module.exports = "SHARE";
  111642. /***/ }),
  111643. /* 49 */
  111644. /***/ (function(module, exports, __webpack_require__) {
  111645. "use strict";
  111646. Object.defineProperty(exports, "__esModule", { value: true });
  111647. var babylonjs_viewer_assets_1 = __webpack_require__(2);
  111648. var babylonjs_viewer_assets_2 = __webpack_require__(2);
  111649. var images = __webpack_require__(2);
  111650. /**
  111651. * The default configuration of the viewer, including templates (canvas, overly, loading screen)
  111652. * This configuration doesn't hold specific parameters, and only defines objects that are needed for the viewer to fully work correctly.
  111653. */
  111654. exports.defaultConfiguration = {
  111655. version: "3.2.0-alpha4",
  111656. templates: {
  111657. main: {
  111658. html: babylonjs_viewer_assets_1.defaultTemplate,
  111659. params: {
  111660. babylonFont: babylonjs_viewer_assets_2.babylonFont,
  111661. noEscape: true
  111662. }
  111663. },
  111664. fillContainer: {
  111665. html: babylonjs_viewer_assets_1.fillContainer,
  111666. params: {
  111667. disable: false
  111668. }
  111669. },
  111670. loadingScreen: {
  111671. html: babylonjs_viewer_assets_1.loadingScreen,
  111672. params: {
  111673. backgroundColor: "#000000",
  111674. loadingImage: images.loading
  111675. }
  111676. },
  111677. viewer: {
  111678. html: babylonjs_viewer_assets_1.defaultViewer,
  111679. params: {
  111680. enableDragAndDrop: false
  111681. }
  111682. },
  111683. navBar: {
  111684. html: babylonjs_viewer_assets_1.navbar,
  111685. params: {
  111686. speedList: {
  111687. "0.5x": "0.5",
  111688. "1.0x": "1.0",
  111689. "1.5x": "1.5",
  111690. "2.0x": "2.0",
  111691. },
  111692. logoImage: images.babylonLogo,
  111693. logoText: 'BabylonJS',
  111694. logoLink: 'https://babylonjs.com',
  111695. hideHelp: true,
  111696. disableOnFullscreen: false,
  111697. },
  111698. events: {
  111699. pointerdown: {
  111700. 'navbar-control': true,
  111701. 'help-button': true
  111702. },
  111703. input: {
  111704. 'progress-wrapper': true
  111705. },
  111706. pointerup: {
  111707. 'progress-wrapper': true
  111708. }
  111709. }
  111710. },
  111711. overlay: {
  111712. html: babylonjs_viewer_assets_1.overlay,
  111713. params: {
  111714. closeImage: images.close,
  111715. closeText: 'Close'
  111716. }
  111717. },
  111718. help: {
  111719. html: babylonjs_viewer_assets_1.help
  111720. },
  111721. share: {
  111722. html: babylonjs_viewer_assets_1.share
  111723. },
  111724. error: {
  111725. html: babylonjs_viewer_assets_1.error
  111726. }
  111727. },
  111728. camera: {
  111729. behaviors: {
  111730. autoRotate: {
  111731. type: 0
  111732. },
  111733. framing: {
  111734. type: 2,
  111735. zoomOnBoundingInfo: true,
  111736. zoomStopsAnimation: false
  111737. },
  111738. bouncing: {
  111739. type: 1
  111740. }
  111741. },
  111742. wheelPrecision: 200,
  111743. },
  111744. skybox: {},
  111745. ground: {
  111746. receiveShadows: true
  111747. },
  111748. engine: {
  111749. antialiasing: true
  111750. },
  111751. scene: {}
  111752. };
  111753. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVmYXVsdC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL3R5cGVzL2RlZmF1bHQudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSxtRUFBNEk7QUFDNUksbUVBQXNEO0FBQ3RELGdEQUFrRDtBQUVsRDs7O0dBR0c7QUFDUSxRQUFBLG9CQUFvQixHQUF3QjtJQUNuRCxPQUFPLEVBQUUsY0FBYztJQUN2QixTQUFTLEVBQUU7UUFDUCxJQUFJLEVBQUU7WUFDRixJQUFJLEVBQUUseUNBQWU7WUFDckIsTUFBTSxFQUFFO2dCQUNKLFdBQVcsRUFBRSxxQ0FBVztnQkFDeEIsUUFBUSxFQUFFLElBQUk7YUFDakI7U0FDSjtRQUNELGFBQWEsRUFBRTtZQUNYLElBQUksRUFBRSx1Q0FBYTtZQUNuQixNQUFNLEVBQUU7Z0JBQ0osT0FBTyxFQUFFLEtBQUs7YUFDakI7U0FDSjtRQUNELGFBQWEsRUFBRTtZQUNYLElBQUksRUFBRSx1Q0FBYTtZQUNuQixNQUFNLEVBQUU7Z0JBQ0osZUFBZSxFQUFFLFNBQVM7Z0JBQzFCLFlBQVksRUFBRSxNQUFNLENBQUMsT0FBTzthQUMvQjtTQUNKO1FBQ0QsTUFBTSxFQUFFO1lBQ0osSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixpQkFBaUIsRUFBRSxLQUFLO2FBQzNCO1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UFFLENBQUM7YUFDVjtZQUNELE9BQU8sRUFBRTtnQkFDTCxJQUFJLEVBQUUsQ0FBQztnQkFDUCxrQkFBa0IsRUFBRSxJQUFJO2dCQUN4QixrQkFBa0IsRUFBRSxLQUFLO2FBQzVCO1lBQ0QsUUFBUSxFQUFFO2dCQUNOLElBQUksRUFBRSxDQUFDO2FBQ1Y7U0FDSjtRQUNELGNBQWMsRUFBRSxHQUFHO0tBQ3RCO0lBQ0QsTUFBTSxFQUFFLEVBQ1A7SUFDRCxNQUFNLEVBQUU7UUFDSixjQUFjLEVBQUUsSUFBSTtLQUN2QjtJQUNELE1BQU0sRUFBRTtRQUNKLFlBQVksRUFBRSxJQUFJO0tBQ3JCO0lBQ0QsS0FBSyxFQUFFLEVBQ047Q0FDSixDQUFBIn0=
  111754. /***/ }),
  111755. /* 50 */
  111756. /***/ (function(module, exports, __webpack_require__) {
  111757. "use strict";
  111758. Object.defineProperty(exports, "__esModule", { value: true });
  111759. var babylonjs_1 = __webpack_require__(0);
  111760. /**
  111761. * The viewer's "extended" configuration.
  111762. * This configuration defines specific obejcts and parameters that we think make any model look good.
  111763. */
  111764. exports.extendedConfiguration = {
  111765. version: "3.2.0",
  111766. extends: "default",
  111767. camera: {
  111768. exposure: 3.034578,
  111769. fov: 0.7853981633974483,
  111770. contrast: 1.6,
  111771. toneMappingEnabled: true,
  111772. upperBetaLimit: 1.3962634015954636 + Math.PI / 2,
  111773. lowerBetaLimit: -1.4835298641951802 + Math.PI / 2,
  111774. behaviors: {
  111775. framing: {
  111776. type: 2,
  111777. mode: 0,
  111778. positionScale: 0.5,
  111779. defaultElevation: 0.2617993877991494,
  111780. elevationReturnWaitTime: 3000,
  111781. elevationReturnTime: 2000,
  111782. framingTime: 500,
  111783. zoomStopsAnimation: false,
  111784. radiusScale: 0.866
  111785. },
  111786. autoRotate: {
  111787. type: 0,
  111788. idleRotationWaitTime: 4000,
  111789. idleRotationSpeed: 0.17453292519943295,
  111790. idleRotationSpinupTime: 2500,
  111791. zoomStopsAnimation: false
  111792. },
  111793. bouncing: {
  111794. type: 1,
  111795. lowerRadiusTransitionRange: 0.05,
  111796. upperRadiusTransitionRange: -0.2
  111797. }
  111798. },
  111799. upperRadiusLimit: 5,
  111800. lowerRadiusLimit: 0.5,
  111801. frameOnModelLoad: true,
  111802. framingElevation: 0.2617993877991494,
  111803. framingRotation: 1.5707963267948966,
  111804. radius: 2,
  111805. alpha: 1.5708,
  111806. beta: Math.PI * 0.5 - 0.2618,
  111807. wheelPrecision: 300,
  111808. minZ: 0.1,
  111809. maxZ: 50,
  111810. fovMode: 0,
  111811. pinchPrecision: 1500,
  111812. panningSensibility: 3000
  111813. },
  111814. lights: {
  111815. light0: {
  111816. type: 0,
  111817. frustumEdgeFalloff: 0,
  111818. intensity: 7,
  111819. intensityMode: 0,
  111820. radius: 0.6,
  111821. range: 0.6,
  111822. spotAngle: 60,
  111823. diffuse: {
  111824. r: 1,
  111825. g: 1,
  111826. b: 1
  111827. },
  111828. position: {
  111829. x: -2,
  111830. y: 2.5,
  111831. z: 2
  111832. },
  111833. target: {
  111834. x: 0,
  111835. y: 0,
  111836. z: 0
  111837. },
  111838. enabled: true,
  111839. shadowEnabled: true,
  111840. shadowBufferSize: 512,
  111841. shadowMinZ: 1,
  111842. shadowMaxZ: 10,
  111843. shadowFieldOfView: 60,
  111844. shadowFrustumSize: 2,
  111845. shadowConfig: {
  111846. useBlurCloseExponentialShadowMap: true,
  111847. useKernelBlur: true,
  111848. blurScale: 1.0,
  111849. bias: 0.001,
  111850. depthScale: 50 * (10 - 1),
  111851. frustumEdgeFalloff: 0
  111852. }
  111853. },
  111854. light1: {
  111855. type: 0,
  111856. frustumEdgeFalloff: 0,
  111857. intensity: 7,
  111858. intensityMode: 0,
  111859. radius: 0.4,
  111860. range: 0.4,
  111861. spotAngle: 57,
  111862. diffuse: {
  111863. r: 1,
  111864. g: 1,
  111865. b: 1
  111866. },
  111867. position: {
  111868. x: 4,
  111869. y: 3,
  111870. z: -0.5
  111871. },
  111872. target: {
  111873. x: 0,
  111874. y: 0,
  111875. z: 0
  111876. },
  111877. enabled: true,
  111878. shadowEnabled: false,
  111879. shadowBufferSize: 512,
  111880. shadowMinZ: 0.2,
  111881. shadowMaxZ: 10,
  111882. shadowFieldOfView: 28,
  111883. shadowFrustumSize: 2
  111884. },
  111885. light2: {
  111886. type: 0,
  111887. frustumEdgeFalloff: 0,
  111888. intensity: 1,
  111889. intensityMode: 0,
  111890. radius: 0.5,
  111891. range: 0.5,
  111892. spotAngle: 42.85,
  111893. diffuse: {
  111894. r: 0.8,
  111895. g: 0.8,
  111896. b: 0.8
  111897. },
  111898. position: {
  111899. x: -1,
  111900. y: 3,
  111901. z: -3
  111902. },
  111903. target: {
  111904. x: 0,
  111905. y: 0,
  111906. z: 0
  111907. },
  111908. enabled: true,
  111909. shadowEnabled: false,
  111910. shadowBufferSize: 512,
  111911. shadowMinZ: 0.2,
  111912. shadowMaxZ: 10,
  111913. shadowFieldOfView: 45,
  111914. shadowFrustumSize: 2
  111915. }
  111916. },
  111917. ground: {
  111918. shadowLevel: 0.9,
  111919. texture: "Ground_2.0-1024.png",
  111920. material: {
  111921. primaryColorHighlightLevel: 0.035,
  111922. primaryColorShadowLevel: 0,
  111923. enableNoise: true,
  111924. useRGBColor: false,
  111925. maxSimultaneousLights: 1,
  111926. diffuseTexture: {
  111927. gammaSpace: true
  111928. }
  111929. },
  111930. opacity: 1,
  111931. mirror: false,
  111932. receiveShadows: true,
  111933. size: 5
  111934. },
  111935. skybox: {
  111936. scale: 11,
  111937. cubeTexture: {
  111938. url: "Skybox_2.0-256.dds"
  111939. },
  111940. material: {
  111941. primaryColorHighlightLevel: 0.03,
  111942. primaryColorShadowLevel: 0.03,
  111943. enableNoise: true,
  111944. useRGBColor: false,
  111945. reflectionTexture: {
  111946. gammaSpace: true
  111947. }
  111948. }
  111949. },
  111950. engine: {
  111951. renderInBackground: true
  111952. },
  111953. scene: {
  111954. flags: {
  111955. shadowsEnabled: true,
  111956. particlesEnabled: false,
  111957. collisionsEnabled: false,
  111958. lightsEnabled: true,
  111959. texturesEnabled: true,
  111960. lensFlaresEnabled: false,
  111961. proceduralTexturesEnabled: false,
  111962. renderTargetsEnabled: true,
  111963. spritesEnabled: false,
  111964. skeletonsEnabled: true,
  111965. audioEnabled: false,
  111966. },
  111967. defaultMaterial: {
  111968. materialType: 'pbr',
  111969. reflectivityColor: {
  111970. r: 0.1,
  111971. g: 0.1,
  111972. b: 0.1
  111973. },
  111974. microSurface: 0.6
  111975. },
  111976. clearColor: {
  111977. r: 0.9,
  111978. g: 0.9,
  111979. b: 0.9,
  111980. a: 1.0
  111981. },
  111982. imageProcessingConfiguration: {
  111983. vignetteCentreX: 0,
  111984. vignetteCentreY: 0,
  111985. vignetteColor: {
  111986. r: 0.086,
  111987. g: 0.184,
  111988. b: 0.259,
  111989. a: 1
  111990. },
  111991. vignetteWeight: 0.855,
  111992. vignetteStretch: 0.5,
  111993. vignetteBlendMode: 0,
  111994. vignetteCameraFov: 0.7853981633974483,
  111995. isEnabled: true,
  111996. colorCurves: {
  111997. shadowsHue: 0,
  111998. shadowsDensity: 0,
  111999. shadowsSaturation: 0,
  112000. shadowsExposure: 0,
  112001. midtonesHue: 0,
  112002. midtonesDensity: 0,
  112003. midtonesExposure: 0,
  112004. midtonesSaturation: 0,
  112005. highlightsHue: 0,
  112006. highlightsDensity: 0,
  112007. highlightsExposure: 0,
  112008. highlightsSaturation: 0
  112009. }
  112010. },
  112011. mainColor: {
  112012. r: 0.8823529411764706,
  112013. g: 0.8823529411764706,
  112014. b: 0.8823529411764706
  112015. }
  112016. },
  112017. loaderPlugins: {
  112018. extendedMaterial: true,
  112019. applyMaterialConfig: true,
  112020. msftLod: true,
  112021. telemetry: true
  112022. },
  112023. model: {
  112024. rotationOffsetAxis: {
  112025. x: 0,
  112026. y: -1,
  112027. z: 0
  112028. },
  112029. rotationOffsetAngle: babylonjs_1.Tools.ToRadians(210),
  112030. material: {
  112031. directEnabled: true,
  112032. directIntensity: 0.884,
  112033. emissiveIntensity: 1.04,
  112034. environmentIntensity: 0.6
  112035. },
  112036. entryAnimation: {
  112037. scaling: {
  112038. x: 0,
  112039. y: 0,
  112040. z: 0
  112041. },
  112042. time: 0.5,
  112043. easingFunction: 4,
  112044. easingMode: 1
  112045. },
  112046. exitAnimation: {
  112047. scaling: {
  112048. x: 0,
  112049. y: 0,
  112050. z: 0
  112051. },
  112052. time: 0.5,
  112053. easingFunction: 4,
  112054. easingMode: 1
  112055. },
  112056. normalize: true,
  112057. castShadow: true,
  112058. receiveShadows: true
  112059. },
  112060. lab: {
  112061. assetsRootURL: 'https://viewer.babylonjs.com/assets/environment/',
  112062. environmentMap: {
  112063. texture: "EnvMap_2.0-256.env",
  112064. rotationY: 3,
  112065. tintLevel: 0.4
  112066. },
  112067. defaultRenderingPipelines: {
  112068. bloomEnabled: true,
  112069. bloomThreshold: 1.0,
  112070. fxaaEnabled: true,
  112071. bloomWeight: 0.05
  112072. }
  112073. }
  112074. };
  112075. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9leHRlbmRlZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUNBLHVDQUFrQztBQUVsQzs7O0dBR0c7QUFDUSxRQUFBLHFCQUFxQixHQUF3QjtJQUNwRCxPQUFPLEVBQUUsT0FBTztJQUNoQixPQUFPLEVBQUUsU0FBUztJQUNsQixNQUFNLEVBQUU7UUFDSixRQUFRLEVBQUUsUUFBUTtRQUNsQixHQUFHLEVBQUUsa0JBQWtCO1FBQ3ZCLFFBQVEsRUFBRSxHQUFHO1FBQ2Isa0JBQWtCLEVBQUUsSUFBSTtRQUN4QixjQUFjLEVBQUUsa0JBQWtCLEdBQUcsSUFBSSxDQUFDLEV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U8sRUFBRSxvQkFBb0I7WUFDN0IsU0FBUyxFQUFFLENBQUM7WUFDWixTQUFTLEVBQUUsR0FBRztTQUNqQjtRQUNELHlCQUF5QixFQUFFO1lBQ3ZCLFlBQVksRUFBRSxJQUFJO1lBQ2xCLGNBQWMsRUFBRSxHQUFHO1lBQ25CLFdBQVcsRUFBRSxJQUFJO1lBQ2pCLFdBQVcsRUFBRSxJQUFJO1NBQ3BCO0tBQ0o7Q0FDSixDQUFBIn0=
  112076. /***/ }),
  112077. /* 51 */
  112078. /***/ (function(module, exports, __webpack_require__) {
  112079. "use strict";
  112080. Object.defineProperty(exports, "__esModule", { value: true });
  112081. /**
  112082. * Defines a default directional shadow light for normalized objects (!)
  112083. */
  112084. exports.shadowDirectionalLightConfiguration = {
  112085. model: {
  112086. receiveShadows: true,
  112087. castShadow: true
  112088. },
  112089. ground: {
  112090. receiveShadows: true
  112091. },
  112092. lights: {
  112093. shadowDirectionalLight: {
  112094. type: 1,
  112095. shadowEnabled: true,
  112096. target: { x: 0, y: 0, z: 0.5 },
  112097. position: { x: 1.49, y: 2.39, z: -1.33 },
  112098. diffuse: { r: 0.867, g: 0.816, b: 0.788 },
  112099. intensity: 4.887,
  112100. intensityMode: 0,
  112101. shadowBufferSize: 1024,
  112102. shadowFrustumSize: 6.0,
  112103. shadowFieldOfView: 50.977,
  112104. shadowMinZ: 0.1,
  112105. shadowMaxZ: 10.0,
  112106. shadowConfig: {
  112107. blurKernel: 32,
  112108. useBlurCloseExponentialShadowMap: true
  112109. }
  112110. }
  112111. }
  112112. };
  112113. /**
  112114. * Defines a default shadow-enabled spot light for normalized objects.
  112115. */
  112116. exports.shadowSpotlLightConfiguration = {
  112117. model: {
  112118. receiveShadows: true,
  112119. castShadow: true
  112120. },
  112121. ground: {
  112122. receiveShadows: true
  112123. },
  112124. lights: {
  112125. shadowSpotLight: {
  112126. type: 2,
  112127. intensity: 2,
  112128. shadowEnabled: true,
  112129. target: { x: 0, y: 0, z: 0.5 },
  112130. position: { x: 0, y: 3.5, z: 3.7 },
  112131. angle: 1,
  112132. shadowOrthoScale: 0.5,
  112133. shadowBufferSize: 1024,
  112134. shadowMinZ: 0.1,
  112135. shadowMaxZ: 50.0,
  112136. shadowConfig: {
  112137. frustumEdgeFalloff: 0.5,
  112138. blurKernel: 32,
  112139. useBlurExponentialShadowMap: true
  112140. }
  112141. }
  112142. }
  112143. };
  112144. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2hhZG93TGlnaHQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9zaGFkb3dMaWdodC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUVBOztHQUVHO0FBQ1UsUUFBQSxtQ0FBbUMsR0FBd0I7SUFDcEUsS0FBSyxFQUFFO1FBQ0gsY0FBYyxFQUFFLElBQUk7UUFDcEIsVUFBVSxFQUFFLElBQUk7S0FDbkI7SUFDRCxNQUFNLEVBQUU7UUFDSixjQUFjLEVBQUUsSUFBSTtLQUN2QjtJQUNELE1BQU0sRUFBRTtRQUNKLHNCQUFzQixFQUFFO1lBQ3BCLElBQUksRUFBRSxDQUFDO1lBQ1AsYUFBYSxFQUFFLElBQUk7WUFDbkIsTUFBTSxFQUFFLEVBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxHQUFHLEVBQUU7WUFDOUIsUUFBUSxFQUFFLEVBQUUsQ0FBQyxFQUFFLElBQUksRUFBRSxDQUFDLEVBQUUsSUFBSSxFQUFFLENBQUMsRUFBRSxDQUFDLElBQUksRUFBRTtZQUN4QyxPQUFPLEVBQUUsRUFBRSxDQUFDLEVBQUUsS0FBSyxFQUFFLENBQUMsRUFBRSxLQUFLLEVBQUUsQ0FBQyxFQUFFLEtBQUssRUFBRTtZQUN6QyxTQUF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xFQUFFLEVBQUU7Z0JBQ2QsMkJBQTJCLEVBQUUsSUFBSTthQUNwQztTQUNKO0tBQ0o7Q0FDSixDQUFBIn0=
  112145. /***/ }),
  112146. /* 52 */
  112147. /***/ (function(module, exports, __webpack_require__) {
  112148. "use strict";
  112149. Object.defineProperty(exports, "__esModule", { value: true });
  112150. /**
  112151. * Lab-oriented default .env support
  112152. */
  112153. exports.environmentMapConfiguration = {
  112154. lab: {
  112155. assetsRootURL: '/assets/environment/',
  112156. environmentMap: {
  112157. texture: 'EnvMap_2.0-256.env',
  112158. rotationY: 0,
  112159. tintLevel: 0.4
  112160. }
  112161. }
  112162. };
  112163. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW52aXJvbm1lbnRNYXAuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9lbnZpcm9ubWVudE1hcC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUVBOztHQUVHO0FBQ1UsUUFBQSwyQkFBMkIsR0FBd0I7SUFDNUQsR0FBRyxFQUFFO1FBQ0QsYUFBYSxFQUFFLHNCQUFzQjtRQUNyQyxjQUFjLEVBQUU7WUFDWixPQUFPLEVBQUUsb0JBQW9CO1lBQzdCLFNBQVMsRUFBRSxDQUFDO1lBQ1osU0FBUyxFQUFFLEdBQUc7U0FDakI7S0FDSjtDQUNKLENBQUEifQ==
  112164. /***/ }),
  112165. /* 53 */
  112166. /***/ (function(module, exports, __webpack_require__) {
  112167. "use strict";
  112168. Object.defineProperty(exports, "__esModule", { value: true });
  112169. var configuration_1 = __webpack_require__(11);
  112170. /**
  112171. * This function will make sure the configuration file is taking deprecated fields into account
  112172. * and is setting them to the correct keys and values.
  112173. *
  112174. * @param configuration The configuration to process. Mutable!
  112175. */
  112176. function processConfigurationCompatibility(configuration) {
  112177. if (configuration.camera) {
  112178. // camera contrast -> image processing contrast
  112179. if (configuration.camera.contrast !== undefined) {
  112180. setKeyInObject(configuration, "scene.imageProcessingConfiguration.contrast", configuration.camera.contrast);
  112181. }
  112182. // camera exposure -> image processing exposure
  112183. if (configuration.camera.exposure !== undefined) {
  112184. setKeyInObject(configuration, "scene.imageProcessingConfiguration.exposure", configuration.camera.exposure);
  112185. }
  112186. }
  112187. if (configuration.scene) {
  112188. //glow
  112189. if (configuration.scene.glow) {
  112190. setKeyInObject(configuration, "lab.defaultRenderingPipelines.glowLayerEnabled", true);
  112191. var enabledProcessing = configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", configuration);
  112192. if (enabledProcessing !== false) {
  112193. setKeyInObject(configuration, "scene.imageProcessingConfiguration.isEnabled", true);
  112194. }
  112195. }
  112196. }
  112197. }
  112198. exports.processConfigurationCompatibility = processConfigurationCompatibility;
  112199. function setKeyInObject(object, keys, value, shouldOverwrite) {
  112200. var keySplit = keys.split(".");
  112201. if (keySplit.length === 0)
  112202. return;
  112203. var lastKey = keySplit.pop();
  112204. if (!lastKey)
  112205. return;
  112206. var curObj = object;
  112207. keySplit.forEach(function (key) {
  112208. curObj[key] = curObj[key] || {};
  112209. curObj = curObj[key];
  112210. });
  112211. if (curObj[lastKey] !== undefined && !shouldOverwrite)
  112212. return;
  112213. curObj[lastKey] = value;
  112214. }
  112215. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbkNvbXBhdGliaWxpdHkuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi9jb25maWd1cmF0aW9uQ29tcGF0aWJpbGl0eS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLGlEQUEwRTtBQUMxRTs7Ozs7R0FLRztBQUNILDJDQUFrRCxhQUFrQztJQUloRixJQUFJLGFBQWEsQ0FBQyxNQUFNLEVBQUU7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FDLEdBQUcsRUFBRSxDQUFDO0lBQzdCLElBQUksQ0FBQyxPQUFPO1FBQUUsT0FBTztJQUNyQixJQUFJLE1BQU0sR0FBRyxNQUFNLENBQUM7SUFDcEIsUUFBUSxDQUFDLE9BQU8sQ0FBQyxVQUFBLEdBQUc7UUFDaEIsTUFBTSxDQUFDLEdBQUcsQ0FBQyxHQUFHLE1BQU0sQ0FBQyxHQUFHLENBQUMsSUFBSSxFQUFFLENBQUM7UUFDaEMsTUFBTSxHQUFHLE1BQU0sQ0FBQyxHQUFHLENBQUMsQ0FBQztJQUN6QixDQUFDLENBQUMsQ0FBQztJQUNILElBQUksTUFBTSxDQUFDLE9BQU8sQ0FBQyxLQUFLLFNBQVMsSUFBSSxDQUFDLGVBQWU7UUFBRSxPQUFPO0lBQzlELE1BQU0sQ0FBQyxPQUFPLENBQUMsR0FBRyxLQUFLLENBQUM7QUFDNUIsQ0FBQyJ9
  112216. /***/ }),
  112217. /* 54 */
  112218. /***/ (function(module, exports, __webpack_require__) {
  112219. "use strict";
  112220. Object.defineProperty(exports, "__esModule", { value: true });
  112221. var telemetryLoaderPlugin_1 = __webpack_require__(55);
  112222. exports.TelemetryLoaderPlugin = telemetryLoaderPlugin_1.TelemetryLoaderPlugin;
  112223. var msftLodLoaderPlugin_1 = __webpack_require__(56);
  112224. exports.MSFTLodLoaderPlugin = msftLodLoaderPlugin_1.MSFTLodLoaderPlugin;
  112225. var applyMaterialConfig_1 = __webpack_require__(57);
  112226. exports.ApplyMaterialConfigPlugin = applyMaterialConfig_1.ApplyMaterialConfigPlugin;
  112227. var extendedMaterialLoaderPlugin_1 = __webpack_require__(58);
  112228. exports.ExtendedMaterialLoaderPlugin = extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin;
  112229. var babylonjs_1 = __webpack_require__(0);
  112230. var pluginCache = {};
  112231. /**
  112232. * Get a loader plugin according to its name.
  112233. * The plugin will be cached and will be reused if called for again.
  112234. *
  112235. * @param name the name of the plugin
  112236. */
  112237. function getLoaderPluginByName(name) {
  112238. if (!pluginCache[name]) {
  112239. switch (name) {
  112240. case 'telemetry':
  112241. pluginCache[name] = new telemetryLoaderPlugin_1.TelemetryLoaderPlugin();
  112242. break;
  112243. case 'msftLod':
  112244. pluginCache[name] = new msftLodLoaderPlugin_1.MSFTLodLoaderPlugin();
  112245. break;
  112246. case 'applyMaterialConfig':
  112247. pluginCache[name] = new applyMaterialConfig_1.ApplyMaterialConfigPlugin();
  112248. break;
  112249. case 'extendedMaterial':
  112250. pluginCache[name] = new extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin();
  112251. break;
  112252. }
  112253. }
  112254. return pluginCache[name];
  112255. }
  112256. exports.getLoaderPluginByName = getLoaderPluginByName;
  112257. /**
  112258. *
  112259. */
  112260. function addLoaderPlugin(name, plugin) {
  112261. if (pluginCache[name]) {
  112262. babylonjs_1.Tools.Warn("Overwriting plugin with the same name - " + name);
  112263. }
  112264. pluginCache[name] = plugin;
  112265. }
  112266. exports.addLoaderPlugin = addLoaderPlugin;
  112267. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvbG9hZGVyL3BsdWdpbnMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpRUFBZ0U7QUFTdkQsZ0NBVEEsNkNBQXFCLENBU0E7QUFQOUIsNkRBQTREO0FBT2IsOEJBUHRDLHlDQUFtQixDQU9zQztBQU5sRSw2REFBa0U7QUFNRSxvQ0FOM0QsK0NBQXlCLENBTTJEO0FBTDdGLCtFQUE4RTtBQUtpQix1Q0FMdEYsMkRBQTRCLENBS3NGO0FBSjNILHVDQUFrQztBQUVsQyxJQUFNLFdBQVcsR0FBcUMsRUFBRSxDQUFDO0FBSXpEOzs7OztHQUtHO0FBQ0gsK0JBQXNDLElBQVk7SUFDOUMsSUFBSSxDQUFDLFdBQVcsQ0FBQyxJQUFJLENBQUMsRUFBRTtRQUNwQixRQUFRLElBQUksRUFBRTtZQUNWLEtBQUssV0FBVztnQkFDWixXQUFXLENBQUMsSUFBSSxDQUFDLEdBQUcsSUFBSSw2Q0FBcUIsRUFBRSxDQUFDO2dCQUNoRCxNQUFNO1lBQ1YsS0FBSyxTQUFTO2dCQUNWLFdBQVcsQ0FBQyxJQUFJLENBQUMsR0FBRyxJQUFJLHlDQUFtQixFQUFFLENBQUM7Z0JBQzlDLE1BQU07WUFDVixLQUFLLHFCQUFxQjtnQkFDdEIsV0FBVyxDQUFDLElBQUksQ0FBQyxHQUFHLElBQUksK0NBQXlCLEVBQUUsQ0FBQztnQkFDcEQsTUFBTTtZQUNWLEtBQUssa0JBQWtCO2dCQUNuQixXQUFXLENBQUMsSUFBSSxDQUFDLEdBQUcsSUFBSSwyREFBNEIsRUFBRSxDQUFDO2dCQUN2RCxNQUFNO1NBQ2I7S0FDSjtJQUVELE9BQU8sV0FBVyxDQUFDLElBQUksQ0FBQyxDQUFDO0FBQzdCLENBQUM7QUFuQkQsc0RBbUJDO0FBRUQ7O0dBRUc7QUFDSCx5QkFBZ0MsSUFBWSxFQUFFLE1BQXFCO0lBQy9ELElBQUksV0FBVyxDQUFDLElBQUksQ0FBQyxFQUFFO1FBQ25CLGlCQUFLLENBQUMsSUFBSSxDQUFDLDBDQUEwQyxHQUFHLElBQUksQ0FBQyxDQUFDO0tBQ2pFO0lBQ0QsV0FBVyxDQUFDLElBQUksQ0FBQyxHQUFHLE1BQU0sQ0FBQztBQUMvQixDQUFDO0FBTEQsMENBS0MifQ==
  112268. /***/ }),
  112269. /* 55 */
  112270. /***/ (function(module, exports, __webpack_require__) {
  112271. "use strict";
  112272. Object.defineProperty(exports, "__esModule", { value: true });
  112273. var telemetryManager_1 = __webpack_require__(6);
  112274. var babylonjs_1 = __webpack_require__(0);
  112275. var TelemetryLoaderPlugin = /** @class */ (function () {
  112276. function TelemetryLoaderPlugin() {
  112277. }
  112278. TelemetryLoaderPlugin.prototype.onInit = function (loader, model) {
  112279. this._model = model;
  112280. this._loadStart = babylonjs_1.Tools.Now;
  112281. };
  112282. TelemetryLoaderPlugin.prototype.onLoaded = function (model) {
  112283. telemetryManager_1.telemetryManager.broadcast("Model Loaded", model.getViewerId(), {
  112284. model: model,
  112285. loadTime: babylonjs_1.Tools.Now - this._loadStart
  112286. });
  112287. telemetryManager_1.telemetryManager.flushWebGLErrors(model.rootMesh.getEngine(), model.getViewerId());
  112288. };
  112289. TelemetryLoaderPlugin.prototype.onError = function (message, exception) {
  112290. this._loadEnd = babylonjs_1.Tools.Now;
  112291. telemetryManager_1.telemetryManager.broadcast("Load Error", this._model.getViewerId(), {
  112292. model: this._model,
  112293. loadTime: this._loadEnd - this._loadStart
  112294. });
  112295. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.rootMesh.getEngine(), this._model.getViewerId());
  112296. };
  112297. TelemetryLoaderPlugin.prototype.onComplete = function () {
  112298. this._loadEnd = babylonjs_1.Tools.Now;
  112299. telemetryManager_1.telemetryManager.broadcast("Load Complete", this._model.getViewerId(), {
  112300. model: this._model,
  112301. loadTime: this._loadEnd - this._loadStart
  112302. });
  112303. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.rootMesh.getEngine(), this._model.getViewerId());
  112304. };
  112305. return TelemetryLoaderPlugin;
  112306. }());
  112307. exports.TelemetryLoaderPlugin = TelemetryLoaderPlugin;
  112308. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVsZW1ldHJ5TG9hZGVyUGx1Z2luLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vLi4vc3JjL2xvYWRlci9wbHVnaW5zL3RlbGVtZXRyeUxvYWRlclBsdWdpbi50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUNBLG9FQUFtRTtBQUVuRSx1Q0F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LENBQUMsTUFBTSxDQUFDLFdBQVcsRUFBRSxDQUFDLENBQUM7SUFDbkcsQ0FBQztJQUVNLDBDQUFVLEdBQWpCO1FBQ0ksSUFBSSxDQUFDLFFBQVEsR0FBRyxpQkFBSyxDQUFDLEdBQUcsQ0FBQztRQUMxQixtQ0FBZ0IsQ0FBQyxTQUFTLENBQUMsZUFBZSxFQUFFLElBQUksQ0FBQyxNQUFNLENBQUMsV0FBVyxFQUFFLEVBQUU7WUFDbkUsS0FBSyxFQUFFLElBQUksQ0FBQyxNQUFNO1lBQ2xCLFFBQVEsRUFBRSxJQUFJLENBQUMsUUFBUSxHQUFHLElBQUksQ0FBQyxVQUFVO1NBQzVDLENBQUMsQ0FBQztRQUVILG1DQUFnQixDQUFDLGdCQUFnQixDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsUUFBUSxDQUFDLFNBQVMsRUFBRSxFQUFFLElBQUksQ0FBQyxNQUFNLENBQUMsV0FBVyxFQUFFLENBQUMsQ0FBQztJQUNuRyxDQUFDO0lBQ0wsNEJBQUM7QUFBRCxDQUFDLEFBdkNELElBdUNDO0FBdkNZLHNEQUFxQiJ9
  112309. /***/ }),
  112310. /* 56 */
  112311. /***/ (function(module, exports, __webpack_require__) {
  112312. "use strict";
  112313. Object.defineProperty(exports, "__esModule", { value: true });
  112314. /**
  112315. * A loder plugin to use MSFT_lod extension correctly (glTF)
  112316. */
  112317. var MSFTLodLoaderPlugin = /** @class */ (function () {
  112318. function MSFTLodLoaderPlugin() {
  112319. }
  112320. MSFTLodLoaderPlugin.prototype.onInit = function (loader, model) {
  112321. this._model = model;
  112322. };
  112323. MSFTLodLoaderPlugin.prototype.onExtensionLoaded = function (extension) {
  112324. if (extension.name === "MSFT_lod" && this._model.configuration.loaderConfiguration) {
  112325. var MSFT_lod = extension;
  112326. MSFT_lod.enabled = !!this._model.configuration.loaderConfiguration.progressiveLoading;
  112327. MSFT_lod.maxLODsToLoad = this._model.configuration.loaderConfiguration.maxLODsToLoad || Number.MAX_VALUE;
  112328. }
  112329. };
  112330. return MSFTLodLoaderPlugin;
  112331. }());
  112332. exports.MSFTLodLoaderPlugin = MSFTLodLoaderPlugin;
  112333. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibXNmdExvZExvYWRlclBsdWdpbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9tc2Z0TG9kTG9hZGVyUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBS0E7O0dBRUc7QUFDSDtJQUFBO0lBZUEsQ0FBQztJQVhVLG9DQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO0lBQ3hCLENBQUM7SUFFTSwrQ0FBaUIsR0FBeEIsVUFBeUIsU0FBK0I7UUFDcEQsSUFBSSxTQUFTLENBQUMsSUFBSSxLQUFLLFVBQVUsSUFBSSxJQUFJLENBQUMsTUFBTSxDQUFDLGFBQWEsQ0FBQyxtQkFBbUIsRUFBRTtZQUNoRixJQUFNLFFBQVEsR0FBRyxTQUFzQyxDQUFDO1lBQ3hELFFBQVEsQ0FBQyxPQUFPLEdBQUcsQ0FBQyxDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsYUFBYSxDQUFDLG1CQUFtQixDQUFDLGtCQUFrQixDQUFDO1lBQ3RGLFFBQVEsQ0FBQyxhQUFhLEdBQUcsSUFBSSxDQUFDLE1BQU0sQ0FBQyxhQUFhLENBQUMsbUJBQW1CLENBQUMsYUFBYSxJQUFJLE1BQU0sQ0FBQyxTQUFTLENBQUM7U0FDNUc7SUFDTCxDQUFDO0lBQ0wsMEJBQUM7QUFBRCxDQUFDLEFBZkQsSUFlQztBQWZZLGtEQUFtQiJ9
  112334. /***/ }),
  112335. /* 57 */
  112336. /***/ (function(module, exports, __webpack_require__) {
  112337. "use strict";
  112338. Object.defineProperty(exports, "__esModule", { value: true });
  112339. /**
  112340. * Force-apply material configuration right after a material was loaded.
  112341. */
  112342. var ApplyMaterialConfigPlugin = /** @class */ (function () {
  112343. function ApplyMaterialConfigPlugin() {
  112344. }
  112345. ApplyMaterialConfigPlugin.prototype.onInit = function (loader, model) {
  112346. this._model = model;
  112347. };
  112348. ApplyMaterialConfigPlugin.prototype.onMaterialLoaded = function (material) {
  112349. this._model && this._model._applyModelMaterialConfiguration(material);
  112350. };
  112351. return ApplyMaterialConfigPlugin;
  112352. }());
  112353. exports.ApplyMaterialConfigPlugin = ApplyMaterialConfigPlugin;
  112354. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBwbHlNYXRlcmlhbENvbmZpZy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9hcHBseU1hdGVyaWFsQ29uZmlnLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBS0E7O0dBRUc7QUFDSDtJQUFBO0lBV0EsQ0FBQztJQVBVLDBDQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO0lBQ3hCLENBQUM7SUFFTSxvREFBZ0IsR0FBdkIsVUFBd0IsUUFBa0I7UUFDdEMsSUFBSSxDQUFDLE1BQU0sSUFBSSxJQUFJLENBQUMsTUFBTSxDQUFDLGdDQUFnQyxDQUFDLFFBQVEsQ0FBQyxDQUFDO0lBQzFFLENBQUM7SUFDTCxnQ0FBQztBQUFELENBQUMsQUFYRCxJQVdDO0FBWFksOERBQXlCIn0=
  112355. /***/ }),
  112356. /* 58 */
  112357. /***/ (function(module, exports, __webpack_require__) {
  112358. "use strict";
  112359. Object.defineProperty(exports, "__esModule", { value: true });
  112360. var babylonjs_1 = __webpack_require__(0);
  112361. /**
  112362. * A (PBR) material will be extended using this function.
  112363. * This function will hold extra default configuration for the viewer, if not implemented in Babylon itself.
  112364. */
  112365. var ExtendedMaterialLoaderPlugin = /** @class */ (function () {
  112366. function ExtendedMaterialLoaderPlugin() {
  112367. }
  112368. ExtendedMaterialLoaderPlugin.prototype.onMaterialLoaded = function (baseMaterial) {
  112369. var material = baseMaterial;
  112370. material.alphaMode = babylonjs_1.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  112371. };
  112372. return ExtendedMaterialLoaderPlugin;
  112373. }());
  112374. exports.ExtendedMaterialLoaderPlugin = ExtendedMaterialLoaderPlugin;
  112375. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWRNYXRlcmlhbExvYWRlclBsdWdpbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9leHRlbmRlZE1hdGVyaWFsTG9hZGVyUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBRUEsdUNBQTRJO0FBRTVJOzs7R0FHRztBQUNIO0lBQUE7SUFNQSxDQUFDO0lBSlUsdURBQWdCLEdBQXZCLFVBQXdCLFlBQXNCO1FBQzFDLElBQUksUUFBUSxHQUFHLFlBQTJCLENBQUM7UUFDM0MsUUFBUSxDQUFDLFNBQVMsR0FBRyxrQkFBTSxDQUFDLDhCQUE4QixDQUFDO0lBQy9ELENBQUM7SUFDTCxtQ0FBQztBQUFELENBQUMsQUFORCxJQU1DO0FBTlksb0VBQTRCIn0=
  112376. /***/ }),
  112377. /* 59 */
  112378. /***/ (function(module, exports, __webpack_require__) {
  112379. "use strict";
  112380. Object.defineProperty(exports, "__esModule", { value: true });
  112381. var babylonjs_1 = __webpack_require__(0);
  112382. var ObservablesManager = /** @class */ (function () {
  112383. function ObservablesManager() {
  112384. this.onSceneInitObservable = new babylonjs_1.Observable();
  112385. this.onEngineInitObservable = new babylonjs_1.Observable();
  112386. this.onModelLoadedObservable = new babylonjs_1.Observable();
  112387. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  112388. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  112389. this.onModelAddedObservable = new babylonjs_1.Observable();
  112390. this.onModelRemovedObservable = new babylonjs_1.Observable();
  112391. this.onViewerInitDoneObservable = new babylonjs_1.Observable();
  112392. this.onLoaderInitObservable = new babylonjs_1.Observable();
  112393. this.onFrameRenderedObservable = new babylonjs_1.Observable();
  112394. }
  112395. ObservablesManager.prototype.dispose = function () {
  112396. this.onSceneInitObservable.clear();
  112397. this.onEngineInitObservable.clear();
  112398. this.onModelLoadedObservable.clear();
  112399. this.onModelLoadProgressObservable.clear();
  112400. this.onModelLoadErrorObservable.clear();
  112401. this.onModelAddedObservable.clear();
  112402. this.onModelRemovedObservable.clear();
  112403. this.onViewerInitDoneObservable.clear();
  112404. this.onLoaderInitObservable.clear();
  112405. this.onFrameRenderedObservable.clear();
  112406. };
  112407. return ObservablesManager;
  112408. }());
  112409. exports.ObservablesManager = ObservablesManager;
  112410. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoib2JzZXJ2YWJsZXNNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL21hbmFnZXJzL29ic2VydmFibGVzTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUE2SDtBQUc3SDtJQStDSTtRQUNJLElBQUksQ0FBQyxxQkFBcUIsR0FBRyxJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUM5QyxJQUFJLENBQUMsc0JBQXNCLEdBQUcsSUFBSSxzQkFBVSxFQUFFLENBQUM7UUFDL0MsSUFBSSxDQUFDLHVCQUF1Qix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BQUksQ0FBQyx5QkFBeUIsQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUMzQyxDQUFDO0lBRUwseUJBQUM7QUFBRCxDQUFDLEFBekVELElBeUVDO0FBekVZLGdEQUFrQiJ9
  112411. /***/ }),
  112412. /* 60 */
  112413. /***/ (function(module, exports, __webpack_require__) {
  112414. "use strict";
  112415. Object.defineProperty(exports, "__esModule", { value: true });
  112416. var babylonjs_1 = __webpack_require__(0);
  112417. var ConfigurationContainer = /** @class */ (function () {
  112418. function ConfigurationContainer() {
  112419. this.mainColor = babylonjs_1.Color3.White();
  112420. this.reflectionColor = babylonjs_1.Color3.White();
  112421. }
  112422. return ConfigurationContainer;
  112423. }());
  112424. exports.ConfigurationContainer = ConfigurationContainer;
  112425. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbkNvbnRhaW5lci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2NvbmZpZ3VyYXRpb25Db250YWluZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSx1Q0FBbUM7QUFFbkM7SUFBQTtRQU1XLGNBQVMsR0FBVyxrQkFBTSxDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ25DLG9CQUFlLEdBQVcsa0JBQU0sQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUNwRCxDQUFDO0lBQUQsNkJBQUM7QUFBRCxDQUFDLEFBUkQsSUFRQztBQVJZLHdEQUFzQiJ9
  112426. /***/ }),
  112427. /* 61 */
  112428. /***/ (function(module, exports, __webpack_require__) {
  112429. "use strict";
  112430. Object.defineProperty(exports, "__esModule", { value: true });
  112431. var babylonjs_1 = __webpack_require__(0);
  112432. var helper_1 = __webpack_require__(1);
  112433. var Handlebars = __webpack_require__(62);
  112434. var eventManager_1 = __webpack_require__(63);
  112435. var _1 = __webpack_require__(1);
  112436. /**
  112437. * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML.
  112438. * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer.
  112439. */
  112440. var TemplateManager = /** @class */ (function () {
  112441. function TemplateManager(containerElement) {
  112442. this.containerElement = containerElement;
  112443. this.templates = {};
  112444. this.onTemplateInit = new babylonjs_1.Observable();
  112445. this.onTemplateLoaded = new babylonjs_1.Observable();
  112446. this.onTemplateStateChange = new babylonjs_1.Observable();
  112447. this.onAllLoaded = new babylonjs_1.Observable();
  112448. this.onEventTriggered = new babylonjs_1.Observable();
  112449. this.eventManager = new eventManager_1.EventManager(this);
  112450. }
  112451. /**
  112452. * Initialize the template(s) for the viewer. Called bay the Viewer class
  112453. * @param templates the templates to be used to initialize the main template
  112454. */
  112455. TemplateManager.prototype.initTemplate = function (templates) {
  112456. var _this = this;
  112457. var internalInit = function (dependencyMap, name, parentTemplate) {
  112458. //init template
  112459. var template = _this.templates[name];
  112460. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  112461. return internalInit(dependencyMap[childName], childName, template);
  112462. });
  112463. // register the observers
  112464. //template.onLoaded.add(() => {
  112465. var addToParent = function () {
  112466. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  112467. template.appendTo(containingElement);
  112468. _this._checkLoadedState();
  112469. };
  112470. if (parentTemplate && !parentTemplate.parent) {
  112471. parentTemplate.onAppended.add(function () {
  112472. addToParent();
  112473. });
  112474. }
  112475. else {
  112476. addToParent();
  112477. }
  112478. //});
  112479. return template;
  112480. };
  112481. //build the html tree
  112482. return this._buildHTMLTree(templates).then(function (htmlTree) {
  112483. if (_this.templates['main']) {
  112484. internalInit(htmlTree, 'main');
  112485. }
  112486. else {
  112487. _this._checkLoadedState();
  112488. }
  112489. return;
  112490. });
  112491. };
  112492. /**
  112493. *
  112494. * This function will create a simple map with child-dependencies of the template html tree.
  112495. * It will compile each template, check if its children exist in the configuration and will add them if they do.
  112496. * It is expected that the main template will be called main!
  112497. *
  112498. * @param templates
  112499. */
  112500. TemplateManager.prototype._buildHTMLTree = function (templates) {
  112501. var _this = this;
  112502. var promises = Object.keys(templates).map(function (name) {
  112503. // if the template was overridden
  112504. if (!templates[name])
  112505. return Promise.resolve(false);
  112506. // else - we have a template, let's do our job!
  112507. var template = new Template(name, templates[name]);
  112508. template.onLoaded.add(function () {
  112509. _this.onTemplateLoaded.notifyObservers(template);
  112510. });
  112511. template.onStateChange.add(function () {
  112512. _this.onTemplateStateChange.notifyObservers(template);
  112513. });
  112514. _this.onTemplateInit.notifyObservers(template);
  112515. // make sure the global onEventTriggered is called as well
  112516. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  112517. _this.templates[name] = template;
  112518. return template.initPromise;
  112519. });
  112520. return Promise.all(promises).then(function () {
  112521. var templateStructure = {};
  112522. // now iterate through all templates and check for children:
  112523. var buildTree = function (parentObject, name) {
  112524. _this.templates[name].isInHtmlTree = true;
  112525. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  112526. childNodes.forEach(function (element) {
  112527. parentObject[element] = {};
  112528. buildTree(parentObject[element], element);
  112529. });
  112530. };
  112531. if (_this.templates['main']) {
  112532. buildTree(templateStructure, "main");
  112533. }
  112534. return templateStructure;
  112535. });
  112536. };
  112537. /**
  112538. * Get the canvas in the template tree.
  112539. * There must be one and only one canvas inthe template.
  112540. */
  112541. TemplateManager.prototype.getCanvas = function () {
  112542. return this.containerElement.querySelector('canvas');
  112543. };
  112544. /**
  112545. * Get a specific template from the template tree
  112546. * @param name the name of the template to load
  112547. */
  112548. TemplateManager.prototype.getTemplate = function (name) {
  112549. return this.templates[name];
  112550. };
  112551. TemplateManager.prototype._checkLoadedState = function () {
  112552. var _this = this;
  112553. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  112554. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  112555. });
  112556. if (done) {
  112557. this.onAllLoaded.notifyObservers(this);
  112558. }
  112559. };
  112560. /**
  112561. * Dispose the template manager
  112562. */
  112563. TemplateManager.prototype.dispose = function () {
  112564. var _this = this;
  112565. // dispose all templates
  112566. Object.keys(this.templates).forEach(function (template) {
  112567. _this.templates[template].dispose();
  112568. });
  112569. this.templates = {};
  112570. this.eventManager.dispose();
  112571. this.onTemplateInit.clear();
  112572. this.onAllLoaded.clear();
  112573. this.onEventTriggered.clear();
  112574. this.onTemplateLoaded.clear();
  112575. this.onTemplateStateChange.clear();
  112576. };
  112577. return TemplateManager;
  112578. }());
  112579. exports.TemplateManager = TemplateManager;
  112580. // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
  112581. Handlebars.registerHelper('eachInMap', function (map, block) {
  112582. var out = '';
  112583. Object.keys(map).map(function (prop) {
  112584. var data = map[prop];
  112585. if (typeof data === 'object') {
  112586. data.id = data.id || prop;
  112587. out += block.fn(data);
  112588. }
  112589. else {
  112590. out += block.fn({ id: prop, value: data });
  112591. }
  112592. });
  112593. return out;
  112594. });
  112595. Handlebars.registerHelper('add', function (a, b) {
  112596. var out = a + b;
  112597. return out;
  112598. });
  112599. Handlebars.registerHelper('eq', function (a, b) {
  112600. var out = (a == b);
  112601. return out;
  112602. });
  112603. Handlebars.registerHelper('or', function (a, b) {
  112604. var out = a || b;
  112605. return out;
  112606. });
  112607. Handlebars.registerHelper('not', function (a) {
  112608. var out = !a;
  112609. return out;
  112610. });
  112611. Handlebars.registerHelper('count', function (map) {
  112612. return map.length;
  112613. });
  112614. Handlebars.registerHelper('gt', function (a, b) {
  112615. var out = a > b;
  112616. return out;
  112617. });
  112618. /**
  112619. * This class represents a single template in the viewer's template tree.
  112620. * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar.
  112621. * A template is injected using the template manager in the correct position.
  112622. * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection)
  112623. *
  112624. * For further information please refer to the documentation page, https://doc.babylonjs.com
  112625. */
  112626. var Template = /** @class */ (function () {
  112627. function Template(name, _configuration) {
  112628. var _this = this;
  112629. this.name = name;
  112630. this._configuration = _configuration;
  112631. this.onLoaded = new babylonjs_1.Observable();
  112632. this.onAppended = new babylonjs_1.Observable();
  112633. this.onStateChange = new babylonjs_1.Observable();
  112634. this.onEventTriggered = new babylonjs_1.Observable();
  112635. this.loadRequests = [];
  112636. this.isLoaded = false;
  112637. this.isShown = false;
  112638. this.isInHtmlTree = false;
  112639. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  112640. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  112641. if (htmlTemplate) {
  112642. _this._htmlTemplate = htmlTemplate;
  112643. var compiledTemplate = Handlebars.compile(htmlTemplate, { noEscape: (_this._configuration.params && !!_this._configuration.params.noEscape) });
  112644. var config = _this._configuration.params || {};
  112645. _this._rawHtml = compiledTemplate(config);
  112646. try {
  112647. _this._fragment = document.createRange().createContextualFragment(_this._rawHtml);
  112648. }
  112649. catch (e) {
  112650. var test = document.createElement(_this.name);
  112651. test.innerHTML = _this._rawHtml;
  112652. _this._fragment = test;
  112653. }
  112654. _this.isLoaded = true;
  112655. _this.isShown = true;
  112656. _this.onLoaded.notifyObservers(_this);
  112657. }
  112658. return _this;
  112659. });
  112660. }
  112661. /**
  112662. * Some templates have parameters (like background color for example).
  112663. * The parameters are provided to Handlebars which in turn generates the template.
  112664. * This function will update the template with the new parameters
  112665. *
  112666. * Note that when updating parameters the events will be registered again (after being cleared).
  112667. *
  112668. * @param params the new template parameters
  112669. */
  112670. Template.prototype.updateParams = function (params, append) {
  112671. if (append === void 0) { append = true; }
  112672. if (append) {
  112673. this._configuration.params = _1.deepmerge(this._configuration.params, params);
  112674. }
  112675. else {
  112676. this._configuration.params = params;
  112677. }
  112678. // update the template
  112679. if (this.isLoaded) {
  112680. // this.dispose();
  112681. }
  112682. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  112683. var config = this._configuration.params || {};
  112684. this._rawHtml = compiledTemplate(config);
  112685. try {
  112686. this._fragment = document.createRange().createContextualFragment(this._rawHtml);
  112687. }
  112688. catch (e) {
  112689. var test = document.createElement(this.name);
  112690. test.innerHTML = this._rawHtml;
  112691. this._fragment = test;
  112692. }
  112693. if (this.parent) {
  112694. this.appendTo(this.parent, true);
  112695. }
  112696. };
  112697. Object.defineProperty(Template.prototype, "configuration", {
  112698. /**
  112699. * Get the template'S configuration
  112700. */
  112701. get: function () {
  112702. return this._configuration;
  112703. },
  112704. enumerable: true,
  112705. configurable: true
  112706. });
  112707. /**
  112708. * A template can be a parent element for other templates or HTML elements.
  112709. * This function will deliver all child HTML elements of this template.
  112710. */
  112711. Template.prototype.getChildElements = function () {
  112712. var childrenArray = [];
  112713. //Edge and IE don't support frage,ent.children
  112714. var children = this._fragment && this._fragment.children;
  112715. if (!this._fragment) {
  112716. var fragment = this.parent.querySelector(this.name);
  112717. if (fragment) {
  112718. children = fragment.querySelectorAll('*');
  112719. }
  112720. }
  112721. if (!children) {
  112722. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  112723. children = this._fragment.querySelectorAll('*');
  112724. }
  112725. for (var i = 0; i < children.length; ++i) {
  112726. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  112727. }
  112728. return childrenArray;
  112729. };
  112730. /**
  112731. * Appending the template to a parent HTML element.
  112732. * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true.
  112733. * @param parent the parent to which the template is added
  112734. * @param forceRemove if the parent already exists, shoud the template be removed from it?
  112735. */
  112736. Template.prototype.appendTo = function (parent, forceRemove) {
  112737. var _this = this;
  112738. if (this.parent) {
  112739. if (forceRemove && this._addedFragment) {
  112740. /*let fragement = this.parent.querySelector(this.name)
  112741. if (fragement)
  112742. this.parent.removeChild(fragement);*/
  112743. this.parent.innerHTML = '';
  112744. }
  112745. else {
  112746. return;
  112747. }
  112748. }
  112749. this.parent = parent;
  112750. if (this._configuration.id) {
  112751. this.parent.id = this._configuration.id;
  112752. }
  112753. if (this._fragment) {
  112754. this.parent.appendChild(this._fragment);
  112755. this._addedFragment = this._fragment;
  112756. }
  112757. else {
  112758. this.parent.insertAdjacentHTML("beforeend", this._rawHtml);
  112759. }
  112760. // appended only one frame after.
  112761. setTimeout(function () {
  112762. _this._registerEvents();
  112763. _this.onAppended.notifyObservers(_this);
  112764. });
  112765. };
  112766. /**
  112767. * Show the template using the provided visibilityFunction, or natively using display: flex.
  112768. * The provided function returns a promise that should be fullfilled when the element is shown.
  112769. * Since it is a promise async operations are more than possible.
  112770. * See the default viewer for an opacity example.
  112771. * @param visibilityFunction The function to execute to show the template.
  112772. */
  112773. Template.prototype.show = function (visibilityFunction) {
  112774. var _this = this;
  112775. if (this._isHiding)
  112776. return Promise.resolve(this);
  112777. return Promise.resolve().then(function () {
  112778. _this._isShowing = true;
  112779. if (visibilityFunction) {
  112780. return visibilityFunction(_this);
  112781. }
  112782. else {
  112783. // flex? box? should this be configurable easier than the visibilityFunction?
  112784. _this.parent.style.display = 'flex';
  112785. // support old browsers with no flex:
  112786. if (_this.parent.style.display !== 'flex') {
  112787. _this.parent.style.display = '';
  112788. }
  112789. return _this;
  112790. }
  112791. }).then(function () {
  112792. _this.isShown = true;
  112793. _this._isShowing = false;
  112794. _this.onStateChange.notifyObservers(_this);
  112795. return _this;
  112796. });
  112797. };
  112798. /**
  112799. * Hide the template using the provided visibilityFunction, or natively using display: none.
  112800. * The provided function returns a promise that should be fullfilled when the element is hidden.
  112801. * Since it is a promise async operations are more than possible.
  112802. * See the default viewer for an opacity example.
  112803. * @param visibilityFunction The function to execute to show the template.
  112804. */
  112805. Template.prototype.hide = function (visibilityFunction) {
  112806. var _this = this;
  112807. if (this._isShowing)
  112808. return Promise.resolve(this);
  112809. return Promise.resolve().then(function () {
  112810. _this._isHiding = true;
  112811. if (visibilityFunction) {
  112812. return visibilityFunction(_this);
  112813. }
  112814. else {
  112815. // flex? box? should this be configurable easier than the visibilityFunction?
  112816. _this.parent.style.display = 'none';
  112817. return _this;
  112818. }
  112819. }).then(function () {
  112820. _this.isShown = false;
  112821. _this._isHiding = false;
  112822. _this.onStateChange.notifyObservers(_this);
  112823. return _this;
  112824. });
  112825. };
  112826. /**
  112827. * Dispose this template
  112828. */
  112829. Template.prototype.dispose = function () {
  112830. this.onAppended.clear();
  112831. this.onEventTriggered.clear();
  112832. this.onLoaded.clear();
  112833. this.onStateChange.clear();
  112834. this.isLoaded = false;
  112835. // remove from parent
  112836. try {
  112837. this.parent.removeChild(this._fragment);
  112838. }
  112839. catch (e) {
  112840. //noop
  112841. }
  112842. this.loadRequests.forEach(function (request) {
  112843. request.abort();
  112844. });
  112845. if (this._registeredEvents) {
  112846. this._registeredEvents.forEach(function (evt) {
  112847. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  112848. });
  112849. }
  112850. delete this._fragment;
  112851. };
  112852. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  112853. var _this = this;
  112854. if (!templateConfig) {
  112855. return Promise.reject('No templateConfig provided');
  112856. }
  112857. else if (templateConfig.html !== undefined) {
  112858. return Promise.resolve(templateConfig.html);
  112859. }
  112860. else {
  112861. var location_1 = this._getTemplateLocation(templateConfig);
  112862. if (helper_1.isUrl(location_1)) {
  112863. return new Promise(function (resolve, reject) {
  112864. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  112865. resolve(data);
  112866. }, undefined, undefined, false, function (request, error) {
  112867. reject(error);
  112868. });
  112869. _this.loadRequests.push(fileRequest);
  112870. });
  112871. }
  112872. else {
  112873. location_1 = location_1.replace('#', '');
  112874. var element = document.getElementById(location_1);
  112875. if (element) {
  112876. return Promise.resolve(element.innerHTML);
  112877. }
  112878. else {
  112879. return Promise.reject('Template ID not found');
  112880. }
  112881. }
  112882. }
  112883. };
  112884. Template.prototype._registerEvents = function () {
  112885. var _this = this;
  112886. this._registeredEvents = this._registeredEvents || [];
  112887. if (this._registeredEvents.length) {
  112888. // first remove the registered events
  112889. this._registeredEvents.forEach(function (evt) {
  112890. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  112891. });
  112892. }
  112893. if (this._configuration.events) {
  112894. var _loop_1 = function (eventName) {
  112895. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  112896. var functionToFire_1 = function (selector, event) {
  112897. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  112898. };
  112899. // if boolean, set the parent as the event listener
  112900. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  112901. var selector = this_1.parent.id;
  112902. if (selector) {
  112903. selector = '#' + selector;
  112904. }
  112905. else {
  112906. selector = this_1.parent.tagName;
  112907. }
  112908. var binding = functionToFire_1.bind(this_1, selector);
  112909. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, selector), false);
  112910. this_1._registeredEvents.push({
  112911. htmlElement: this_1.parent,
  112912. eventName: eventName,
  112913. function: binding
  112914. });
  112915. }
  112916. else if (typeof this_1._configuration.events[eventName] === 'object') {
  112917. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  112918. // strict null checl is working incorrectly, must override:
  112919. var event_1 = this_1._configuration.events[eventName] || {};
  112920. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  112921. if (selector && selector.indexOf('#') !== 0) {
  112922. selector = '#' + selector;
  112923. }
  112924. var htmlElement = _this.parent.querySelector(selector);
  112925. if (htmlElement) {
  112926. var binding = functionToFire_1.bind(_this, selector);
  112927. htmlElement.addEventListener(eventName, binding, false);
  112928. _this._registeredEvents.push({
  112929. htmlElement: htmlElement,
  112930. eventName: eventName,
  112931. function: binding
  112932. });
  112933. }
  112934. });
  112935. }
  112936. }
  112937. };
  112938. var this_1 = this;
  112939. for (var eventName in this._configuration.events) {
  112940. _loop_1(eventName);
  112941. }
  112942. }
  112943. };
  112944. Template.prototype._getTemplateLocation = function (templateConfig) {
  112945. if (!templateConfig || typeof templateConfig === 'string') {
  112946. return templateConfig;
  112947. }
  112948. else {
  112949. return templateConfig.location;
  112950. }
  112951. };
  112952. return Template;
  112953. }());
  112954. exports.Template = Template;
  112955. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVtcGxhdGVNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3RlbXBsYXRpbmcvdGVtcGxhdGVNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQ0EsdUNBQTREO0FBQzVELG9DQUE4RDtBQUU5RCx1REFBeUQ7QUFDekQsK0NBQThDO0FBRTlDLCtCQUF1QztBQVl2Qzs7O0dBR0c7QUFDSDtJQThCSSx5QkFBbUIsZ0JBQTZCO1FBQTdCLHFCQUFnQixHQUFoQixnQkFBZ0IsQ0FBYTtRQUM1QyxJQUFJLENBQUMsU0FBUyxHQUFHLEVBQUUsQ0FBQztRQUVwQixJQUFJLENBQUMsY0FBYyxHQUFHLElBQUksc0JBQVUsRUFBWSxDQUFDO1FBQ2pELElBQUksQ0FBQyxnQkFBZ0IsR0FBRyxJQUFJLHNCQUFVLEVBQVksQ0FBQztRQUNuRCxJQUFJLENBQUMscUJBQXFCLEdBQUcsSUFBSSxzQkFBVSxFQUFZLENBQUM7UUFDeEQsSUFBSSxDQUFDLFdBQVcsR0FBRyxJQUFJLHNCQUFVLEVBQW1CLENBQUM7UUFDckQsSUFBSSxDQUFDLGdCQUFnQixHQUFHLElBQUksc0JBQVUsRUFBaUIsQ0FBQztRQUV4RCxJQUFJLENBQUMsWUFBWSxHQUFHLElBQUksMkJBQVksQ0FBQyxJQUFJLENBQUMsQ0FBQztJQUMvQyxDQUFDO0lBRUQ7OztPQUdHO0lBQ0ksc0NBQVksR0FBbkIsVUFBb0IsU0FBb0Q7UUFBeEUsaUJBdUNDO1FBckNHLElBQUksWUFBWSxHQUFHLFVBQUMsYUFBYSxFQUFFLElB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RyxRQUFRLENBQUM7NkJBQzdCOzRCQUNELElBQUksV0FBVyxHQUFnQixLQUFJLENBQUMsTUFBTSxDQUFDLGFBQWEsQ0FBQyxRQUFRLENBQUMsQ0FBQzs0QkFDbkUsSUFBSSxXQUFXLEVBQUU7Z0NBQ2IsSUFBSSxPQUFPLEdBQUcsZ0JBQWMsQ0FBQyxJQUFJLENBQUMsS0FBSSxFQUFFLFFBQVEsQ0FBQyxDQUFDO2dDQUNsRCxXQUFXLENBQUMsZ0JBQWdCLENBQUMsU0FBUyxFQUFFLE9BQU8sRUFBRSxLQUFLLENBQUMsQ0FBQztnQ0FDeEQsS0FBSSxDQUFDLGlCQUFpQixDQUFDLElBQUksQ0FBQztvQ0FDeEIsV0FBVyxFQUFFLFdBQVc7b0NBQ3hCLFNBQVMsRUFBRSxTQUFTO29DQUNwQixRQUFRLEVBQUUsT0FBTztpQ0FDcEIsQ0FBQyxDQUFDOzZCQUNOO3dCQUNMLENBQUMsQ0FBQyxDQUFDO3FCQUNOO2lCQUNKO1lBQ0wsQ0FBQzs7WUExQ0QsS0FBSyxJQUFJLFNBQVMsSUFBSSxJQUFJLENBQUMsY0FBYyxDQUFDLE1BQU07d0JBQXZDLFNBQVM7YUEwQ2pCO1NBQ0o7SUFDTCxDQUFDO0lBRU8sdUNBQW9CLEdBQTVCLFVBQTZCLGNBQWM7UUFDdkMsSUFBSSxDQUFDLGNBQWMsSUFBSSxPQUFPLGNBQWMsS0FBSyxRQUFRLEVBQUU7WUFDdkQsT0FBTyxjQUFjLENBQUM7U0FDekI7YUFBTTtZQUNILE9BQU8sY0FBYyxDQUFDLFFBQVEsQ0FBQztTQUNsQztJQUNMLENBQUM7SUFDTCxlQUFDO0FBQUQsQ0FBQyxBQS9XRCxJQStXQztBQS9XWSw0QkFBUSJ9
  112956. /***/ }),
  112957. /* 62 */
  112958. /***/ (function(module, exports, __webpack_require__) {
  112959. /**!
  112960. @license
  112961. handlebars v4.0.11
  112962. Copyright (C) 2011-2017 by Yehuda Katz
  112963. Permission is hereby granted, free of charge, to any person obtaining a copy
  112964. of this software and associated documentation files (the "Software"), to deal
  112965. in the Software without restriction, including without limitation the rights
  112966. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  112967. copies of the Software, and to permit persons to whom the Software is
  112968. furnished to do so, subject to the following conditions:
  112969. The above copyright notice and this permission notice shall be included in
  112970. all copies or substantial portions of the Software.
  112971. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  112972. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  112973. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  112974. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  112975. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  112976. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  112977. THE SOFTWARE.
  112978. */
  112979. (function webpackUniversalModuleDefinition(root, factory) {
  112980. if(true)
  112981. module.exports = factory();
  112982. else if(typeof define === 'function' && define.amd)
  112983. define([], factory);
  112984. else if(typeof exports === 'object')
  112985. exports["Handlebars"] = factory();
  112986. else
  112987. root["Handlebars"] = factory();
  112988. })(this, function() {
  112989. return /******/ (function(modules) { // webpackBootstrap
  112990. /******/ // The module cache
  112991. /******/ var installedModules = {};
  112992. /******/ // The require function
  112993. /******/ function __webpack_require__(moduleId) {
  112994. /******/ // Check if module is in cache
  112995. /******/ if(installedModules[moduleId])
  112996. /******/ return installedModules[moduleId].exports;
  112997. /******/ // Create a new module (and put it into the cache)
  112998. /******/ var module = installedModules[moduleId] = {
  112999. /******/ exports: {},
  113000. /******/ id: moduleId,
  113001. /******/ loaded: false
  113002. /******/ };
  113003. /******/ // Execute the module function
  113004. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  113005. /******/ // Flag the module as loaded
  113006. /******/ module.loaded = true;
  113007. /******/ // Return the exports of the module
  113008. /******/ return module.exports;
  113009. /******/ }
  113010. /******/ // expose the modules object (__webpack_modules__)
  113011. /******/ __webpack_require__.m = modules;
  113012. /******/ // expose the module cache
  113013. /******/ __webpack_require__.c = installedModules;
  113014. /******/ // __webpack_public_path__
  113015. /******/ __webpack_require__.p = "";
  113016. /******/ // Load entry module and return exports
  113017. /******/ return __webpack_require__(0);
  113018. /******/ })
  113019. /************************************************************************/
  113020. /******/ ([
  113021. /* 0 */
  113022. /***/ (function(module, exports, __webpack_require__) {
  113023. 'use strict';
  113024. var _interopRequireDefault = __webpack_require__(1)['default'];
  113025. exports.__esModule = true;
  113026. var _handlebarsRuntime = __webpack_require__(2);
  113027. var _handlebarsRuntime2 = _interopRequireDefault(_handlebarsRuntime);
  113028. // Compiler imports
  113029. var _handlebarsCompilerAst = __webpack_require__(35);
  113030. var _handlebarsCompilerAst2 = _interopRequireDefault(_handlebarsCompilerAst);
  113031. var _handlebarsCompilerBase = __webpack_require__(36);
  113032. var _handlebarsCompilerCompiler = __webpack_require__(41);
  113033. var _handlebarsCompilerJavascriptCompiler = __webpack_require__(42);
  113034. var _handlebarsCompilerJavascriptCompiler2 = _interopRequireDefault(_handlebarsCompilerJavascriptCompiler);
  113035. var _handlebarsCompilerVisitor = __webpack_require__(39);
  113036. var _handlebarsCompilerVisitor2 = _interopRequireDefault(_handlebarsCompilerVisitor);
  113037. var _handlebarsNoConflict = __webpack_require__(34);
  113038. var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
  113039. var _create = _handlebarsRuntime2['default'].create;
  113040. function create() {
  113041. var hb = _create();
  113042. hb.compile = function (input, options) {
  113043. return _handlebarsCompilerCompiler.compile(input, options, hb);
  113044. };
  113045. hb.precompile = function (input, options) {
  113046. return _handlebarsCompilerCompiler.precompile(input, options, hb);
  113047. };
  113048. hb.AST = _handlebarsCompilerAst2['default'];
  113049. hb.Compiler = _handlebarsCompilerCompiler.Compiler;
  113050. hb.JavaScriptCompiler = _handlebarsCompilerJavascriptCompiler2['default'];
  113051. hb.Parser = _handlebarsCompilerBase.parser;
  113052. hb.parse = _handlebarsCompilerBase.parse;
  113053. return hb;
  113054. }
  113055. var inst = create();
  113056. inst.create = create;
  113057. _handlebarsNoConflict2['default'](inst);
  113058. inst.Visitor = _handlebarsCompilerVisitor2['default'];
  113059. inst['default'] = inst;
  113060. exports['default'] = inst;
  113061. module.exports = exports['default'];
  113062. /***/ }),
  113063. /* 1 */
  113064. /***/ (function(module, exports) {
  113065. "use strict";
  113066. exports["default"] = function (obj) {
  113067. return obj && obj.__esModule ? obj : {
  113068. "default": obj
  113069. };
  113070. };
  113071. exports.__esModule = true;
  113072. /***/ }),
  113073. /* 2 */
  113074. /***/ (function(module, exports, __webpack_require__) {
  113075. 'use strict';
  113076. var _interopRequireWildcard = __webpack_require__(3)['default'];
  113077. var _interopRequireDefault = __webpack_require__(1)['default'];
  113078. exports.__esModule = true;
  113079. var _handlebarsBase = __webpack_require__(4);
  113080. var base = _interopRequireWildcard(_handlebarsBase);
  113081. // Each of these augment the Handlebars object. No need to setup here.
  113082. // (This is done to easily share code between commonjs and browse envs)
  113083. var _handlebarsSafeString = __webpack_require__(21);
  113084. var _handlebarsSafeString2 = _interopRequireDefault(_handlebarsSafeString);
  113085. var _handlebarsException = __webpack_require__(6);
  113086. var _handlebarsException2 = _interopRequireDefault(_handlebarsException);
  113087. var _handlebarsUtils = __webpack_require__(5);
  113088. var Utils = _interopRequireWildcard(_handlebarsUtils);
  113089. var _handlebarsRuntime = __webpack_require__(22);
  113090. var runtime = _interopRequireWildcard(_handlebarsRuntime);
  113091. var _handlebarsNoConflict = __webpack_require__(34);
  113092. var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
  113093. // For compatibility and usage outside of module systems, make the Handlebars object a namespace
  113094. function create() {
  113095. var hb = new base.HandlebarsEnvironment();
  113096. Utils.extend(hb, base);
  113097. hb.SafeString = _handlebarsSafeString2['default'];
  113098. hb.Exception = _handlebarsException2['default'];
  113099. hb.Utils = Utils;
  113100. hb.escapeExpression = Utils.escapeExpression;
  113101. hb.VM = runtime;
  113102. hb.template = function (spec) {
  113103. return runtime.template(spec, hb);
  113104. };
  113105. return hb;
  113106. }
  113107. var inst = create();
  113108. inst.create = create;
  113109. _handlebarsNoConflict2['default'](inst);
  113110. inst['default'] = inst;
  113111. exports['default'] = inst;
  113112. module.exports = exports['default'];
  113113. /***/ }),
  113114. /* 3 */
  113115. /***/ (function(module, exports) {
  113116. "use strict";
  113117. exports["default"] = function (obj) {
  113118. if (obj && obj.__esModule) {
  113119. return obj;
  113120. } else {
  113121. var newObj = {};
  113122. if (obj != null) {
  113123. for (var key in obj) {
  113124. if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
  113125. }
  113126. }
  113127. newObj["default"] = obj;
  113128. return newObj;
  113129. }
  113130. };
  113131. exports.__esModule = true;
  113132. /***/ }),
  113133. /* 4 */
  113134. /***/ (function(module, exports, __webpack_require__) {
  113135. 'use strict';
  113136. var _interopRequireDefault = __webpack_require__(1)['default'];
  113137. exports.__esModule = true;
  113138. exports.HandlebarsEnvironment = HandlebarsEnvironment;
  113139. var _utils = __webpack_require__(5);
  113140. var _exception = __webpack_require__(6);
  113141. var _exception2 = _interopRequireDefault(_exception);
  113142. var _helpers = __webpack_require__(10);
  113143. var _decorators = __webpack_require__(18);
  113144. var _logger = __webpack_require__(20);
  113145. var _logger2 = _interopRequireDefault(_logger);
  113146. var VERSION = '4.0.11';
  113147. exports.VERSION = VERSION;
  113148. var COMPILER_REVISION = 7;
  113149. exports.COMPILER_REVISION = COMPILER_REVISION;
  113150. var REVISION_CHANGES = {
  113151. 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it
  113152. 2: '== 1.0.0-rc.3',
  113153. 3: '== 1.0.0-rc.4',
  113154. 4: '== 1.x.x',
  113155. 5: '== 2.0.0-alpha.x',
  113156. 6: '>= 2.0.0-beta.1',
  113157. 7: '>= 4.0.0'
  113158. };
  113159. exports.REVISION_CHANGES = REVISION_CHANGES;
  113160. var objectType = '[object Object]';
  113161. function HandlebarsEnvironment(helpers, partials, decorators) {
  113162. this.helpers = helpers || {};
  113163. this.partials = partials || {};
  113164. this.decorators = decorators || {};
  113165. _helpers.registerDefaultHelpers(this);
  113166. _decorators.registerDefaultDecorators(this);
  113167. }
  113168. HandlebarsEnvironment.prototype = {
  113169. constructor: HandlebarsEnvironment,
  113170. logger: _logger2['default'],
  113171. log: _logger2['default'].log,
  113172. registerHelper: function registerHelper(name, fn) {
  113173. if (_utils.toString.call(name) === objectType) {
  113174. if (fn) {
  113175. throw new _exception2['default']('Arg not supported with multiple helpers');
  113176. }
  113177. _utils.extend(this.helpers, name);
  113178. } else {
  113179. this.helpers[name] = fn;
  113180. }
  113181. },
  113182. unregisterHelper: function unregisterHelper(name) {
  113183. delete this.helpers[name];
  113184. },
  113185. registerPartial: function registerPartial(name, partial) {
  113186. if (_utils.toString.call(name) === objectType) {
  113187. _utils.extend(this.partials, name);
  113188. } else {
  113189. if (typeof partial === 'undefined') {
  113190. throw new _exception2['default']('Attempting to register a partial called "' + name + '" as undefined');
  113191. }
  113192. this.partials[name] = partial;
  113193. }
  113194. },
  113195. unregisterPartial: function unregisterPartial(name) {
  113196. delete this.partials[name];
  113197. },
  113198. registerDecorator: function registerDecorator(name, fn) {
  113199. if (_utils.toString.call(name) === objectType) {
  113200. if (fn) {
  113201. throw new _exception2['default']('Arg not supported with multiple decorators');
  113202. }
  113203. _utils.extend(this.decorators, name);
  113204. } else {
  113205. this.decorators[name] = fn;
  113206. }
  113207. },
  113208. unregisterDecorator: function unregisterDecorator(name) {
  113209. delete this.decorators[name];
  113210. }
  113211. };
  113212. var log = _logger2['default'].log;
  113213. exports.log = log;
  113214. exports.createFrame = _utils.createFrame;
  113215. exports.logger = _logger2['default'];
  113216. /***/ }),
  113217. /* 5 */
  113218. /***/ (function(module, exports) {
  113219. 'use strict';
  113220. exports.__esModule = true;
  113221. exports.extend = extend;
  113222. exports.indexOf = indexOf;
  113223. exports.escapeExpression = escapeExpression;
  113224. exports.isEmpty = isEmpty;
  113225. exports.createFrame = createFrame;
  113226. exports.blockParams = blockParams;
  113227. exports.appendContextPath = appendContextPath;
  113228. var escape = {
  113229. '&': '&amp;',
  113230. '<': '&lt;',
  113231. '>': '&gt;',
  113232. '"': '&quot;',
  113233. "'": '&#x27;',
  113234. '`': '&#x60;',
  113235. '=': '&#x3D;'
  113236. };
  113237. var badChars = /[&<>"'`=]/g,
  113238. possible = /[&<>"'`=]/;
  113239. function escapeChar(chr) {
  113240. return escape[chr];
  113241. }
  113242. function extend(obj /* , ...source */) {
  113243. for (var i = 1; i < arguments.length; i++) {
  113244. for (var key in arguments[i]) {
  113245. if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
  113246. obj[key] = arguments[i][key];
  113247. }
  113248. }
  113249. }
  113250. return obj;
  113251. }
  113252. var toString = Object.prototype.toString;
  113253. exports.toString = toString;
  113254. // Sourced from lodash
  113255. // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt
  113256. /* eslint-disable func-style */
  113257. var isFunction = function isFunction(value) {
  113258. return typeof value === 'function';
  113259. };
  113260. // fallback for older versions of Chrome and Safari
  113261. /* istanbul ignore next */
  113262. if (isFunction(/x/)) {
  113263. exports.isFunction = isFunction = function (value) {
  113264. return typeof value === 'function' && toString.call(value) === '[object Function]';
  113265. };
  113266. }
  113267. exports.isFunction = isFunction;
  113268. /* eslint-enable func-style */
  113269. /* istanbul ignore next */
  113270. var isArray = Array.isArray || function (value) {
  113271. return value && typeof value === 'object' ? toString.call(value) === '[object Array]' : false;
  113272. };
  113273. exports.isArray = isArray;
  113274. // Older IE versions do not directly support indexOf so we must implement our own, sadly.
  113275. function indexOf(array, value) {
  113276. for (var i = 0, len = array.length; i < len; i++) {
  113277. if (array[i] === value) {
  113278. return i;
  113279. }
  113280. }
  113281. return -1;
  113282. }
  113283. function escapeExpression(string) {
  113284. if (typeof string !== 'string') {
  113285. // don't escape SafeStrings, since they're already safe
  113286. if (string && string.toHTML) {
  113287. return string.toHTML();
  113288. } else if (string == null) {
  113289. return '';
  113290. } else if (!string) {
  113291. return string + '';
  113292. }
  113293. // Force a string conversion as this will be done by the append regardless and
  113294. // the regex test will do this transparently behind the scenes, causing issues if
  113295. // an object's to string has escaped characters in it.
  113296. string = '' + string;
  113297. }
  113298. if (!possible.test(string)) {
  113299. return string;
  113300. }
  113301. return string.replace(badChars, escapeChar);
  113302. }
  113303. function isEmpty(value) {
  113304. if (!value && value !== 0) {
  113305. return true;
  113306. } else if (isArray(value) && value.length === 0) {
  113307. return true;
  113308. } else {
  113309. return false;
  113310. }
  113311. }
  113312. function createFrame(object) {
  113313. var frame = extend({}, object);
  113314. frame._parent = object;
  113315. return frame;
  113316. }
  113317. function blockParams(params, ids) {
  113318. params.path = ids;
  113319. return params;
  113320. }
  113321. function appendContextPath(contextPath, id) {
  113322. return (contextPath ? contextPath + '.' : '') + id;
  113323. }
  113324. /***/ }),
  113325. /* 6 */
  113326. /***/ (function(module, exports, __webpack_require__) {
  113327. 'use strict';
  113328. var _Object$defineProperty = __webpack_require__(7)['default'];
  113329. exports.__esModule = true;
  113330. var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack'];
  113331. function Exception(message, node) {
  113332. var loc = node && node.loc,
  113333. line = undefined,
  113334. column = undefined;
  113335. if (loc) {
  113336. line = loc.start.line;
  113337. column = loc.start.column;
  113338. message += ' - ' + line + ':' + column;
  113339. }
  113340. var tmp = Error.prototype.constructor.call(this, message);
  113341. // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work.
  113342. for (var idx = 0; idx < errorProps.length; idx++) {
  113343. this[errorProps[idx]] = tmp[errorProps[idx]];
  113344. }
  113345. /* istanbul ignore else */
  113346. if (Error.captureStackTrace) {
  113347. Error.captureStackTrace(this, Exception);
  113348. }
  113349. try {
  113350. if (loc) {
  113351. this.lineNumber = line;
  113352. // Work around issue under safari where we can't directly set the column value
  113353. /* istanbul ignore next */
  113354. if (_Object$defineProperty) {
  113355. Object.defineProperty(this, 'column', {
  113356. value: column,
  113357. enumerable: true
  113358. });
  113359. } else {
  113360. this.column = column;
  113361. }
  113362. }
  113363. } catch (nop) {
  113364. /* Ignore if the browser is very particular */
  113365. }
  113366. }
  113367. Exception.prototype = new Error();
  113368. exports['default'] = Exception;
  113369. module.exports = exports['default'];
  113370. /***/ }),
  113371. /* 7 */
  113372. /***/ (function(module, exports, __webpack_require__) {
  113373. module.exports = { "default": __webpack_require__(8), __esModule: true };
  113374. /***/ }),
  113375. /* 8 */
  113376. /***/ (function(module, exports, __webpack_require__) {
  113377. var $ = __webpack_require__(9);
  113378. module.exports = function defineProperty(it, key, desc){
  113379. return $.setDesc(it, key, desc);
  113380. };
  113381. /***/ }),
  113382. /* 9 */
  113383. /***/ (function(module, exports) {
  113384. var $Object = Object;
  113385. module.exports = {
  113386. create: $Object.create,
  113387. getProto: $Object.getPrototypeOf,
  113388. isEnum: {}.propertyIsEnumerable,
  113389. getDesc: $Object.getOwnPropertyDescriptor,
  113390. setDesc: $Object.defineProperty,
  113391. setDescs: $Object.defineProperties,
  113392. getKeys: $Object.keys,
  113393. getNames: $Object.getOwnPropertyNames,
  113394. getSymbols: $Object.getOwnPropertySymbols,
  113395. each: [].forEach
  113396. };
  113397. /***/ }),
  113398. /* 10 */
  113399. /***/ (function(module, exports, __webpack_require__) {
  113400. 'use strict';
  113401. var _interopRequireDefault = __webpack_require__(1)['default'];
  113402. exports.__esModule = true;
  113403. exports.registerDefaultHelpers = registerDefaultHelpers;
  113404. var _helpersBlockHelperMissing = __webpack_require__(11);
  113405. var _helpersBlockHelperMissing2 = _interopRequireDefault(_helpersBlockHelperMissing);
  113406. var _helpersEach = __webpack_require__(12);
  113407. var _helpersEach2 = _interopRequireDefault(_helpersEach);
  113408. var _helpersHelperMissing = __webpack_require__(13);
  113409. var _helpersHelperMissing2 = _interopRequireDefault(_helpersHelperMissing);
  113410. var _helpersIf = __webpack_require__(14);
  113411. var _helpersIf2 = _interopRequireDefault(_helpersIf);
  113412. var _helpersLog = __webpack_require__(15);
  113413. var _helpersLog2 = _interopRequireDefault(_helpersLog);
  113414. var _helpersLookup = __webpack_require__(16);
  113415. var _helpersLookup2 = _interopRequireDefault(_helpersLookup);
  113416. var _helpersWith = __webpack_require__(17);
  113417. var _helpersWith2 = _interopRequireDefault(_helpersWith);
  113418. function registerDefaultHelpers(instance) {
  113419. _helpersBlockHelperMissing2['default'](instance);
  113420. _helpersEach2['default'](instance);
  113421. _helpersHelperMissing2['default'](instance);
  113422. _helpersIf2['default'](instance);
  113423. _helpersLog2['default'](instance);
  113424. _helpersLookup2['default'](instance);
  113425. _helpersWith2['default'](instance);
  113426. }
  113427. /***/ }),
  113428. /* 11 */
  113429. /***/ (function(module, exports, __webpack_require__) {
  113430. 'use strict';
  113431. exports.__esModule = true;
  113432. var _utils = __webpack_require__(5);
  113433. exports['default'] = function (instance) {
  113434. instance.registerHelper('blockHelperMissing', function (context, options) {
  113435. var inverse = options.inverse,
  113436. fn = options.fn;
  113437. if (context === true) {
  113438. return fn(this);
  113439. } else if (context === false || context == null) {
  113440. return inverse(this);
  113441. } else if (_utils.isArray(context)) {
  113442. if (context.length > 0) {
  113443. if (options.ids) {
  113444. options.ids = [options.name];
  113445. }
  113446. return instance.helpers.each(context, options);
  113447. } else {
  113448. return inverse(this);
  113449. }
  113450. } else {
  113451. if (options.data && options.ids) {
  113452. var data = _utils.createFrame(options.data);
  113453. data.contextPath = _utils.appendContextPath(options.data.contextPath, options.name);
  113454. options = { data: data };
  113455. }
  113456. return fn(context, options);
  113457. }
  113458. });
  113459. };
  113460. module.exports = exports['default'];
  113461. /***/ }),
  113462. /* 12 */
  113463. /***/ (function(module, exports, __webpack_require__) {
  113464. 'use strict';
  113465. var _interopRequireDefault = __webpack_require__(1)['default'];
  113466. exports.__esModule = true;
  113467. var _utils = __webpack_require__(5);
  113468. var _exception = __webpack_require__(6);
  113469. var _exception2 = _interopRequireDefault(_exception);
  113470. exports['default'] = function (instance) {
  113471. instance.registerHelper('each', function (context, options) {
  113472. if (!options) {
  113473. throw new _exception2['default']('Must pass iterator to #each');
  113474. }
  113475. var fn = options.fn,
  113476. inverse = options.inverse,
  113477. i = 0,
  113478. ret = '',
  113479. data = undefined,
  113480. contextPath = undefined;
  113481. if (options.data && options.ids) {
  113482. contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]) + '.';
  113483. }
  113484. if (_utils.isFunction(context)) {
  113485. context = context.call(this);
  113486. }
  113487. if (options.data) {
  113488. data = _utils.createFrame(options.data);
  113489. }
  113490. function execIteration(field, index, last) {
  113491. if (data) {
  113492. data.key = field;
  113493. data.index = index;
  113494. data.first = index === 0;
  113495. data.last = !!last;
  113496. if (contextPath) {
  113497. data.contextPath = contextPath + field;
  113498. }
  113499. }
  113500. ret = ret + fn(context[field], {
  113501. data: data,
  113502. blockParams: _utils.blockParams([context[field], field], [contextPath + field, null])
  113503. });
  113504. }
  113505. if (context && typeof context === 'object') {
  113506. if (_utils.isArray(context)) {
  113507. for (var j = context.length; i < j; i++) {
  113508. if (i in context) {
  113509. execIteration(i, i, i === context.length - 1);
  113510. }
  113511. }
  113512. } else {
  113513. var priorKey = undefined;
  113514. for (var key in context) {
  113515. if (context.hasOwnProperty(key)) {
  113516. // We're running the iterations one step out of sync so we can detect
  113517. // the last iteration without have to scan the object twice and create
  113518. // an itermediate keys array.
  113519. if (priorKey !== undefined) {
  113520. execIteration(priorKey, i - 1);
  113521. }
  113522. priorKey = key;
  113523. i++;
  113524. }
  113525. }
  113526. if (priorKey !== undefined) {
  113527. execIteration(priorKey, i - 1, true);
  113528. }
  113529. }
  113530. }
  113531. if (i === 0) {
  113532. ret = inverse(this);
  113533. }
  113534. return ret;
  113535. });
  113536. };
  113537. module.exports = exports['default'];
  113538. /***/ }),
  113539. /* 13 */
  113540. /***/ (function(module, exports, __webpack_require__) {
  113541. 'use strict';
  113542. var _interopRequireDefault = __webpack_require__(1)['default'];
  113543. exports.__esModule = true;
  113544. var _exception = __webpack_require__(6);
  113545. var _exception2 = _interopRequireDefault(_exception);
  113546. exports['default'] = function (instance) {
  113547. instance.registerHelper('helperMissing', function () /* [args, ]options */{
  113548. if (arguments.length === 1) {
  113549. // A missing field in a {{foo}} construct.
  113550. return undefined;
  113551. } else {
  113552. // Someone is actually trying to call something, blow up.
  113553. throw new _exception2['default']('Missing helper: "' + arguments[arguments.length - 1].name + '"');
  113554. }
  113555. });
  113556. };
  113557. module.exports = exports['default'];
  113558. /***/ }),
  113559. /* 14 */
  113560. /***/ (function(module, exports, __webpack_require__) {
  113561. 'use strict';
  113562. exports.__esModule = true;
  113563. var _utils = __webpack_require__(5);
  113564. exports['default'] = function (instance) {
  113565. instance.registerHelper('if', function (conditional, options) {
  113566. if (_utils.isFunction(conditional)) {
  113567. conditional = conditional.call(this);
  113568. }
  113569. // Default behavior is to render the positive path if the value is truthy and not empty.
  113570. // The `includeZero` option may be set to treat the condtional as purely not empty based on the
  113571. // behavior of isEmpty. Effectively this determines if 0 is handled by the positive path or negative.
  113572. if (!options.hash.includeZero && !conditional || _utils.isEmpty(conditional)) {
  113573. return options.inverse(this);
  113574. } else {
  113575. return options.fn(this);
  113576. }
  113577. });
  113578. instance.registerHelper('unless', function (conditional, options) {
  113579. return instance.helpers['if'].call(this, conditional, { fn: options.inverse, inverse: options.fn, hash: options.hash });
  113580. });
  113581. };
  113582. module.exports = exports['default'];
  113583. /***/ }),
  113584. /* 15 */
  113585. /***/ (function(module, exports) {
  113586. 'use strict';
  113587. exports.__esModule = true;
  113588. exports['default'] = function (instance) {
  113589. instance.registerHelper('log', function () /* message, options */{
  113590. var args = [undefined],
  113591. options = arguments[arguments.length - 1];
  113592. for (var i = 0; i < arguments.length - 1; i++) {
  113593. args.push(arguments[i]);
  113594. }
  113595. var level = 1;
  113596. if (options.hash.level != null) {
  113597. level = options.hash.level;
  113598. } else if (options.data && options.data.level != null) {
  113599. level = options.data.level;
  113600. }
  113601. args[0] = level;
  113602. instance.log.apply(instance, args);
  113603. });
  113604. };
  113605. module.exports = exports['default'];
  113606. /***/ }),
  113607. /* 16 */
  113608. /***/ (function(module, exports) {
  113609. 'use strict';
  113610. exports.__esModule = true;
  113611. exports['default'] = function (instance) {
  113612. instance.registerHelper('lookup', function (obj, field) {
  113613. return obj && obj[field];
  113614. });
  113615. };
  113616. module.exports = exports['default'];
  113617. /***/ }),
  113618. /* 17 */
  113619. /***/ (function(module, exports, __webpack_require__) {
  113620. 'use strict';
  113621. exports.__esModule = true;
  113622. var _utils = __webpack_require__(5);
  113623. exports['default'] = function (instance) {
  113624. instance.registerHelper('with', function (context, options) {
  113625. if (_utils.isFunction(context)) {
  113626. context = context.call(this);
  113627. }
  113628. var fn = options.fn;
  113629. if (!_utils.isEmpty(context)) {
  113630. var data = options.data;
  113631. if (options.data && options.ids) {
  113632. data = _utils.createFrame(options.data);
  113633. data.contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]);
  113634. }
  113635. return fn(context, {
  113636. data: data,
  113637. blockParams: _utils.blockParams([context], [data && data.contextPath])
  113638. });
  113639. } else {
  113640. return options.inverse(this);
  113641. }
  113642. });
  113643. };
  113644. module.exports = exports['default'];
  113645. /***/ }),
  113646. /* 18 */
  113647. /***/ (function(module, exports, __webpack_require__) {
  113648. 'use strict';
  113649. var _interopRequireDefault = __webpack_require__(1)['default'];
  113650. exports.__esModule = true;
  113651. exports.registerDefaultDecorators = registerDefaultDecorators;
  113652. var _decoratorsInline = __webpack_require__(19);
  113653. var _decoratorsInline2 = _interopRequireDefault(_decoratorsInline);
  113654. function registerDefaultDecorators(instance) {
  113655. _decoratorsInline2['default'](instance);
  113656. }
  113657. /***/ }),
  113658. /* 19 */
  113659. /***/ (function(module, exports, __webpack_require__) {
  113660. 'use strict';
  113661. exports.__esModule = true;
  113662. var _utils = __webpack_require__(5);
  113663. exports['default'] = function (instance) {
  113664. instance.registerDecorator('inline', function (fn, props, container, options) {
  113665. var ret = fn;
  113666. if (!props.partials) {
  113667. props.partials = {};
  113668. ret = function (context, options) {
  113669. // Create a new partials stack frame prior to exec.
  113670. var original = container.partials;
  113671. container.partials = _utils.extend({}, original, props.partials);
  113672. var ret = fn(context, options);
  113673. container.partials = original;
  113674. return ret;
  113675. };
  113676. }
  113677. props.partials[options.args[0]] = options.fn;
  113678. return ret;
  113679. });
  113680. };
  113681. module.exports = exports['default'];
  113682. /***/ }),
  113683. /* 20 */
  113684. /***/ (function(module, exports, __webpack_require__) {
  113685. 'use strict';
  113686. exports.__esModule = true;
  113687. var _utils = __webpack_require__(5);
  113688. var logger = {
  113689. methodMap: ['debug', 'info', 'warn', 'error'],
  113690. level: 'info',
  113691. // Maps a given level value to the `methodMap` indexes above.
  113692. lookupLevel: function lookupLevel(level) {
  113693. if (typeof level === 'string') {
  113694. var levelMap = _utils.indexOf(logger.methodMap, level.toLowerCase());
  113695. if (levelMap >= 0) {
  113696. level = levelMap;
  113697. } else {
  113698. level = parseInt(level, 10);
  113699. }
  113700. }
  113701. return level;
  113702. },
  113703. // Can be overridden in the host environment
  113704. log: function log(level) {
  113705. level = logger.lookupLevel(level);
  113706. if (typeof console !== 'undefined' && logger.lookupLevel(logger.level) <= level) {
  113707. var method = logger.methodMap[level];
  113708. if (!console[method]) {
  113709. // eslint-disable-line no-console
  113710. method = 'log';
  113711. }
  113712. for (var _len = arguments.length, message = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  113713. message[_key - 1] = arguments[_key];
  113714. }
  113715. console[method].apply(console, message); // eslint-disable-line no-console
  113716. }
  113717. }
  113718. };
  113719. exports['default'] = logger;
  113720. module.exports = exports['default'];
  113721. /***/ }),
  113722. /* 21 */
  113723. /***/ (function(module, exports) {
  113724. // Build out our basic SafeString type
  113725. 'use strict';
  113726. exports.__esModule = true;
  113727. function SafeString(string) {
  113728. this.string = string;
  113729. }
  113730. SafeString.prototype.toString = SafeString.prototype.toHTML = function () {
  113731. return '' + this.string;
  113732. };
  113733. exports['default'] = SafeString;
  113734. module.exports = exports['default'];
  113735. /***/ }),
  113736. /* 22 */
  113737. /***/ (function(module, exports, __webpack_require__) {
  113738. 'use strict';
  113739. var _Object$seal = __webpack_require__(23)['default'];
  113740. var _interopRequireWildcard = __webpack_require__(3)['default'];
  113741. var _interopRequireDefault = __webpack_require__(1)['default'];
  113742. exports.__esModule = true;
  113743. exports.checkRevision = checkRevision;
  113744. exports.template = template;
  113745. exports.wrapProgram = wrapProgram;
  113746. exports.resolvePartial = resolvePartial;
  113747. exports.invokePartial = invokePartial;
  113748. exports.noop = noop;
  113749. var _utils = __webpack_require__(5);
  113750. var Utils = _interopRequireWildcard(_utils);
  113751. var _exception = __webpack_require__(6);
  113752. var _exception2 = _interopRequireDefault(_exception);
  113753. var _base = __webpack_require__(4);
  113754. function checkRevision(compilerInfo) {
  113755. var compilerRevision = compilerInfo && compilerInfo[0] || 1,
  113756. currentRevision = _base.COMPILER_REVISION;
  113757. if (compilerRevision !== currentRevision) {
  113758. if (compilerRevision < currentRevision) {
  113759. var runtimeVersions = _base.REVISION_CHANGES[currentRevision],
  113760. compilerVersions = _base.REVISION_CHANGES[compilerRevision];
  113761. throw new _exception2['default']('Template was precompiled with an older version of Handlebars than the current runtime. ' + 'Please update your precompiler to a newer version (' + runtimeVersions + ') or downgrade your runtime to an older version (' + compilerVersions + ').');
  113762. } else {
  113763. // Use the embedded version info since the runtime doesn't know about this revision yet
  113764. throw new _exception2['default']('Template was precompiled with a newer version of Handlebars than the current runtime. ' + 'Please update your runtime to a newer version (' + compilerInfo[1] + ').');
  113765. }
  113766. }
  113767. }
  113768. function template(templateSpec, env) {
  113769. /* istanbul ignore next */
  113770. if (!env) {
  113771. throw new _exception2['default']('No environment passed to template');
  113772. }
  113773. if (!templateSpec || !templateSpec.main) {
  113774. throw new _exception2['default']('Unknown template object: ' + typeof templateSpec);
  113775. }
  113776. templateSpec.main.decorator = templateSpec.main_d;
  113777. // Note: Using env.VM references rather than local var references throughout this section to allow
  113778. // for external users to override these as psuedo-supported APIs.
  113779. env.VM.checkRevision(templateSpec.compiler);
  113780. function invokePartialWrapper(partial, context, options) {
  113781. if (options.hash) {
  113782. context = Utils.extend({}, context, options.hash);
  113783. if (options.ids) {
  113784. options.ids[0] = true;
  113785. }
  113786. }
  113787. partial = env.VM.resolvePartial.call(this, partial, context, options);
  113788. var result = env.VM.invokePartial.call(this, partial, context, options);
  113789. if (result == null && env.compile) {
  113790. options.partials[options.name] = env.compile(partial, templateSpec.compilerOptions, env);
  113791. result = options.partials[options.name](context, options);
  113792. }
  113793. if (result != null) {
  113794. if (options.indent) {
  113795. var lines = result.split('\n');
  113796. for (var i = 0, l = lines.length; i < l; i++) {
  113797. if (!lines[i] && i + 1 === l) {
  113798. break;
  113799. }
  113800. lines[i] = options.indent + lines[i];
  113801. }
  113802. result = lines.join('\n');
  113803. }
  113804. return result;
  113805. } else {
  113806. throw new _exception2['default']('The partial ' + options.name + ' could not be compiled when running in runtime-only mode');
  113807. }
  113808. }
  113809. // Just add water
  113810. var container = {
  113811. strict: function strict(obj, name) {
  113812. if (!(name in obj)) {
  113813. throw new _exception2['default']('"' + name + '" not defined in ' + obj);
  113814. }
  113815. return obj[name];
  113816. },
  113817. lookup: function lookup(depths, name) {
  113818. var len = depths.length;
  113819. for (var i = 0; i < len; i++) {
  113820. if (depths[i] && depths[i][name] != null) {
  113821. return depths[i][name];
  113822. }
  113823. }
  113824. },
  113825. lambda: function lambda(current, context) {
  113826. return typeof current === 'function' ? current.call(context) : current;
  113827. },
  113828. escapeExpression: Utils.escapeExpression,
  113829. invokePartial: invokePartialWrapper,
  113830. fn: function fn(i) {
  113831. var ret = templateSpec[i];
  113832. ret.decorator = templateSpec[i + '_d'];
  113833. return ret;
  113834. },
  113835. programs: [],
  113836. program: function program(i, data, declaredBlockParams, blockParams, depths) {
  113837. var programWrapper = this.programs[i],
  113838. fn = this.fn(i);
  113839. if (data || depths || blockParams || declaredBlockParams) {
  113840. programWrapper = wrapProgram(this, i, fn, data, declaredBlockParams, blockParams, depths);
  113841. } else if (!programWrapper) {
  113842. programWrapper = this.programs[i] = wrapProgram(this, i, fn);
  113843. }
  113844. return programWrapper;
  113845. },
  113846. data: function data(value, depth) {
  113847. while (value && depth--) {
  113848. value = value._parent;
  113849. }
  113850. return value;
  113851. },
  113852. merge: function merge(param, common) {
  113853. var obj = param || common;
  113854. if (param && common && param !== common) {
  113855. obj = Utils.extend({}, common, param);
  113856. }
  113857. return obj;
  113858. },
  113859. // An empty object to use as replacement for null-contexts
  113860. nullContext: _Object$seal({}),
  113861. noop: env.VM.noop,
  113862. compilerInfo: templateSpec.compiler
  113863. };
  113864. function ret(context) {
  113865. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  113866. var data = options.data;
  113867. ret._setup(options);
  113868. if (!options.partial && templateSpec.useData) {
  113869. data = initData(context, data);
  113870. }
  113871. var depths = undefined,
  113872. blockParams = templateSpec.useBlockParams ? [] : undefined;
  113873. if (templateSpec.useDepths) {
  113874. if (options.depths) {
  113875. depths = context != options.depths[0] ? [context].concat(options.depths) : options.depths;
  113876. } else {
  113877. depths = [context];
  113878. }
  113879. }
  113880. function main(context /*, options*/) {
  113881. return '' + templateSpec.main(container, context, container.helpers, container.partials, data, blockParams, depths);
  113882. }
  113883. main = executeDecorators(templateSpec.main, main, container, options.depths || [], data, blockParams);
  113884. return main(context, options);
  113885. }
  113886. ret.isTop = true;
  113887. ret._setup = function (options) {
  113888. if (!options.partial) {
  113889. container.helpers = container.merge(options.helpers, env.helpers);
  113890. if (templateSpec.usePartial) {
  113891. container.partials = container.merge(options.partials, env.partials);
  113892. }
  113893. if (templateSpec.usePartial || templateSpec.useDecorators) {
  113894. container.decorators = container.merge(options.decorators, env.decorators);
  113895. }
  113896. } else {
  113897. container.helpers = options.helpers;
  113898. container.partials = options.partials;
  113899. container.decorators = options.decorators;
  113900. }
  113901. };
  113902. ret._child = function (i, data, blockParams, depths) {
  113903. if (templateSpec.useBlockParams && !blockParams) {
  113904. throw new _exception2['default']('must pass block params');
  113905. }
  113906. if (templateSpec.useDepths && !depths) {
  113907. throw new _exception2['default']('must pass parent depths');
  113908. }
  113909. return wrapProgram(container, i, templateSpec[i], data, 0, blockParams, depths);
  113910. };
  113911. return ret;
  113912. }
  113913. function wrapProgram(container, i, fn, data, declaredBlockParams, blockParams, depths) {
  113914. function prog(context) {
  113915. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  113916. var currentDepths = depths;
  113917. if (depths && context != depths[0] && !(context === container.nullContext && depths[0] === null)) {
  113918. currentDepths = [context].concat(depths);
  113919. }
  113920. return fn(container, context, container.helpers, container.partials, options.data || data, blockParams && [options.blockParams].concat(blockParams), currentDepths);
  113921. }
  113922. prog = executeDecorators(fn, prog, container, depths, data, blockParams);
  113923. prog.program = i;
  113924. prog.depth = depths ? depths.length : 0;
  113925. prog.blockParams = declaredBlockParams || 0;
  113926. return prog;
  113927. }
  113928. function resolvePartial(partial, context, options) {
  113929. if (!partial) {
  113930. if (options.name === '@partial-block') {
  113931. partial = options.data['partial-block'];
  113932. } else {
  113933. partial = options.partials[options.name];
  113934. }
  113935. } else if (!partial.call && !options.name) {
  113936. // This is a dynamic partial that returned a string
  113937. options.name = partial;
  113938. partial = options.partials[partial];
  113939. }
  113940. return partial;
  113941. }
  113942. function invokePartial(partial, context, options) {
  113943. // Use the current closure context to save the partial-block if this partial
  113944. var currentPartialBlock = options.data && options.data['partial-block'];
  113945. options.partial = true;
  113946. if (options.ids) {
  113947. options.data.contextPath = options.ids[0] || options.data.contextPath;
  113948. }
  113949. var partialBlock = undefined;
  113950. if (options.fn && options.fn !== noop) {
  113951. (function () {
  113952. options.data = _base.createFrame(options.data);
  113953. // Wrapper function to get access to currentPartialBlock from the closure
  113954. var fn = options.fn;
  113955. partialBlock = options.data['partial-block'] = function partialBlockWrapper(context) {
  113956. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  113957. // Restore the partial-block from the closure for the execution of the block
  113958. // i.e. the part inside the block of the partial call.
  113959. options.data = _base.createFrame(options.data);
  113960. options.data['partial-block'] = currentPartialBlock;
  113961. return fn(context, options);
  113962. };
  113963. if (fn.partials) {
  113964. options.partials = Utils.extend({}, options.partials, fn.partials);
  113965. }
  113966. })();
  113967. }
  113968. if (partial === undefined && partialBlock) {
  113969. partial = partialBlock;
  113970. }
  113971. if (partial === undefined) {
  113972. throw new _exception2['default']('The partial ' + options.name + ' could not be found');
  113973. } else if (partial instanceof Function) {
  113974. return partial(context, options);
  113975. }
  113976. }
  113977. function noop() {
  113978. return '';
  113979. }
  113980. function initData(context, data) {
  113981. if (!data || !('root' in data)) {
  113982. data = data ? _base.createFrame(data) : {};
  113983. data.root = context;
  113984. }
  113985. return data;
  113986. }
  113987. function executeDecorators(fn, prog, container, depths, data, blockParams) {
  113988. if (fn.decorator) {
  113989. var props = {};
  113990. prog = fn.decorator(prog, props, container, depths && depths[0], data, blockParams, depths);
  113991. Utils.extend(prog, props);
  113992. }
  113993. return prog;
  113994. }
  113995. /***/ }),
  113996. /* 23 */
  113997. /***/ (function(module, exports, __webpack_require__) {
  113998. module.exports = { "default": __webpack_require__(24), __esModule: true };
  113999. /***/ }),
  114000. /* 24 */
  114001. /***/ (function(module, exports, __webpack_require__) {
  114002. __webpack_require__(25);
  114003. module.exports = __webpack_require__(30).Object.seal;
  114004. /***/ }),
  114005. /* 25 */
  114006. /***/ (function(module, exports, __webpack_require__) {
  114007. // 19.1.2.17 Object.seal(O)
  114008. var isObject = __webpack_require__(26);
  114009. __webpack_require__(27)('seal', function($seal){
  114010. return function seal(it){
  114011. return $seal && isObject(it) ? $seal(it) : it;
  114012. };
  114013. });
  114014. /***/ }),
  114015. /* 26 */
  114016. /***/ (function(module, exports) {
  114017. module.exports = function(it){
  114018. return typeof it === 'object' ? it !== null : typeof it === 'function';
  114019. };
  114020. /***/ }),
  114021. /* 27 */
  114022. /***/ (function(module, exports, __webpack_require__) {
  114023. // most Object methods by ES6 should accept primitives
  114024. var $export = __webpack_require__(28)
  114025. , core = __webpack_require__(30)
  114026. , fails = __webpack_require__(33);
  114027. module.exports = function(KEY, exec){
  114028. var fn = (core.Object || {})[KEY] || Object[KEY]
  114029. , exp = {};
  114030. exp[KEY] = exec(fn);
  114031. $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
  114032. };
  114033. /***/ }),
  114034. /* 28 */
  114035. /***/ (function(module, exports, __webpack_require__) {
  114036. var global = __webpack_require__(29)
  114037. , core = __webpack_require__(30)
  114038. , ctx = __webpack_require__(31)
  114039. , PROTOTYPE = 'prototype';
  114040. var $export = function(type, name, source){
  114041. var IS_FORCED = type & $export.F
  114042. , IS_GLOBAL = type & $export.G
  114043. , IS_STATIC = type & $export.S
  114044. , IS_PROTO = type & $export.P
  114045. , IS_BIND = type & $export.B
  114046. , IS_WRAP = type & $export.W
  114047. , exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
  114048. , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
  114049. , key, own, out;
  114050. if(IS_GLOBAL)source = name;
  114051. for(key in source){
  114052. // contains in native
  114053. own = !IS_FORCED && target && key in target;
  114054. if(own && key in exports)continue;
  114055. // export native or passed
  114056. out = own ? target[key] : source[key];
  114057. // prevent global pollution for namespaces
  114058. exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
  114059. // bind timers to global for call from export context
  114060. : IS_BIND && own ? ctx(out, global)
  114061. // wrap global constructors for prevent change them in library
  114062. : IS_WRAP && target[key] == out ? (function(C){
  114063. var F = function(param){
  114064. return this instanceof C ? new C(param) : C(param);
  114065. };
  114066. F[PROTOTYPE] = C[PROTOTYPE];
  114067. return F;
  114068. // make static versions for prototype methods
  114069. })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
  114070. if(IS_PROTO)(exports[PROTOTYPE] || (exports[PROTOTYPE] = {}))[key] = out;
  114071. }
  114072. };
  114073. // type bitmap
  114074. $export.F = 1; // forced
  114075. $export.G = 2; // global
  114076. $export.S = 4; // static
  114077. $export.P = 8; // proto
  114078. $export.B = 16; // bind
  114079. $export.W = 32; // wrap
  114080. module.exports = $export;
  114081. /***/ }),
  114082. /* 29 */
  114083. /***/ (function(module, exports) {
  114084. // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
  114085. var global = module.exports = typeof window != 'undefined' && window.Math == Math
  114086. ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
  114087. if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
  114088. /***/ }),
  114089. /* 30 */
  114090. /***/ (function(module, exports) {
  114091. var core = module.exports = {version: '1.2.6'};
  114092. if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
  114093. /***/ }),
  114094. /* 31 */
  114095. /***/ (function(module, exports, __webpack_require__) {
  114096. // optional / simple context binding
  114097. var aFunction = __webpack_require__(32);
  114098. module.exports = function(fn, that, length){
  114099. aFunction(fn);
  114100. if(that === undefined)return fn;
  114101. switch(length){
  114102. case 1: return function(a){
  114103. return fn.call(that, a);
  114104. };
  114105. case 2: return function(a, b){
  114106. return fn.call(that, a, b);
  114107. };
  114108. case 3: return function(a, b, c){
  114109. return fn.call(that, a, b, c);
  114110. };
  114111. }
  114112. return function(/* ...args */){
  114113. return fn.apply(that, arguments);
  114114. };
  114115. };
  114116. /***/ }),
  114117. /* 32 */
  114118. /***/ (function(module, exports) {
  114119. module.exports = function(it){
  114120. if(typeof it != 'function')throw TypeError(it + ' is not a function!');
  114121. return it;
  114122. };
  114123. /***/ }),
  114124. /* 33 */
  114125. /***/ (function(module, exports) {
  114126. module.exports = function(exec){
  114127. try {
  114128. return !!exec();
  114129. } catch(e){
  114130. return true;
  114131. }
  114132. };
  114133. /***/ }),
  114134. /* 34 */
  114135. /***/ (function(module, exports) {
  114136. /* WEBPACK VAR INJECTION */(function(global) {/* global window */
  114137. 'use strict';
  114138. exports.__esModule = true;
  114139. exports['default'] = function (Handlebars) {
  114140. /* istanbul ignore next */
  114141. var root = typeof global !== 'undefined' ? global : window,
  114142. $Handlebars = root.Handlebars;
  114143. /* istanbul ignore next */
  114144. Handlebars.noConflict = function () {
  114145. if (root.Handlebars === Handlebars) {
  114146. root.Handlebars = $Handlebars;
  114147. }
  114148. return Handlebars;
  114149. };
  114150. };
  114151. module.exports = exports['default'];
  114152. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
  114153. /***/ }),
  114154. /* 35 */
  114155. /***/ (function(module, exports) {
  114156. 'use strict';
  114157. exports.__esModule = true;
  114158. var AST = {
  114159. // Public API used to evaluate derived attributes regarding AST nodes
  114160. helpers: {
  114161. // a mustache is definitely a helper if:
  114162. // * it is an eligible helper, and
  114163. // * it has at least one parameter or hash segment
  114164. helperExpression: function helperExpression(node) {
  114165. return node.type === 'SubExpression' || (node.type === 'MustacheStatement' || node.type === 'BlockStatement') && !!(node.params && node.params.length || node.hash);
  114166. },
  114167. scopedId: function scopedId(path) {
  114168. return (/^\.|this\b/.test(path.original)
  114169. );
  114170. },
  114171. // an ID is simple if it only has one part, and that part is not
  114172. // `..` or `this`.
  114173. simpleId: function simpleId(path) {
  114174. return path.parts.length === 1 && !AST.helpers.scopedId(path) && !path.depth;
  114175. }
  114176. }
  114177. };
  114178. // Must be exported as an object rather than the root of the module as the jison lexer
  114179. // must modify the object to operate properly.
  114180. exports['default'] = AST;
  114181. module.exports = exports['default'];
  114182. /***/ }),
  114183. /* 36 */
  114184. /***/ (function(module, exports, __webpack_require__) {
  114185. 'use strict';
  114186. var _interopRequireDefault = __webpack_require__(1)['default'];
  114187. var _interopRequireWildcard = __webpack_require__(3)['default'];
  114188. exports.__esModule = true;
  114189. exports.parse = parse;
  114190. var _parser = __webpack_require__(37);
  114191. var _parser2 = _interopRequireDefault(_parser);
  114192. var _whitespaceControl = __webpack_require__(38);
  114193. var _whitespaceControl2 = _interopRequireDefault(_whitespaceControl);
  114194. var _helpers = __webpack_require__(40);
  114195. var Helpers = _interopRequireWildcard(_helpers);
  114196. var _utils = __webpack_require__(5);
  114197. exports.parser = _parser2['default'];
  114198. var yy = {};
  114199. _utils.extend(yy, Helpers);
  114200. function parse(input, options) {
  114201. // Just return if an already-compiled AST was passed in.
  114202. if (input.type === 'Program') {
  114203. return input;
  114204. }
  114205. _parser2['default'].yy = yy;
  114206. // Altering the shared object here, but this is ok as parser is a sync operation
  114207. yy.locInfo = function (locInfo) {
  114208. return new yy.SourceLocation(options && options.srcName, locInfo);
  114209. };
  114210. var strip = new _whitespaceControl2['default'](options);
  114211. return strip.accept(_parser2['default'].parse(input));
  114212. }
  114213. /***/ }),
  114214. /* 37 */
  114215. /***/ (function(module, exports) {
  114216. // File ignored in coverage tests via setting in .istanbul.yml
  114217. /* Jison generated parser */
  114218. "use strict";
  114219. exports.__esModule = true;
  114220. var handlebars = (function () {
  114221. var parser = { trace: function trace() {},
  114222. yy: {},
  114223. 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 },
  114224. 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" },
  114225. 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]],
  114226. performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$
  114227. /**/) {
  114228. var $0 = $$.length - 1;
  114229. switch (yystate) {
  114230. case 1:
  114231. return $$[$0 - 1];
  114232. break;
  114233. case 2:
  114234. this.$ = yy.prepareProgram($$[$0]);
  114235. break;
  114236. case 3:
  114237. this.$ = $$[$0];
  114238. break;
  114239. case 4:
  114240. this.$ = $$[$0];
  114241. break;
  114242. case 5:
  114243. this.$ = $$[$0];
  114244. break;
  114245. case 6:
  114246. this.$ = $$[$0];
  114247. break;
  114248. case 7:
  114249. this.$ = $$[$0];
  114250. break;
  114251. case 8:
  114252. this.$ = $$[$0];
  114253. break;
  114254. case 9:
  114255. this.$ = {
  114256. type: 'CommentStatement',
  114257. value: yy.stripComment($$[$0]),
  114258. strip: yy.stripFlags($$[$0], $$[$0]),
  114259. loc: yy.locInfo(this._$)
  114260. };
  114261. break;
  114262. case 10:
  114263. this.$ = {
  114264. type: 'ContentStatement',
  114265. original: $$[$0],
  114266. value: $$[$0],
  114267. loc: yy.locInfo(this._$)
  114268. };
  114269. break;
  114270. case 11:
  114271. this.$ = yy.prepareRawBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
  114272. break;
  114273. case 12:
  114274. this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1] };
  114275. break;
  114276. case 13:
  114277. this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], false, this._$);
  114278. break;
  114279. case 14:
  114280. this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], true, this._$);
  114281. break;
  114282. case 15:
  114283. this.$ = { open: $$[$0 - 5], path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  114284. break;
  114285. case 16:
  114286. this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  114287. break;
  114288. case 17:
  114289. this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  114290. break;
  114291. case 18:
  114292. this.$ = { strip: yy.stripFlags($$[$0 - 1], $$[$0 - 1]), program: $$[$0] };
  114293. break;
  114294. case 19:
  114295. var inverse = yy.prepareBlock($$[$0 - 2], $$[$0 - 1], $$[$0], $$[$0], false, this._$),
  114296. program = yy.prepareProgram([inverse], $$[$0 - 1].loc);
  114297. program.chained = true;
  114298. this.$ = { strip: $$[$0 - 2].strip, program: program, chain: true };
  114299. break;
  114300. case 20:
  114301. this.$ = $$[$0];
  114302. break;
  114303. case 21:
  114304. this.$ = { path: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 2], $$[$0]) };
  114305. break;
  114306. case 22:
  114307. this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
  114308. break;
  114309. case 23:
  114310. this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
  114311. break;
  114312. case 24:
  114313. this.$ = {
  114314. type: 'PartialStatement',
  114315. name: $$[$0 - 3],
  114316. params: $$[$0 - 2],
  114317. hash: $$[$0 - 1],
  114318. indent: '',
  114319. strip: yy.stripFlags($$[$0 - 4], $$[$0]),
  114320. loc: yy.locInfo(this._$)
  114321. };
  114322. break;
  114323. case 25:
  114324. this.$ = yy.preparePartialBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
  114325. break;
  114326. case 26:
  114327. this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 4], $$[$0]) };
  114328. break;
  114329. case 27:
  114330. this.$ = $$[$0];
  114331. break;
  114332. case 28:
  114333. this.$ = $$[$0];
  114334. break;
  114335. case 29:
  114336. this.$ = {
  114337. type: 'SubExpression',
  114338. path: $$[$0 - 3],
  114339. params: $$[$0 - 2],
  114340. hash: $$[$0 - 1],
  114341. loc: yy.locInfo(this._$)
  114342. };
  114343. break;
  114344. case 30:
  114345. this.$ = { type: 'Hash', pairs: $$[$0], loc: yy.locInfo(this._$) };
  114346. break;
  114347. case 31:
  114348. this.$ = { type: 'HashPair', key: yy.id($$[$0 - 2]), value: $$[$0], loc: yy.locInfo(this._$) };
  114349. break;
  114350. case 32:
  114351. this.$ = yy.id($$[$0 - 1]);
  114352. break;
  114353. case 33:
  114354. this.$ = $$[$0];
  114355. break;
  114356. case 34:
  114357. this.$ = $$[$0];
  114358. break;
  114359. case 35:
  114360. this.$ = { type: 'StringLiteral', value: $$[$0], original: $$[$0], loc: yy.locInfo(this._$) };
  114361. break;
  114362. case 36:
  114363. this.$ = { type: 'NumberLiteral', value: Number($$[$0]), original: Number($$[$0]), loc: yy.locInfo(this._$) };
  114364. break;
  114365. case 37:
  114366. this.$ = { type: 'BooleanLiteral', value: $$[$0] === 'true', original: $$[$0] === 'true', loc: yy.locInfo(this._$) };
  114367. break;
  114368. case 38:
  114369. this.$ = { type: 'UndefinedLiteral', original: undefined, value: undefined, loc: yy.locInfo(this._$) };
  114370. break;
  114371. case 39:
  114372. this.$ = { type: 'NullLiteral', original: null, value: null, loc: yy.locInfo(this._$) };
  114373. break;
  114374. case 40:
  114375. this.$ = $$[$0];
  114376. break;
  114377. case 41:
  114378. this.$ = $$[$0];
  114379. break;
  114380. case 42:
  114381. this.$ = yy.preparePath(true, $$[$0], this._$);
  114382. break;
  114383. case 43:
  114384. this.$ = yy.preparePath(false, $$[$0], this._$);
  114385. break;
  114386. case 44:
  114387. $$[$0 - 2].push({ part: yy.id($$[$0]), original: $$[$0], separator: $$[$0 - 1] });this.$ = $$[$0 - 2];
  114388. break;
  114389. case 45:
  114390. this.$ = [{ part: yy.id($$[$0]), original: $$[$0] }];
  114391. break;
  114392. case 46:
  114393. this.$ = [];
  114394. break;
  114395. case 47:
  114396. $$[$0 - 1].push($$[$0]);
  114397. break;
  114398. case 48:
  114399. this.$ = [$$[$0]];
  114400. break;
  114401. case 49:
  114402. $$[$0 - 1].push($$[$0]);
  114403. break;
  114404. case 50:
  114405. this.$ = [];
  114406. break;
  114407. case 51:
  114408. $$[$0 - 1].push($$[$0]);
  114409. break;
  114410. case 58:
  114411. this.$ = [];
  114412. break;
  114413. case 59:
  114414. $$[$0 - 1].push($$[$0]);
  114415. break;
  114416. case 64:
  114417. this.$ = [];
  114418. break;
  114419. case 65:
  114420. $$[$0 - 1].push($$[$0]);
  114421. break;
  114422. case 70:
  114423. this.$ = [];
  114424. break;
  114425. case 71:
  114426. $$[$0 - 1].push($$[$0]);
  114427. break;
  114428. case 78:
  114429. this.$ = [];
  114430. break;
  114431. case 79:
  114432. $$[$0 - 1].push($$[$0]);
  114433. break;
  114434. case 82:
  114435. this.$ = [];
  114436. break;
  114437. case 83:
  114438. $$[$0 - 1].push($$[$0]);
  114439. break;
  114440. case 86:
  114441. this.$ = [];
  114442. break;
  114443. case 87:
  114444. $$[$0 - 1].push($$[$0]);
  114445. break;
  114446. case 90:
  114447. this.$ = [];
  114448. break;
  114449. case 91:
  114450. $$[$0 - 1].push($$[$0]);
  114451. break;
  114452. case 94:
  114453. this.$ = [];
  114454. break;
  114455. case 95:
  114456. $$[$0 - 1].push($$[$0]);
  114457. break;
  114458. case 98:
  114459. this.$ = [$$[$0]];
  114460. break;
  114461. case 99:
  114462. $$[$0 - 1].push($$[$0]);
  114463. break;
  114464. case 100:
  114465. this.$ = [$$[$0]];
  114466. break;
  114467. case 101:
  114468. $$[$0 - 1].push($$[$0]);
  114469. break;
  114470. }
  114471. },
  114472. 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], 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] }],
  114473. 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] },
  114474. parseError: function parseError(str, hash) {
  114475. throw new Error(str);
  114476. },
  114477. parse: function parse(input) {
  114478. var self = this,
  114479. stack = [0],
  114480. vstack = [null],
  114481. lstack = [],
  114482. table = this.table,
  114483. yytext = "",
  114484. yylineno = 0,
  114485. yyleng = 0,
  114486. recovering = 0,
  114487. TERROR = 2,
  114488. EOF = 1;
  114489. this.lexer.setInput(input);
  114490. this.lexer.yy = this.yy;
  114491. this.yy.lexer = this.lexer;
  114492. this.yy.parser = this;
  114493. if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {};
  114494. var yyloc = this.lexer.yylloc;
  114495. lstack.push(yyloc);
  114496. var ranges = this.lexer.options && this.lexer.options.ranges;
  114497. if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError;
  114498. function popStack(n) {
  114499. stack.length = stack.length - 2 * n;
  114500. vstack.length = vstack.length - n;
  114501. lstack.length = lstack.length - n;
  114502. }
  114503. function lex() {
  114504. var token;
  114505. token = self.lexer.lex() || 1;
  114506. if (typeof token !== "number") {
  114507. token = self.symbols_[token] || token;
  114508. }
  114509. return token;
  114510. }
  114511. var symbol,
  114512. preErrorSymbol,
  114513. state,
  114514. action,
  114515. a,
  114516. r,
  114517. yyval = {},
  114518. p,
  114519. len,
  114520. newState,
  114521. expected;
  114522. while (true) {
  114523. state = stack[stack.length - 1];
  114524. if (this.defaultActions[state]) {
  114525. action = this.defaultActions[state];
  114526. } else {
  114527. if (symbol === null || typeof symbol == "undefined") {
  114528. symbol = lex();
  114529. }
  114530. action = table[state] && table[state][symbol];
  114531. }
  114532. if (typeof action === "undefined" || !action.length || !action[0]) {
  114533. var errStr = "";
  114534. if (!recovering) {
  114535. expected = [];
  114536. for (p in table[state]) if (this.terminals_[p] && p > 2) {
  114537. expected.push("'" + this.terminals_[p] + "'");
  114538. }
  114539. if (this.lexer.showPosition) {
  114540. errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'";
  114541. } else {
  114542. errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1 ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'");
  114543. }
  114544. this.parseError(errStr, { text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected });
  114545. }
  114546. }
  114547. if (action[0] instanceof Array && action.length > 1) {
  114548. throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol);
  114549. }
  114550. switch (action[0]) {
  114551. case 1:
  114552. stack.push(symbol);
  114553. vstack.push(this.lexer.yytext);
  114554. lstack.push(this.lexer.yylloc);
  114555. stack.push(action[1]);
  114556. symbol = null;
  114557. if (!preErrorSymbol) {
  114558. yyleng = this.lexer.yyleng;
  114559. yytext = this.lexer.yytext;
  114560. yylineno = this.lexer.yylineno;
  114561. yyloc = this.lexer.yylloc;
  114562. if (recovering > 0) recovering--;
  114563. } else {
  114564. symbol = preErrorSymbol;
  114565. preErrorSymbol = null;
  114566. }
  114567. break;
  114568. case 2:
  114569. len = this.productions_[action[1]][1];
  114570. yyval.$ = vstack[vstack.length - len];
  114571. yyval._$ = { first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column };
  114572. if (ranges) {
  114573. yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]];
  114574. }
  114575. r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);
  114576. if (typeof r !== "undefined") {
  114577. return r;
  114578. }
  114579. if (len) {
  114580. stack = stack.slice(0, -1 * len * 2);
  114581. vstack = vstack.slice(0, -1 * len);
  114582. lstack = lstack.slice(0, -1 * len);
  114583. }
  114584. stack.push(this.productions_[action[1]][0]);
  114585. vstack.push(yyval.$);
  114586. lstack.push(yyval._$);
  114587. newState = table[stack[stack.length - 2]][stack[stack.length - 1]];
  114588. stack.push(newState);
  114589. break;
  114590. case 3:
  114591. return true;
  114592. }
  114593. }
  114594. return true;
  114595. }
  114596. };
  114597. /* Jison generated lexer */
  114598. var lexer = (function () {
  114599. var lexer = { EOF: 1,
  114600. parseError: function parseError(str, hash) {
  114601. if (this.yy.parser) {
  114602. this.yy.parser.parseError(str, hash);
  114603. } else {
  114604. throw new Error(str);
  114605. }
  114606. },
  114607. setInput: function setInput(input) {
  114608. this._input = input;
  114609. this._more = this._less = this.done = false;
  114610. this.yylineno = this.yyleng = 0;
  114611. this.yytext = this.matched = this.match = '';
  114612. this.conditionStack = ['INITIAL'];
  114613. this.yylloc = { first_line: 1, first_column: 0, last_line: 1, last_column: 0 };
  114614. if (this.options.ranges) this.yylloc.range = [0, 0];
  114615. this.offset = 0;
  114616. return this;
  114617. },
  114618. input: function input() {
  114619. var ch = this._input[0];
  114620. this.yytext += ch;
  114621. this.yyleng++;
  114622. this.offset++;
  114623. this.match += ch;
  114624. this.matched += ch;
  114625. var lines = ch.match(/(?:\r\n?|\n).*/g);
  114626. if (lines) {
  114627. this.yylineno++;
  114628. this.yylloc.last_line++;
  114629. } else {
  114630. this.yylloc.last_column++;
  114631. }
  114632. if (this.options.ranges) this.yylloc.range[1]++;
  114633. this._input = this._input.slice(1);
  114634. return ch;
  114635. },
  114636. unput: function unput(ch) {
  114637. var len = ch.length;
  114638. var lines = ch.split(/(?:\r\n?|\n)/g);
  114639. this._input = ch + this._input;
  114640. this.yytext = this.yytext.substr(0, this.yytext.length - len - 1);
  114641. //this.yyleng -= len;
  114642. this.offset -= len;
  114643. var oldLines = this.match.split(/(?:\r\n?|\n)/g);
  114644. this.match = this.match.substr(0, this.match.length - 1);
  114645. this.matched = this.matched.substr(0, this.matched.length - 1);
  114646. if (lines.length - 1) this.yylineno -= lines.length - 1;
  114647. var r = this.yylloc.range;
  114648. this.yylloc = { first_line: this.yylloc.first_line,
  114649. last_line: this.yylineno + 1,
  114650. first_column: this.yylloc.first_column,
  114651. last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len
  114652. };
  114653. if (this.options.ranges) {
  114654. this.yylloc.range = [r[0], r[0] + this.yyleng - len];
  114655. }
  114656. return this;
  114657. },
  114658. more: function more() {
  114659. this._more = true;
  114660. return this;
  114661. },
  114662. less: function less(n) {
  114663. this.unput(this.match.slice(n));
  114664. },
  114665. pastInput: function pastInput() {
  114666. var past = this.matched.substr(0, this.matched.length - this.match.length);
  114667. return (past.length > 20 ? '...' : '') + past.substr(-20).replace(/\n/g, "");
  114668. },
  114669. upcomingInput: function upcomingInput() {
  114670. var next = this.match;
  114671. if (next.length < 20) {
  114672. next += this._input.substr(0, 20 - next.length);
  114673. }
  114674. return (next.substr(0, 20) + (next.length > 20 ? '...' : '')).replace(/\n/g, "");
  114675. },
  114676. showPosition: function showPosition() {
  114677. var pre = this.pastInput();
  114678. var c = new Array(pre.length + 1).join("-");
  114679. return pre + this.upcomingInput() + "\n" + c + "^";
  114680. },
  114681. next: function next() {
  114682. if (this.done) {
  114683. return this.EOF;
  114684. }
  114685. if (!this._input) this.done = true;
  114686. var token, match, tempMatch, index, col, lines;
  114687. if (!this._more) {
  114688. this.yytext = '';
  114689. this.match = '';
  114690. }
  114691. var rules = this._currentRules();
  114692. for (var i = 0; i < rules.length; i++) {
  114693. tempMatch = this._input.match(this.rules[rules[i]]);
  114694. if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {
  114695. match = tempMatch;
  114696. index = i;
  114697. if (!this.options.flex) break;
  114698. }
  114699. }
  114700. if (match) {
  114701. lines = match[0].match(/(?:\r\n?|\n).*/g);
  114702. if (lines) this.yylineno += lines.length;
  114703. this.yylloc = { first_line: this.yylloc.last_line,
  114704. last_line: this.yylineno + 1,
  114705. first_column: this.yylloc.last_column,
  114706. last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length };
  114707. this.yytext += match[0];
  114708. this.match += match[0];
  114709. this.matches = match;
  114710. this.yyleng = this.yytext.length;
  114711. if (this.options.ranges) {
  114712. this.yylloc.range = [this.offset, this.offset += this.yyleng];
  114713. }
  114714. this._more = false;
  114715. this._input = this._input.slice(match[0].length);
  114716. this.matched += match[0];
  114717. token = this.performAction.call(this, this.yy, this, rules[index], this.conditionStack[this.conditionStack.length - 1]);
  114718. if (this.done && this._input) this.done = false;
  114719. if (token) return token;else return;
  114720. }
  114721. if (this._input === "") {
  114722. return this.EOF;
  114723. } else {
  114724. return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), { text: "", token: null, line: this.yylineno });
  114725. }
  114726. },
  114727. lex: function lex() {
  114728. var r = this.next();
  114729. if (typeof r !== 'undefined') {
  114730. return r;
  114731. } else {
  114732. return this.lex();
  114733. }
  114734. },
  114735. begin: function begin(condition) {
  114736. this.conditionStack.push(condition);
  114737. },
  114738. popState: function popState() {
  114739. return this.conditionStack.pop();
  114740. },
  114741. _currentRules: function _currentRules() {
  114742. return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;
  114743. },
  114744. topState: function topState() {
  114745. return this.conditionStack[this.conditionStack.length - 2];
  114746. },
  114747. pushState: function begin(condition) {
  114748. this.begin(condition);
  114749. } };
  114750. lexer.options = {};
  114751. lexer.performAction = function anonymous(yy, yy_, $avoiding_name_collisions, YY_START
  114752. /**/) {
  114753. function strip(start, end) {
  114754. return yy_.yytext = yy_.yytext.substr(start, yy_.yyleng - end);
  114755. }
  114756. var YYSTATE = YY_START;
  114757. switch ($avoiding_name_collisions) {
  114758. case 0:
  114759. if (yy_.yytext.slice(-2) === "\\\\") {
  114760. strip(0, 1);
  114761. this.begin("mu");
  114762. } else if (yy_.yytext.slice(-1) === "\\") {
  114763. strip(0, 1);
  114764. this.begin("emu");
  114765. } else {
  114766. this.begin("mu");
  114767. }
  114768. if (yy_.yytext) return 15;
  114769. break;
  114770. case 1:
  114771. return 15;
  114772. break;
  114773. case 2:
  114774. this.popState();
  114775. return 15;
  114776. break;
  114777. case 3:
  114778. this.begin('raw');return 15;
  114779. break;
  114780. case 4:
  114781. this.popState();
  114782. // Should be using `this.topState()` below, but it currently
  114783. // returns the second top instead of the first top. Opened an
  114784. // issue about it at https://github.com/zaach/jison/issues/291
  114785. if (this.conditionStack[this.conditionStack.length - 1] === 'raw') {
  114786. return 15;
  114787. } else {
  114788. yy_.yytext = yy_.yytext.substr(5, yy_.yyleng - 9);
  114789. return 'END_RAW_BLOCK';
  114790. }
  114791. break;
  114792. case 5:
  114793. return 15;
  114794. break;
  114795. case 6:
  114796. this.popState();
  114797. return 14;
  114798. break;
  114799. case 7:
  114800. return 65;
  114801. break;
  114802. case 8:
  114803. return 68;
  114804. break;
  114805. case 9:
  114806. return 19;
  114807. break;
  114808. case 10:
  114809. this.popState();
  114810. this.begin('raw');
  114811. return 23;
  114812. break;
  114813. case 11:
  114814. return 55;
  114815. break;
  114816. case 12:
  114817. return 60;
  114818. break;
  114819. case 13:
  114820. return 29;
  114821. break;
  114822. case 14:
  114823. return 47;
  114824. break;
  114825. case 15:
  114826. this.popState();return 44;
  114827. break;
  114828. case 16:
  114829. this.popState();return 44;
  114830. break;
  114831. case 17:
  114832. return 34;
  114833. break;
  114834. case 18:
  114835. return 39;
  114836. break;
  114837. case 19:
  114838. return 51;
  114839. break;
  114840. case 20:
  114841. return 48;
  114842. break;
  114843. case 21:
  114844. this.unput(yy_.yytext);
  114845. this.popState();
  114846. this.begin('com');
  114847. break;
  114848. case 22:
  114849. this.popState();
  114850. return 14;
  114851. break;
  114852. case 23:
  114853. return 48;
  114854. break;
  114855. case 24:
  114856. return 73;
  114857. break;
  114858. case 25:
  114859. return 72;
  114860. break;
  114861. case 26:
  114862. return 72;
  114863. break;
  114864. case 27:
  114865. return 87;
  114866. break;
  114867. case 28:
  114868. // ignore whitespace
  114869. break;
  114870. case 29:
  114871. this.popState();return 54;
  114872. break;
  114873. case 30:
  114874. this.popState();return 33;
  114875. break;
  114876. case 31:
  114877. yy_.yytext = strip(1, 2).replace(/\\"/g, '"');return 80;
  114878. break;
  114879. case 32:
  114880. yy_.yytext = strip(1, 2).replace(/\\'/g, "'");return 80;
  114881. break;
  114882. case 33:
  114883. return 85;
  114884. break;
  114885. case 34:
  114886. return 82;
  114887. break;
  114888. case 35:
  114889. return 82;
  114890. break;
  114891. case 36:
  114892. return 83;
  114893. break;
  114894. case 37:
  114895. return 84;
  114896. break;
  114897. case 38:
  114898. return 81;
  114899. break;
  114900. case 39:
  114901. return 75;
  114902. break;
  114903. case 40:
  114904. return 77;
  114905. break;
  114906. case 41:
  114907. return 72;
  114908. break;
  114909. case 42:
  114910. yy_.yytext = yy_.yytext.replace(/\\([\\\]])/g, '$1');return 72;
  114911. break;
  114912. case 43:
  114913. return 'INVALID';
  114914. break;
  114915. case 44:
  114916. return 5;
  114917. break;
  114918. }
  114919. };
  114920. lexer.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\/.)|]))))/, /^(?:\[(\\\]|[^\]])*\])/, /^(?:.)/, /^(?:$)/];
  114921. lexer.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": false }, "emu": { "rules": [2], "inclusive": false }, "com": { "rules": [6], "inclusive": false }, "raw": { "rules": [3, 4, 5], "inclusive": false }, "INITIAL": { "rules": [0, 1, 44], "inclusive": true } };
  114922. return lexer;
  114923. })();
  114924. parser.lexer = lexer;
  114925. function Parser() {
  114926. this.yy = {};
  114927. }Parser.prototype = parser;parser.Parser = Parser;
  114928. return new Parser();
  114929. })();exports["default"] = handlebars;
  114930. module.exports = exports["default"];
  114931. /***/ }),
  114932. /* 38 */
  114933. /***/ (function(module, exports, __webpack_require__) {
  114934. 'use strict';
  114935. var _interopRequireDefault = __webpack_require__(1)['default'];
  114936. exports.__esModule = true;
  114937. var _visitor = __webpack_require__(39);
  114938. var _visitor2 = _interopRequireDefault(_visitor);
  114939. function WhitespaceControl() {
  114940. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  114941. this.options = options;
  114942. }
  114943. WhitespaceControl.prototype = new _visitor2['default']();
  114944. WhitespaceControl.prototype.Program = function (program) {
  114945. var doStandalone = !this.options.ignoreStandalone;
  114946. var isRoot = !this.isRootSeen;
  114947. this.isRootSeen = true;
  114948. var body = program.body;
  114949. for (var i = 0, l = body.length; i < l; i++) {
  114950. var current = body[i],
  114951. strip = this.accept(current);
  114952. if (!strip) {
  114953. continue;
  114954. }
  114955. var _isPrevWhitespace = isPrevWhitespace(body, i, isRoot),
  114956. _isNextWhitespace = isNextWhitespace(body, i, isRoot),
  114957. openStandalone = strip.openStandalone && _isPrevWhitespace,
  114958. closeStandalone = strip.closeStandalone && _isNextWhitespace,
  114959. inlineStandalone = strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace;
  114960. if (strip.close) {
  114961. omitRight(body, i, true);
  114962. }
  114963. if (strip.open) {
  114964. omitLeft(body, i, true);
  114965. }
  114966. if (doStandalone && inlineStandalone) {
  114967. omitRight(body, i);
  114968. if (omitLeft(body, i)) {
  114969. // If we are on a standalone node, save the indent info for partials
  114970. if (current.type === 'PartialStatement') {
  114971. // Pull out the whitespace from the final line
  114972. current.indent = /([ \t]+$)/.exec(body[i - 1].original)[1];
  114973. }
  114974. }
  114975. }
  114976. if (doStandalone && openStandalone) {
  114977. omitRight((current.program || current.inverse).body);
  114978. // Strip out the previous content node if it's whitespace only
  114979. omitLeft(body, i);
  114980. }
  114981. if (doStandalone && closeStandalone) {
  114982. // Always strip the next node
  114983. omitRight(body, i);
  114984. omitLeft((current.inverse || current.program).body);
  114985. }
  114986. }
  114987. return program;
  114988. };
  114989. WhitespaceControl.prototype.BlockStatement = WhitespaceControl.prototype.DecoratorBlock = WhitespaceControl.prototype.PartialBlockStatement = function (block) {
  114990. this.accept(block.program);
  114991. this.accept(block.inverse);
  114992. // Find the inverse program that is involed with whitespace stripping.
  114993. var program = block.program || block.inverse,
  114994. inverse = block.program && block.inverse,
  114995. firstInverse = inverse,
  114996. lastInverse = inverse;
  114997. if (inverse && inverse.chained) {
  114998. firstInverse = inverse.body[0].program;
  114999. // Walk the inverse chain to find the last inverse that is actually in the chain.
  115000. while (lastInverse.chained) {
  115001. lastInverse = lastInverse.body[lastInverse.body.length - 1].program;
  115002. }
  115003. }
  115004. var strip = {
  115005. open: block.openStrip.open,
  115006. close: block.closeStrip.close,
  115007. // Determine the standalone candiacy. Basically flag our content as being possibly standalone
  115008. // so our parent can determine if we actually are standalone
  115009. openStandalone: isNextWhitespace(program.body),
  115010. closeStandalone: isPrevWhitespace((firstInverse || program).body)
  115011. };
  115012. if (block.openStrip.close) {
  115013. omitRight(program.body, null, true);
  115014. }
  115015. if (inverse) {
  115016. var inverseStrip = block.inverseStrip;
  115017. if (inverseStrip.open) {
  115018. omitLeft(program.body, null, true);
  115019. }
  115020. if (inverseStrip.close) {
  115021. omitRight(firstInverse.body, null, true);
  115022. }
  115023. if (block.closeStrip.open) {
  115024. omitLeft(lastInverse.body, null, true);
  115025. }
  115026. // Find standalone else statments
  115027. if (!this.options.ignoreStandalone && isPrevWhitespace(program.body) && isNextWhitespace(firstInverse.body)) {
  115028. omitLeft(program.body);
  115029. omitRight(firstInverse.body);
  115030. }
  115031. } else if (block.closeStrip.open) {
  115032. omitLeft(program.body, null, true);
  115033. }
  115034. return strip;
  115035. };
  115036. WhitespaceControl.prototype.Decorator = WhitespaceControl.prototype.MustacheStatement = function (mustache) {
  115037. return mustache.strip;
  115038. };
  115039. WhitespaceControl.prototype.PartialStatement = WhitespaceControl.prototype.CommentStatement = function (node) {
  115040. /* istanbul ignore next */
  115041. var strip = node.strip || {};
  115042. return {
  115043. inlineStandalone: true,
  115044. open: strip.open,
  115045. close: strip.close
  115046. };
  115047. };
  115048. function isPrevWhitespace(body, i, isRoot) {
  115049. if (i === undefined) {
  115050. i = body.length;
  115051. }
  115052. // Nodes that end with newlines are considered whitespace (but are special
  115053. // cased for strip operations)
  115054. var prev = body[i - 1],
  115055. sibling = body[i - 2];
  115056. if (!prev) {
  115057. return isRoot;
  115058. }
  115059. if (prev.type === 'ContentStatement') {
  115060. return (sibling || !isRoot ? /\r?\n\s*?$/ : /(^|\r?\n)\s*?$/).test(prev.original);
  115061. }
  115062. }
  115063. function isNextWhitespace(body, i, isRoot) {
  115064. if (i === undefined) {
  115065. i = -1;
  115066. }
  115067. var next = body[i + 1],
  115068. sibling = body[i + 2];
  115069. if (!next) {
  115070. return isRoot;
  115071. }
  115072. if (next.type === 'ContentStatement') {
  115073. return (sibling || !isRoot ? /^\s*?\r?\n/ : /^\s*?(\r?\n|$)/).test(next.original);
  115074. }
  115075. }
  115076. // Marks the node to the right of the position as omitted.
  115077. // I.e. {{foo}}' ' will mark the ' ' node as omitted.
  115078. //
  115079. // If i is undefined, then the first child will be marked as such.
  115080. //
  115081. // If mulitple is truthy then all whitespace will be stripped out until non-whitespace
  115082. // content is met.
  115083. function omitRight(body, i, multiple) {
  115084. var current = body[i == null ? 0 : i + 1];
  115085. if (!current || current.type !== 'ContentStatement' || !multiple && current.rightStripped) {
  115086. return;
  115087. }
  115088. var original = current.value;
  115089. current.value = current.value.replace(multiple ? /^\s+/ : /^[ \t]*\r?\n?/, '');
  115090. current.rightStripped = current.value !== original;
  115091. }
  115092. // Marks the node to the left of the position as omitted.
  115093. // I.e. ' '{{foo}} will mark the ' ' node as omitted.
  115094. //
  115095. // If i is undefined then the last child will be marked as such.
  115096. //
  115097. // If mulitple is truthy then all whitespace will be stripped out until non-whitespace
  115098. // content is met.
  115099. function omitLeft(body, i, multiple) {
  115100. var current = body[i == null ? body.length - 1 : i - 1];
  115101. if (!current || current.type !== 'ContentStatement' || !multiple && current.leftStripped) {
  115102. return;
  115103. }
  115104. // We omit the last node if it's whitespace only and not preceeded by a non-content node.
  115105. var original = current.value;
  115106. current.value = current.value.replace(multiple ? /\s+$/ : /[ \t]+$/, '');
  115107. current.leftStripped = current.value !== original;
  115108. return current.leftStripped;
  115109. }
  115110. exports['default'] = WhitespaceControl;
  115111. module.exports = exports['default'];
  115112. /***/ }),
  115113. /* 39 */
  115114. /***/ (function(module, exports, __webpack_require__) {
  115115. 'use strict';
  115116. var _interopRequireDefault = __webpack_require__(1)['default'];
  115117. exports.__esModule = true;
  115118. var _exception = __webpack_require__(6);
  115119. var _exception2 = _interopRequireDefault(_exception);
  115120. function Visitor() {
  115121. this.parents = [];
  115122. }
  115123. Visitor.prototype = {
  115124. constructor: Visitor,
  115125. mutating: false,
  115126. // Visits a given value. If mutating, will replace the value if necessary.
  115127. acceptKey: function acceptKey(node, name) {
  115128. var value = this.accept(node[name]);
  115129. if (this.mutating) {
  115130. // Hacky sanity check: This may have a few false positives for type for the helper
  115131. // methods but will generally do the right thing without a lot of overhead.
  115132. if (value && !Visitor.prototype[value.type]) {
  115133. throw new _exception2['default']('Unexpected node type "' + value.type + '" found when accepting ' + name + ' on ' + node.type);
  115134. }
  115135. node[name] = value;
  115136. }
  115137. },
  115138. // Performs an accept operation with added sanity check to ensure
  115139. // required keys are not removed.
  115140. acceptRequired: function acceptRequired(node, name) {
  115141. this.acceptKey(node, name);
  115142. if (!node[name]) {
  115143. throw new _exception2['default'](node.type + ' requires ' + name);
  115144. }
  115145. },
  115146. // Traverses a given array. If mutating, empty respnses will be removed
  115147. // for child elements.
  115148. acceptArray: function acceptArray(array) {
  115149. for (var i = 0, l = array.length; i < l; i++) {
  115150. this.acceptKey(array, i);
  115151. if (!array[i]) {
  115152. array.splice(i, 1);
  115153. i--;
  115154. l--;
  115155. }
  115156. }
  115157. },
  115158. accept: function accept(object) {
  115159. if (!object) {
  115160. return;
  115161. }
  115162. /* istanbul ignore next: Sanity code */
  115163. if (!this[object.type]) {
  115164. throw new _exception2['default']('Unknown type: ' + object.type, object);
  115165. }
  115166. if (this.current) {
  115167. this.parents.unshift(this.current);
  115168. }
  115169. this.current = object;
  115170. var ret = this[object.type](object);
  115171. this.current = this.parents.shift();
  115172. if (!this.mutating || ret) {
  115173. return ret;
  115174. } else if (ret !== false) {
  115175. return object;
  115176. }
  115177. },
  115178. Program: function Program(program) {
  115179. this.acceptArray(program.body);
  115180. },
  115181. MustacheStatement: visitSubExpression,
  115182. Decorator: visitSubExpression,
  115183. BlockStatement: visitBlock,
  115184. DecoratorBlock: visitBlock,
  115185. PartialStatement: visitPartial,
  115186. PartialBlockStatement: function PartialBlockStatement(partial) {
  115187. visitPartial.call(this, partial);
  115188. this.acceptKey(partial, 'program');
  115189. },
  115190. ContentStatement: function ContentStatement() /* content */{},
  115191. CommentStatement: function CommentStatement() /* comment */{},
  115192. SubExpression: visitSubExpression,
  115193. PathExpression: function PathExpression() /* path */{},
  115194. StringLiteral: function StringLiteral() /* string */{},
  115195. NumberLiteral: function NumberLiteral() /* number */{},
  115196. BooleanLiteral: function BooleanLiteral() /* bool */{},
  115197. UndefinedLiteral: function UndefinedLiteral() /* literal */{},
  115198. NullLiteral: function NullLiteral() /* literal */{},
  115199. Hash: function Hash(hash) {
  115200. this.acceptArray(hash.pairs);
  115201. },
  115202. HashPair: function HashPair(pair) {
  115203. this.acceptRequired(pair, 'value');
  115204. }
  115205. };
  115206. function visitSubExpression(mustache) {
  115207. this.acceptRequired(mustache, 'path');
  115208. this.acceptArray(mustache.params);
  115209. this.acceptKey(mustache, 'hash');
  115210. }
  115211. function visitBlock(block) {
  115212. visitSubExpression.call(this, block);
  115213. this.acceptKey(block, 'program');
  115214. this.acceptKey(block, 'inverse');
  115215. }
  115216. function visitPartial(partial) {
  115217. this.acceptRequired(partial, 'name');
  115218. this.acceptArray(partial.params);
  115219. this.acceptKey(partial, 'hash');
  115220. }
  115221. exports['default'] = Visitor;
  115222. module.exports = exports['default'];
  115223. /***/ }),
  115224. /* 40 */
  115225. /***/ (function(module, exports, __webpack_require__) {
  115226. 'use strict';
  115227. var _interopRequireDefault = __webpack_require__(1)['default'];
  115228. exports.__esModule = true;
  115229. exports.SourceLocation = SourceLocation;
  115230. exports.id = id;
  115231. exports.stripFlags = stripFlags;
  115232. exports.stripComment = stripComment;
  115233. exports.preparePath = preparePath;
  115234. exports.prepareMustache = prepareMustache;
  115235. exports.prepareRawBlock = prepareRawBlock;
  115236. exports.prepareBlock = prepareBlock;
  115237. exports.prepareProgram = prepareProgram;
  115238. exports.preparePartialBlock = preparePartialBlock;
  115239. var _exception = __webpack_require__(6);
  115240. var _exception2 = _interopRequireDefault(_exception);
  115241. function validateClose(open, close) {
  115242. close = close.path ? close.path.original : close;
  115243. if (open.path.original !== close) {
  115244. var errorNode = { loc: open.path.loc };
  115245. throw new _exception2['default'](open.path.original + " doesn't match " + close, errorNode);
  115246. }
  115247. }
  115248. function SourceLocation(source, locInfo) {
  115249. this.source = source;
  115250. this.start = {
  115251. line: locInfo.first_line,
  115252. column: locInfo.first_column
  115253. };
  115254. this.end = {
  115255. line: locInfo.last_line,
  115256. column: locInfo.last_column
  115257. };
  115258. }
  115259. function id(token) {
  115260. if (/^\[.*\]$/.test(token)) {
  115261. return token.substr(1, token.length - 2);
  115262. } else {
  115263. return token;
  115264. }
  115265. }
  115266. function stripFlags(open, close) {
  115267. return {
  115268. open: open.charAt(2) === '~',
  115269. close: close.charAt(close.length - 3) === '~'
  115270. };
  115271. }
  115272. function stripComment(comment) {
  115273. return comment.replace(/^\{\{~?\!-?-?/, '').replace(/-?-?~?\}\}$/, '');
  115274. }
  115275. function preparePath(data, parts, loc) {
  115276. loc = this.locInfo(loc);
  115277. var original = data ? '@' : '',
  115278. dig = [],
  115279. depth = 0,
  115280. depthString = '';
  115281. for (var i = 0, l = parts.length; i < l; i++) {
  115282. var part = parts[i].part,
  115283. // If we have [] syntax then we do not treat path references as operators,
  115284. // i.e. foo.[this] resolves to approximately context.foo['this']
  115285. isLiteral = parts[i].original !== part;
  115286. original += (parts[i].separator || '') + part;
  115287. if (!isLiteral && (part === '..' || part === '.' || part === 'this')) {
  115288. if (dig.length > 0) {
  115289. throw new _exception2['default']('Invalid path: ' + original, { loc: loc });
  115290. } else if (part === '..') {
  115291. depth++;
  115292. depthString += '../';
  115293. }
  115294. } else {
  115295. dig.push(part);
  115296. }
  115297. }
  115298. return {
  115299. type: 'PathExpression',
  115300. data: data,
  115301. depth: depth,
  115302. parts: dig,
  115303. original: original,
  115304. loc: loc
  115305. };
  115306. }
  115307. function prepareMustache(path, params, hash, open, strip, locInfo) {
  115308. // Must use charAt to support IE pre-10
  115309. var escapeFlag = open.charAt(3) || open.charAt(2),
  115310. escaped = escapeFlag !== '{' && escapeFlag !== '&';
  115311. var decorator = /\*/.test(open);
  115312. return {
  115313. type: decorator ? 'Decorator' : 'MustacheStatement',
  115314. path: path,
  115315. params: params,
  115316. hash: hash,
  115317. escaped: escaped,
  115318. strip: strip,
  115319. loc: this.locInfo(locInfo)
  115320. };
  115321. }
  115322. function prepareRawBlock(openRawBlock, contents, close, locInfo) {
  115323. validateClose(openRawBlock, close);
  115324. locInfo = this.locInfo(locInfo);
  115325. var program = {
  115326. type: 'Program',
  115327. body: contents,
  115328. strip: {},
  115329. loc: locInfo
  115330. };
  115331. return {
  115332. type: 'BlockStatement',
  115333. path: openRawBlock.path,
  115334. params: openRawBlock.params,
  115335. hash: openRawBlock.hash,
  115336. program: program,
  115337. openStrip: {},
  115338. inverseStrip: {},
  115339. closeStrip: {},
  115340. loc: locInfo
  115341. };
  115342. }
  115343. function prepareBlock(openBlock, program, inverseAndProgram, close, inverted, locInfo) {
  115344. if (close && close.path) {
  115345. validateClose(openBlock, close);
  115346. }
  115347. var decorator = /\*/.test(openBlock.open);
  115348. program.blockParams = openBlock.blockParams;
  115349. var inverse = undefined,
  115350. inverseStrip = undefined;
  115351. if (inverseAndProgram) {
  115352. if (decorator) {
  115353. throw new _exception2['default']('Unexpected inverse block on decorator', inverseAndProgram);
  115354. }
  115355. if (inverseAndProgram.chain) {
  115356. inverseAndProgram.program.body[0].closeStrip = close.strip;
  115357. }
  115358. inverseStrip = inverseAndProgram.strip;
  115359. inverse = inverseAndProgram.program;
  115360. }
  115361. if (inverted) {
  115362. inverted = inverse;
  115363. inverse = program;
  115364. program = inverted;
  115365. }
  115366. return {
  115367. type: decorator ? 'DecoratorBlock' : 'BlockStatement',
  115368. path: openBlock.path,
  115369. params: openBlock.params,
  115370. hash: openBlock.hash,
  115371. program: program,
  115372. inverse: inverse,
  115373. openStrip: openBlock.strip,
  115374. inverseStrip: inverseStrip,
  115375. closeStrip: close && close.strip,
  115376. loc: this.locInfo(locInfo)
  115377. };
  115378. }
  115379. function prepareProgram(statements, loc) {
  115380. if (!loc && statements.length) {
  115381. var firstLoc = statements[0].loc,
  115382. lastLoc = statements[statements.length - 1].loc;
  115383. /* istanbul ignore else */
  115384. if (firstLoc && lastLoc) {
  115385. loc = {
  115386. source: firstLoc.source,
  115387. start: {
  115388. line: firstLoc.start.line,
  115389. column: firstLoc.start.column
  115390. },
  115391. end: {
  115392. line: lastLoc.end.line,
  115393. column: lastLoc.end.column
  115394. }
  115395. };
  115396. }
  115397. }
  115398. return {
  115399. type: 'Program',
  115400. body: statements,
  115401. strip: {},
  115402. loc: loc
  115403. };
  115404. }
  115405. function preparePartialBlock(open, program, close, locInfo) {
  115406. validateClose(open, close);
  115407. return {
  115408. type: 'PartialBlockStatement',
  115409. name: open.path,
  115410. params: open.params,
  115411. hash: open.hash,
  115412. program: program,
  115413. openStrip: open.strip,
  115414. closeStrip: close && close.strip,
  115415. loc: this.locInfo(locInfo)
  115416. };
  115417. }
  115418. /***/ }),
  115419. /* 41 */
  115420. /***/ (function(module, exports, __webpack_require__) {
  115421. /* eslint-disable new-cap */
  115422. 'use strict';
  115423. var _interopRequireDefault = __webpack_require__(1)['default'];
  115424. exports.__esModule = true;
  115425. exports.Compiler = Compiler;
  115426. exports.precompile = precompile;
  115427. exports.compile = compile;
  115428. var _exception = __webpack_require__(6);
  115429. var _exception2 = _interopRequireDefault(_exception);
  115430. var _utils = __webpack_require__(5);
  115431. var _ast = __webpack_require__(35);
  115432. var _ast2 = _interopRequireDefault(_ast);
  115433. var slice = [].slice;
  115434. function Compiler() {}
  115435. // the foundHelper register will disambiguate helper lookup from finding a
  115436. // function in a context. This is necessary for mustache compatibility, which
  115437. // requires that context functions in blocks are evaluated by blockHelperMissing,
  115438. // and then proceed as if the resulting value was provided to blockHelperMissing.
  115439. Compiler.prototype = {
  115440. compiler: Compiler,
  115441. equals: function equals(other) {
  115442. var len = this.opcodes.length;
  115443. if (other.opcodes.length !== len) {
  115444. return false;
  115445. }
  115446. for (var i = 0; i < len; i++) {
  115447. var opcode = this.opcodes[i],
  115448. otherOpcode = other.opcodes[i];
  115449. if (opcode.opcode !== otherOpcode.opcode || !argEquals(opcode.args, otherOpcode.args)) {
  115450. return false;
  115451. }
  115452. }
  115453. // We know that length is the same between the two arrays because they are directly tied
  115454. // to the opcode behavior above.
  115455. len = this.children.length;
  115456. for (var i = 0; i < len; i++) {
  115457. if (!this.children[i].equals(other.children[i])) {
  115458. return false;
  115459. }
  115460. }
  115461. return true;
  115462. },
  115463. guid: 0,
  115464. compile: function compile(program, options) {
  115465. this.sourceNode = [];
  115466. this.opcodes = [];
  115467. this.children = [];
  115468. this.options = options;
  115469. this.stringParams = options.stringParams;
  115470. this.trackIds = options.trackIds;
  115471. options.blockParams = options.blockParams || [];
  115472. // These changes will propagate to the other compiler components
  115473. var knownHelpers = options.knownHelpers;
  115474. options.knownHelpers = {
  115475. 'helperMissing': true,
  115476. 'blockHelperMissing': true,
  115477. 'each': true,
  115478. 'if': true,
  115479. 'unless': true,
  115480. 'with': true,
  115481. 'log': true,
  115482. 'lookup': true
  115483. };
  115484. if (knownHelpers) {
  115485. for (var _name in knownHelpers) {
  115486. /* istanbul ignore else */
  115487. if (_name in knownHelpers) {
  115488. this.options.knownHelpers[_name] = knownHelpers[_name];
  115489. }
  115490. }
  115491. }
  115492. return this.accept(program);
  115493. },
  115494. compileProgram: function compileProgram(program) {
  115495. var childCompiler = new this.compiler(),
  115496. // eslint-disable-line new-cap
  115497. result = childCompiler.compile(program, this.options),
  115498. guid = this.guid++;
  115499. this.usePartial = this.usePartial || result.usePartial;
  115500. this.children[guid] = result;
  115501. this.useDepths = this.useDepths || result.useDepths;
  115502. return guid;
  115503. },
  115504. accept: function accept(node) {
  115505. /* istanbul ignore next: Sanity code */
  115506. if (!this[node.type]) {
  115507. throw new _exception2['default']('Unknown type: ' + node.type, node);
  115508. }
  115509. this.sourceNode.unshift(node);
  115510. var ret = this[node.type](node);
  115511. this.sourceNode.shift();
  115512. return ret;
  115513. },
  115514. Program: function Program(program) {
  115515. this.options.blockParams.unshift(program.blockParams);
  115516. var body = program.body,
  115517. bodyLength = body.length;
  115518. for (var i = 0; i < bodyLength; i++) {
  115519. this.accept(body[i]);
  115520. }
  115521. this.options.blockParams.shift();
  115522. this.isSimple = bodyLength === 1;
  115523. this.blockParams = program.blockParams ? program.blockParams.length : 0;
  115524. return this;
  115525. },
  115526. BlockStatement: function BlockStatement(block) {
  115527. transformLiteralToPath(block);
  115528. var program = block.program,
  115529. inverse = block.inverse;
  115530. program = program && this.compileProgram(program);
  115531. inverse = inverse && this.compileProgram(inverse);
  115532. var type = this.classifySexpr(block);
  115533. if (type === 'helper') {
  115534. this.helperSexpr(block, program, inverse);
  115535. } else if (type === 'simple') {
  115536. this.simpleSexpr(block);
  115537. // now that the simple mustache is resolved, we need to
  115538. // evaluate it by executing `blockHelperMissing`
  115539. this.opcode('pushProgram', program);
  115540. this.opcode('pushProgram', inverse);
  115541. this.opcode('emptyHash');
  115542. this.opcode('blockValue', block.path.original);
  115543. } else {
  115544. this.ambiguousSexpr(block, program, inverse);
  115545. // now that the simple mustache is resolved, we need to
  115546. // evaluate it by executing `blockHelperMissing`
  115547. this.opcode('pushProgram', program);
  115548. this.opcode('pushProgram', inverse);
  115549. this.opcode('emptyHash');
  115550. this.opcode('ambiguousBlockValue');
  115551. }
  115552. this.opcode('append');
  115553. },
  115554. DecoratorBlock: function DecoratorBlock(decorator) {
  115555. var program = decorator.program && this.compileProgram(decorator.program);
  115556. var params = this.setupFullMustacheParams(decorator, program, undefined),
  115557. path = decorator.path;
  115558. this.useDecorators = true;
  115559. this.opcode('registerDecorator', params.length, path.original);
  115560. },
  115561. PartialStatement: function PartialStatement(partial) {
  115562. this.usePartial = true;
  115563. var program = partial.program;
  115564. if (program) {
  115565. program = this.compileProgram(partial.program);
  115566. }
  115567. var params = partial.params;
  115568. if (params.length > 1) {
  115569. throw new _exception2['default']('Unsupported number of partial arguments: ' + params.length, partial);
  115570. } else if (!params.length) {
  115571. if (this.options.explicitPartialContext) {
  115572. this.opcode('pushLiteral', 'undefined');
  115573. } else {
  115574. params.push({ type: 'PathExpression', parts: [], depth: 0 });
  115575. }
  115576. }
  115577. var partialName = partial.name.original,
  115578. isDynamic = partial.name.type === 'SubExpression';
  115579. if (isDynamic) {
  115580. this.accept(partial.name);
  115581. }
  115582. this.setupFullMustacheParams(partial, program, undefined, true);
  115583. var indent = partial.indent || '';
  115584. if (this.options.preventIndent && indent) {
  115585. this.opcode('appendContent', indent);
  115586. indent = '';
  115587. }
  115588. this.opcode('invokePartial', isDynamic, partialName, indent);
  115589. this.opcode('append');
  115590. },
  115591. PartialBlockStatement: function PartialBlockStatement(partialBlock) {
  115592. this.PartialStatement(partialBlock);
  115593. },
  115594. MustacheStatement: function MustacheStatement(mustache) {
  115595. this.SubExpression(mustache);
  115596. if (mustache.escaped && !this.options.noEscape) {
  115597. this.opcode('appendEscaped');
  115598. } else {
  115599. this.opcode('append');
  115600. }
  115601. },
  115602. Decorator: function Decorator(decorator) {
  115603. this.DecoratorBlock(decorator);
  115604. },
  115605. ContentStatement: function ContentStatement(content) {
  115606. if (content.value) {
  115607. this.opcode('appendContent', content.value);
  115608. }
  115609. },
  115610. CommentStatement: function CommentStatement() {},
  115611. SubExpression: function SubExpression(sexpr) {
  115612. transformLiteralToPath(sexpr);
  115613. var type = this.classifySexpr(sexpr);
  115614. if (type === 'simple') {
  115615. this.simpleSexpr(sexpr);
  115616. } else if (type === 'helper') {
  115617. this.helperSexpr(sexpr);
  115618. } else {
  115619. this.ambiguousSexpr(sexpr);
  115620. }
  115621. },
  115622. ambiguousSexpr: function ambiguousSexpr(sexpr, program, inverse) {
  115623. var path = sexpr.path,
  115624. name = path.parts[0],
  115625. isBlock = program != null || inverse != null;
  115626. this.opcode('getContext', path.depth);
  115627. this.opcode('pushProgram', program);
  115628. this.opcode('pushProgram', inverse);
  115629. path.strict = true;
  115630. this.accept(path);
  115631. this.opcode('invokeAmbiguous', name, isBlock);
  115632. },
  115633. simpleSexpr: function simpleSexpr(sexpr) {
  115634. var path = sexpr.path;
  115635. path.strict = true;
  115636. this.accept(path);
  115637. this.opcode('resolvePossibleLambda');
  115638. },
  115639. helperSexpr: function helperSexpr(sexpr, program, inverse) {
  115640. var params = this.setupFullMustacheParams(sexpr, program, inverse),
  115641. path = sexpr.path,
  115642. name = path.parts[0];
  115643. if (this.options.knownHelpers[name]) {
  115644. this.opcode('invokeKnownHelper', params.length, name);
  115645. } else if (this.options.knownHelpersOnly) {
  115646. throw new _exception2['default']('You specified knownHelpersOnly, but used the unknown helper ' + name, sexpr);
  115647. } else {
  115648. path.strict = true;
  115649. path.falsy = true;
  115650. this.accept(path);
  115651. this.opcode('invokeHelper', params.length, path.original, _ast2['default'].helpers.simpleId(path));
  115652. }
  115653. },
  115654. PathExpression: function PathExpression(path) {
  115655. this.addDepth(path.depth);
  115656. this.opcode('getContext', path.depth);
  115657. var name = path.parts[0],
  115658. scoped = _ast2['default'].helpers.scopedId(path),
  115659. blockParamId = !path.depth && !scoped && this.blockParamIndex(name);
  115660. if (blockParamId) {
  115661. this.opcode('lookupBlockParam', blockParamId, path.parts);
  115662. } else if (!name) {
  115663. // Context reference, i.e. `{{foo .}}` or `{{foo ..}}`
  115664. this.opcode('pushContext');
  115665. } else if (path.data) {
  115666. this.options.data = true;
  115667. this.opcode('lookupData', path.depth, path.parts, path.strict);
  115668. } else {
  115669. this.opcode('lookupOnContext', path.parts, path.falsy, path.strict, scoped);
  115670. }
  115671. },
  115672. StringLiteral: function StringLiteral(string) {
  115673. this.opcode('pushString', string.value);
  115674. },
  115675. NumberLiteral: function NumberLiteral(number) {
  115676. this.opcode('pushLiteral', number.value);
  115677. },
  115678. BooleanLiteral: function BooleanLiteral(bool) {
  115679. this.opcode('pushLiteral', bool.value);
  115680. },
  115681. UndefinedLiteral: function UndefinedLiteral() {
  115682. this.opcode('pushLiteral', 'undefined');
  115683. },
  115684. NullLiteral: function NullLiteral() {
  115685. this.opcode('pushLiteral', 'null');
  115686. },
  115687. Hash: function Hash(hash) {
  115688. var pairs = hash.pairs,
  115689. i = 0,
  115690. l = pairs.length;
  115691. this.opcode('pushHash');
  115692. for (; i < l; i++) {
  115693. this.pushParam(pairs[i].value);
  115694. }
  115695. while (i--) {
  115696. this.opcode('assignToHash', pairs[i].key);
  115697. }
  115698. this.opcode('popHash');
  115699. },
  115700. // HELPERS
  115701. opcode: function opcode(name) {
  115702. this.opcodes.push({ opcode: name, args: slice.call(arguments, 1), loc: this.sourceNode[0].loc });
  115703. },
  115704. addDepth: function addDepth(depth) {
  115705. if (!depth) {
  115706. return;
  115707. }
  115708. this.useDepths = true;
  115709. },
  115710. classifySexpr: function classifySexpr(sexpr) {
  115711. var isSimple = _ast2['default'].helpers.simpleId(sexpr.path);
  115712. var isBlockParam = isSimple && !!this.blockParamIndex(sexpr.path.parts[0]);
  115713. // a mustache is an eligible helper if:
  115714. // * its id is simple (a single part, not `this` or `..`)
  115715. var isHelper = !isBlockParam && _ast2['default'].helpers.helperExpression(sexpr);
  115716. // if a mustache is an eligible helper but not a definite
  115717. // helper, it is ambiguous, and will be resolved in a later
  115718. // pass or at runtime.
  115719. var isEligible = !isBlockParam && (isHelper || isSimple);
  115720. // if ambiguous, we can possibly resolve the ambiguity now
  115721. // An eligible helper is one that does not have a complex path, i.e. `this.foo`, `../foo` etc.
  115722. if (isEligible && !isHelper) {
  115723. var _name2 = sexpr.path.parts[0],
  115724. options = this.options;
  115725. if (options.knownHelpers[_name2]) {
  115726. isHelper = true;
  115727. } else if (options.knownHelpersOnly) {
  115728. isEligible = false;
  115729. }
  115730. }
  115731. if (isHelper) {
  115732. return 'helper';
  115733. } else if (isEligible) {
  115734. return 'ambiguous';
  115735. } else {
  115736. return 'simple';
  115737. }
  115738. },
  115739. pushParams: function pushParams(params) {
  115740. for (var i = 0, l = params.length; i < l; i++) {
  115741. this.pushParam(params[i]);
  115742. }
  115743. },
  115744. pushParam: function pushParam(val) {
  115745. var value = val.value != null ? val.value : val.original || '';
  115746. if (this.stringParams) {
  115747. if (value.replace) {
  115748. value = value.replace(/^(\.?\.\/)*/g, '').replace(/\//g, '.');
  115749. }
  115750. if (val.depth) {
  115751. this.addDepth(val.depth);
  115752. }
  115753. this.opcode('getContext', val.depth || 0);
  115754. this.opcode('pushStringParam', value, val.type);
  115755. if (val.type === 'SubExpression') {
  115756. // SubExpressions get evaluated and passed in
  115757. // in string params mode.
  115758. this.accept(val);
  115759. }
  115760. } else {
  115761. if (this.trackIds) {
  115762. var blockParamIndex = undefined;
  115763. if (val.parts && !_ast2['default'].helpers.scopedId(val) && !val.depth) {
  115764. blockParamIndex = this.blockParamIndex(val.parts[0]);
  115765. }
  115766. if (blockParamIndex) {
  115767. var blockParamChild = val.parts.slice(1).join('.');
  115768. this.opcode('pushId', 'BlockParam', blockParamIndex, blockParamChild);
  115769. } else {
  115770. value = val.original || value;
  115771. if (value.replace) {
  115772. value = value.replace(/^this(?:\.|$)/, '').replace(/^\.\//, '').replace(/^\.$/, '');
  115773. }
  115774. this.opcode('pushId', val.type, value);
  115775. }
  115776. }
  115777. this.accept(val);
  115778. }
  115779. },
  115780. setupFullMustacheParams: function setupFullMustacheParams(sexpr, program, inverse, omitEmpty) {
  115781. var params = sexpr.params;
  115782. this.pushParams(params);
  115783. this.opcode('pushProgram', program);
  115784. this.opcode('pushProgram', inverse);
  115785. if (sexpr.hash) {
  115786. this.accept(sexpr.hash);
  115787. } else {
  115788. this.opcode('emptyHash', omitEmpty);
  115789. }
  115790. return params;
  115791. },
  115792. blockParamIndex: function blockParamIndex(name) {
  115793. for (var depth = 0, len = this.options.blockParams.length; depth < len; depth++) {
  115794. var blockParams = this.options.blockParams[depth],
  115795. param = blockParams && _utils.indexOf(blockParams, name);
  115796. if (blockParams && param >= 0) {
  115797. return [depth, param];
  115798. }
  115799. }
  115800. }
  115801. };
  115802. function precompile(input, options, env) {
  115803. if (input == null || typeof input !== 'string' && input.type !== 'Program') {
  115804. throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.precompile. You passed ' + input);
  115805. }
  115806. options = options || {};
  115807. if (!('data' in options)) {
  115808. options.data = true;
  115809. }
  115810. if (options.compat) {
  115811. options.useDepths = true;
  115812. }
  115813. var ast = env.parse(input, options),
  115814. environment = new env.Compiler().compile(ast, options);
  115815. return new env.JavaScriptCompiler().compile(environment, options);
  115816. }
  115817. function compile(input, options, env) {
  115818. if (options === undefined) options = {};
  115819. if (input == null || typeof input !== 'string' && input.type !== 'Program') {
  115820. throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.compile. You passed ' + input);
  115821. }
  115822. options = _utils.extend({}, options);
  115823. if (!('data' in options)) {
  115824. options.data = true;
  115825. }
  115826. if (options.compat) {
  115827. options.useDepths = true;
  115828. }
  115829. var compiled = undefined;
  115830. function compileInput() {
  115831. var ast = env.parse(input, options),
  115832. environment = new env.Compiler().compile(ast, options),
  115833. templateSpec = new env.JavaScriptCompiler().compile(environment, options, undefined, true);
  115834. return env.template(templateSpec);
  115835. }
  115836. // Template is only compiled on first use and cached after that point.
  115837. function ret(context, execOptions) {
  115838. if (!compiled) {
  115839. compiled = compileInput();
  115840. }
  115841. return compiled.call(this, context, execOptions);
  115842. }
  115843. ret._setup = function (setupOptions) {
  115844. if (!compiled) {
  115845. compiled = compileInput();
  115846. }
  115847. return compiled._setup(setupOptions);
  115848. };
  115849. ret._child = function (i, data, blockParams, depths) {
  115850. if (!compiled) {
  115851. compiled = compileInput();
  115852. }
  115853. return compiled._child(i, data, blockParams, depths);
  115854. };
  115855. return ret;
  115856. }
  115857. function argEquals(a, b) {
  115858. if (a === b) {
  115859. return true;
  115860. }
  115861. if (_utils.isArray(a) && _utils.isArray(b) && a.length === b.length) {
  115862. for (var i = 0; i < a.length; i++) {
  115863. if (!argEquals(a[i], b[i])) {
  115864. return false;
  115865. }
  115866. }
  115867. return true;
  115868. }
  115869. }
  115870. function transformLiteralToPath(sexpr) {
  115871. if (!sexpr.path.parts) {
  115872. var literal = sexpr.path;
  115873. // Casting to string here to make false and 0 literal values play nicely with the rest
  115874. // of the system.
  115875. sexpr.path = {
  115876. type: 'PathExpression',
  115877. data: false,
  115878. depth: 0,
  115879. parts: [literal.original + ''],
  115880. original: literal.original + '',
  115881. loc: literal.loc
  115882. };
  115883. }
  115884. }
  115885. /***/ }),
  115886. /* 42 */
  115887. /***/ (function(module, exports, __webpack_require__) {
  115888. 'use strict';
  115889. var _interopRequireDefault = __webpack_require__(1)['default'];
  115890. exports.__esModule = true;
  115891. var _base = __webpack_require__(4);
  115892. var _exception = __webpack_require__(6);
  115893. var _exception2 = _interopRequireDefault(_exception);
  115894. var _utils = __webpack_require__(5);
  115895. var _codeGen = __webpack_require__(43);
  115896. var _codeGen2 = _interopRequireDefault(_codeGen);
  115897. function Literal(value) {
  115898. this.value = value;
  115899. }
  115900. function JavaScriptCompiler() {}
  115901. JavaScriptCompiler.prototype = {
  115902. // PUBLIC API: You can override these methods in a subclass to provide
  115903. // alternative compiled forms for name lookup and buffering semantics
  115904. nameLookup: function nameLookup(parent, name /* , type*/) {
  115905. if (JavaScriptCompiler.isValidJavaScriptVariableName(name)) {
  115906. return [parent, '.', name];
  115907. } else {
  115908. return [parent, '[', JSON.stringify(name), ']'];
  115909. }
  115910. },
  115911. depthedLookup: function depthedLookup(name) {
  115912. return [this.aliasable('container.lookup'), '(depths, "', name, '")'];
  115913. },
  115914. compilerInfo: function compilerInfo() {
  115915. var revision = _base.COMPILER_REVISION,
  115916. versions = _base.REVISION_CHANGES[revision];
  115917. return [revision, versions];
  115918. },
  115919. appendToBuffer: function appendToBuffer(source, location, explicit) {
  115920. // Force a source as this simplifies the merge logic.
  115921. if (!_utils.isArray(source)) {
  115922. source = [source];
  115923. }
  115924. source = this.source.wrap(source, location);
  115925. if (this.environment.isSimple) {
  115926. return ['return ', source, ';'];
  115927. } else if (explicit) {
  115928. // This is a case where the buffer operation occurs as a child of another
  115929. // construct, generally braces. We have to explicitly output these buffer
  115930. // operations to ensure that the emitted code goes in the correct location.
  115931. return ['buffer += ', source, ';'];
  115932. } else {
  115933. source.appendToBuffer = true;
  115934. return source;
  115935. }
  115936. },
  115937. initializeBuffer: function initializeBuffer() {
  115938. return this.quotedString('');
  115939. },
  115940. // END PUBLIC API
  115941. compile: function compile(environment, options, context, asObject) {
  115942. this.environment = environment;
  115943. this.options = options;
  115944. this.stringParams = this.options.stringParams;
  115945. this.trackIds = this.options.trackIds;
  115946. this.precompile = !asObject;
  115947. this.name = this.environment.name;
  115948. this.isChild = !!context;
  115949. this.context = context || {
  115950. decorators: [],
  115951. programs: [],
  115952. environments: []
  115953. };
  115954. this.preamble();
  115955. this.stackSlot = 0;
  115956. this.stackVars = [];
  115957. this.aliases = {};
  115958. this.registers = { list: [] };
  115959. this.hashes = [];
  115960. this.compileStack = [];
  115961. this.inlineStack = [];
  115962. this.blockParams = [];
  115963. this.compileChildren(environment, options);
  115964. this.useDepths = this.useDepths || environment.useDepths || environment.useDecorators || this.options.compat;
  115965. this.useBlockParams = this.useBlockParams || environment.useBlockParams;
  115966. var opcodes = environment.opcodes,
  115967. opcode = undefined,
  115968. firstLoc = undefined,
  115969. i = undefined,
  115970. l = undefined;
  115971. for (i = 0, l = opcodes.length; i < l; i++) {
  115972. opcode = opcodes[i];
  115973. this.source.currentLocation = opcode.loc;
  115974. firstLoc = firstLoc || opcode.loc;
  115975. this[opcode.opcode].apply(this, opcode.args);
  115976. }
  115977. // Flush any trailing content that might be pending.
  115978. this.source.currentLocation = firstLoc;
  115979. this.pushSource('');
  115980. /* istanbul ignore next */
  115981. if (this.stackSlot || this.inlineStack.length || this.compileStack.length) {
  115982. throw new _exception2['default']('Compile completed with content left on stack');
  115983. }
  115984. if (!this.decorators.isEmpty()) {
  115985. this.useDecorators = true;
  115986. this.decorators.prepend('var decorators = container.decorators;\n');
  115987. this.decorators.push('return fn;');
  115988. if (asObject) {
  115989. this.decorators = Function.apply(this, ['fn', 'props', 'container', 'depth0', 'data', 'blockParams', 'depths', this.decorators.merge()]);
  115990. } else {
  115991. this.decorators.prepend('function(fn, props, container, depth0, data, blockParams, depths) {\n');
  115992. this.decorators.push('}\n');
  115993. this.decorators = this.decorators.merge();
  115994. }
  115995. } else {
  115996. this.decorators = undefined;
  115997. }
  115998. var fn = this.createFunctionContext(asObject);
  115999. if (!this.isChild) {
  116000. var ret = {
  116001. compiler: this.compilerInfo(),
  116002. main: fn
  116003. };
  116004. if (this.decorators) {
  116005. ret.main_d = this.decorators; // eslint-disable-line camelcase
  116006. ret.useDecorators = true;
  116007. }
  116008. var _context = this.context;
  116009. var programs = _context.programs;
  116010. var decorators = _context.decorators;
  116011. for (i = 0, l = programs.length; i < l; i++) {
  116012. if (programs[i]) {
  116013. ret[i] = programs[i];
  116014. if (decorators[i]) {
  116015. ret[i + '_d'] = decorators[i];
  116016. ret.useDecorators = true;
  116017. }
  116018. }
  116019. }
  116020. if (this.environment.usePartial) {
  116021. ret.usePartial = true;
  116022. }
  116023. if (this.options.data) {
  116024. ret.useData = true;
  116025. }
  116026. if (this.useDepths) {
  116027. ret.useDepths = true;
  116028. }
  116029. if (this.useBlockParams) {
  116030. ret.useBlockParams = true;
  116031. }
  116032. if (this.options.compat) {
  116033. ret.compat = true;
  116034. }
  116035. if (!asObject) {
  116036. ret.compiler = JSON.stringify(ret.compiler);
  116037. this.source.currentLocation = { start: { line: 1, column: 0 } };
  116038. ret = this.objectLiteral(ret);
  116039. if (options.srcName) {
  116040. ret = ret.toStringWithSourceMap({ file: options.destName });
  116041. ret.map = ret.map && ret.map.toString();
  116042. } else {
  116043. ret = ret.toString();
  116044. }
  116045. } else {
  116046. ret.compilerOptions = this.options;
  116047. }
  116048. return ret;
  116049. } else {
  116050. return fn;
  116051. }
  116052. },
  116053. preamble: function preamble() {
  116054. // track the last context pushed into place to allow skipping the
  116055. // getContext opcode when it would be a noop
  116056. this.lastContext = 0;
  116057. this.source = new _codeGen2['default'](this.options.srcName);
  116058. this.decorators = new _codeGen2['default'](this.options.srcName);
  116059. },
  116060. createFunctionContext: function createFunctionContext(asObject) {
  116061. var varDeclarations = '';
  116062. var locals = this.stackVars.concat(this.registers.list);
  116063. if (locals.length > 0) {
  116064. varDeclarations += ', ' + locals.join(', ');
  116065. }
  116066. // Generate minimizer alias mappings
  116067. //
  116068. // When using true SourceNodes, this will update all references to the given alias
  116069. // as the source nodes are reused in situ. For the non-source node compilation mode,
  116070. // aliases will not be used, but this case is already being run on the client and
  116071. // we aren't concern about minimizing the template size.
  116072. var aliasCount = 0;
  116073. for (var alias in this.aliases) {
  116074. // eslint-disable-line guard-for-in
  116075. var node = this.aliases[alias];
  116076. if (this.aliases.hasOwnProperty(alias) && node.children && node.referenceCount > 1) {
  116077. varDeclarations += ', alias' + ++aliasCount + '=' + alias;
  116078. node.children[0] = 'alias' + aliasCount;
  116079. }
  116080. }
  116081. var params = ['container', 'depth0', 'helpers', 'partials', 'data'];
  116082. if (this.useBlockParams || this.useDepths) {
  116083. params.push('blockParams');
  116084. }
  116085. if (this.useDepths) {
  116086. params.push('depths');
  116087. }
  116088. // Perform a second pass over the output to merge content when possible
  116089. var source = this.mergeSource(varDeclarations);
  116090. if (asObject) {
  116091. params.push(source);
  116092. return Function.apply(this, params);
  116093. } else {
  116094. return this.source.wrap(['function(', params.join(','), ') {\n ', source, '}']);
  116095. }
  116096. },
  116097. mergeSource: function mergeSource(varDeclarations) {
  116098. var isSimple = this.environment.isSimple,
  116099. appendOnly = !this.forceBuffer,
  116100. appendFirst = undefined,
  116101. sourceSeen = undefined,
  116102. bufferStart = undefined,
  116103. bufferEnd = undefined;
  116104. this.source.each(function (line) {
  116105. if (line.appendToBuffer) {
  116106. if (bufferStart) {
  116107. line.prepend(' + ');
  116108. } else {
  116109. bufferStart = line;
  116110. }
  116111. bufferEnd = line;
  116112. } else {
  116113. if (bufferStart) {
  116114. if (!sourceSeen) {
  116115. appendFirst = true;
  116116. } else {
  116117. bufferStart.prepend('buffer += ');
  116118. }
  116119. bufferEnd.add(';');
  116120. bufferStart = bufferEnd = undefined;
  116121. }
  116122. sourceSeen = true;
  116123. if (!isSimple) {
  116124. appendOnly = false;
  116125. }
  116126. }
  116127. });
  116128. if (appendOnly) {
  116129. if (bufferStart) {
  116130. bufferStart.prepend('return ');
  116131. bufferEnd.add(';');
  116132. } else if (!sourceSeen) {
  116133. this.source.push('return "";');
  116134. }
  116135. } else {
  116136. varDeclarations += ', buffer = ' + (appendFirst ? '' : this.initializeBuffer());
  116137. if (bufferStart) {
  116138. bufferStart.prepend('return buffer + ');
  116139. bufferEnd.add(';');
  116140. } else {
  116141. this.source.push('return buffer;');
  116142. }
  116143. }
  116144. if (varDeclarations) {
  116145. this.source.prepend('var ' + varDeclarations.substring(2) + (appendFirst ? '' : ';\n'));
  116146. }
  116147. return this.source.merge();
  116148. },
  116149. // [blockValue]
  116150. //
  116151. // On stack, before: hash, inverse, program, value
  116152. // On stack, after: return value of blockHelperMissing
  116153. //
  116154. // The purpose of this opcode is to take a block of the form
  116155. // `{{#this.foo}}...{{/this.foo}}`, resolve the value of `foo`, and
  116156. // replace it on the stack with the result of properly
  116157. // invoking blockHelperMissing.
  116158. blockValue: function blockValue(name) {
  116159. var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'),
  116160. params = [this.contextName(0)];
  116161. this.setupHelperArgs(name, 0, params);
  116162. var blockName = this.popStack();
  116163. params.splice(1, 0, blockName);
  116164. this.push(this.source.functionCall(blockHelperMissing, 'call', params));
  116165. },
  116166. // [ambiguousBlockValue]
  116167. //
  116168. // On stack, before: hash, inverse, program, value
  116169. // Compiler value, before: lastHelper=value of last found helper, if any
  116170. // On stack, after, if no lastHelper: same as [blockValue]
  116171. // On stack, after, if lastHelper: value
  116172. ambiguousBlockValue: function ambiguousBlockValue() {
  116173. // We're being a bit cheeky and reusing the options value from the prior exec
  116174. var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'),
  116175. params = [this.contextName(0)];
  116176. this.setupHelperArgs('', 0, params, true);
  116177. this.flushInline();
  116178. var current = this.topStack();
  116179. params.splice(1, 0, current);
  116180. this.pushSource(['if (!', this.lastHelper, ') { ', current, ' = ', this.source.functionCall(blockHelperMissing, 'call', params), '}']);
  116181. },
  116182. // [appendContent]
  116183. //
  116184. // On stack, before: ...
  116185. // On stack, after: ...
  116186. //
  116187. // Appends the string value of `content` to the current buffer
  116188. appendContent: function appendContent(content) {
  116189. if (this.pendingContent) {
  116190. content = this.pendingContent + content;
  116191. } else {
  116192. this.pendingLocation = this.source.currentLocation;
  116193. }
  116194. this.pendingContent = content;
  116195. },
  116196. // [append]
  116197. //
  116198. // On stack, before: value, ...
  116199. // On stack, after: ...
  116200. //
  116201. // Coerces `value` to a String and appends it to the current buffer.
  116202. //
  116203. // If `value` is truthy, or 0, it is coerced into a string and appended
  116204. // Otherwise, the empty string is appended
  116205. append: function append() {
  116206. if (this.isInline()) {
  116207. this.replaceStack(function (current) {
  116208. return [' != null ? ', current, ' : ""'];
  116209. });
  116210. this.pushSource(this.appendToBuffer(this.popStack()));
  116211. } else {
  116212. var local = this.popStack();
  116213. this.pushSource(['if (', local, ' != null) { ', this.appendToBuffer(local, undefined, true), ' }']);
  116214. if (this.environment.isSimple) {
  116215. this.pushSource(['else { ', this.appendToBuffer("''", undefined, true), ' }']);
  116216. }
  116217. }
  116218. },
  116219. // [appendEscaped]
  116220. //
  116221. // On stack, before: value, ...
  116222. // On stack, after: ...
  116223. //
  116224. // Escape `value` and append it to the buffer
  116225. appendEscaped: function appendEscaped() {
  116226. this.pushSource(this.appendToBuffer([this.aliasable('container.escapeExpression'), '(', this.popStack(), ')']));
  116227. },
  116228. // [getContext]
  116229. //
  116230. // On stack, before: ...
  116231. // On stack, after: ...
  116232. // Compiler value, after: lastContext=depth
  116233. //
  116234. // Set the value of the `lastContext` compiler value to the depth
  116235. getContext: function getContext(depth) {
  116236. this.lastContext = depth;
  116237. },
  116238. // [pushContext]
  116239. //
  116240. // On stack, before: ...
  116241. // On stack, after: currentContext, ...
  116242. //
  116243. // Pushes the value of the current context onto the stack.
  116244. pushContext: function pushContext() {
  116245. this.pushStackLiteral(this.contextName(this.lastContext));
  116246. },
  116247. // [lookupOnContext]
  116248. //
  116249. // On stack, before: ...
  116250. // On stack, after: currentContext[name], ...
  116251. //
  116252. // Looks up the value of `name` on the current context and pushes
  116253. // it onto the stack.
  116254. lookupOnContext: function lookupOnContext(parts, falsy, strict, scoped) {
  116255. var i = 0;
  116256. if (!scoped && this.options.compat && !this.lastContext) {
  116257. // The depthed query is expected to handle the undefined logic for the root level that
  116258. // is implemented below, so we evaluate that directly in compat mode
  116259. this.push(this.depthedLookup(parts[i++]));
  116260. } else {
  116261. this.pushContext();
  116262. }
  116263. this.resolvePath('context', parts, i, falsy, strict);
  116264. },
  116265. // [lookupBlockParam]
  116266. //
  116267. // On stack, before: ...
  116268. // On stack, after: blockParam[name], ...
  116269. //
  116270. // Looks up the value of `parts` on the given block param and pushes
  116271. // it onto the stack.
  116272. lookupBlockParam: function lookupBlockParam(blockParamId, parts) {
  116273. this.useBlockParams = true;
  116274. this.push(['blockParams[', blockParamId[0], '][', blockParamId[1], ']']);
  116275. this.resolvePath('context', parts, 1);
  116276. },
  116277. // [lookupData]
  116278. //
  116279. // On stack, before: ...
  116280. // On stack, after: data, ...
  116281. //
  116282. // Push the data lookup operator
  116283. lookupData: function lookupData(depth, parts, strict) {
  116284. if (!depth) {
  116285. this.pushStackLiteral('data');
  116286. } else {
  116287. this.pushStackLiteral('container.data(data, ' + depth + ')');
  116288. }
  116289. this.resolvePath('data', parts, 0, true, strict);
  116290. },
  116291. resolvePath: function resolvePath(type, parts, i, falsy, strict) {
  116292. // istanbul ignore next
  116293. var _this = this;
  116294. if (this.options.strict || this.options.assumeObjects) {
  116295. this.push(strictLookup(this.options.strict && strict, this, parts, type));
  116296. return;
  116297. }
  116298. var len = parts.length;
  116299. for (; i < len; i++) {
  116300. /* eslint-disable no-loop-func */
  116301. this.replaceStack(function (current) {
  116302. var lookup = _this.nameLookup(current, parts[i], type);
  116303. // We want to ensure that zero and false are handled properly if the context (falsy flag)
  116304. // needs to have the special handling for these values.
  116305. if (!falsy) {
  116306. return [' != null ? ', lookup, ' : ', current];
  116307. } else {
  116308. // Otherwise we can use generic falsy handling
  116309. return [' && ', lookup];
  116310. }
  116311. });
  116312. /* eslint-enable no-loop-func */
  116313. }
  116314. },
  116315. // [resolvePossibleLambda]
  116316. //
  116317. // On stack, before: value, ...
  116318. // On stack, after: resolved value, ...
  116319. //
  116320. // If the `value` is a lambda, replace it on the stack by
  116321. // the return value of the lambda
  116322. resolvePossibleLambda: function resolvePossibleLambda() {
  116323. this.push([this.aliasable('container.lambda'), '(', this.popStack(), ', ', this.contextName(0), ')']);
  116324. },
  116325. // [pushStringParam]
  116326. //
  116327. // On stack, before: ...
  116328. // On stack, after: string, currentContext, ...
  116329. //
  116330. // This opcode is designed for use in string mode, which
  116331. // provides the string value of a parameter along with its
  116332. // depth rather than resolving it immediately.
  116333. pushStringParam: function pushStringParam(string, type) {
  116334. this.pushContext();
  116335. this.pushString(type);
  116336. // If it's a subexpression, the string result
  116337. // will be pushed after this opcode.
  116338. if (type !== 'SubExpression') {
  116339. if (typeof string === 'string') {
  116340. this.pushString(string);
  116341. } else {
  116342. this.pushStackLiteral(string);
  116343. }
  116344. }
  116345. },
  116346. emptyHash: function emptyHash(omitEmpty) {
  116347. if (this.trackIds) {
  116348. this.push('{}'); // hashIds
  116349. }
  116350. if (this.stringParams) {
  116351. this.push('{}'); // hashContexts
  116352. this.push('{}'); // hashTypes
  116353. }
  116354. this.pushStackLiteral(omitEmpty ? 'undefined' : '{}');
  116355. },
  116356. pushHash: function pushHash() {
  116357. if (this.hash) {
  116358. this.hashes.push(this.hash);
  116359. }
  116360. this.hash = { values: [], types: [], contexts: [], ids: [] };
  116361. },
  116362. popHash: function popHash() {
  116363. var hash = this.hash;
  116364. this.hash = this.hashes.pop();
  116365. if (this.trackIds) {
  116366. this.push(this.objectLiteral(hash.ids));
  116367. }
  116368. if (this.stringParams) {
  116369. this.push(this.objectLiteral(hash.contexts));
  116370. this.push(this.objectLiteral(hash.types));
  116371. }
  116372. this.push(this.objectLiteral(hash.values));
  116373. },
  116374. // [pushString]
  116375. //
  116376. // On stack, before: ...
  116377. // On stack, after: quotedString(string), ...
  116378. //
  116379. // Push a quoted version of `string` onto the stack
  116380. pushString: function pushString(string) {
  116381. this.pushStackLiteral(this.quotedString(string));
  116382. },
  116383. // [pushLiteral]
  116384. //
  116385. // On stack, before: ...
  116386. // On stack, after: value, ...
  116387. //
  116388. // Pushes a value onto the stack. This operation prevents
  116389. // the compiler from creating a temporary variable to hold
  116390. // it.
  116391. pushLiteral: function pushLiteral(value) {
  116392. this.pushStackLiteral(value);
  116393. },
  116394. // [pushProgram]
  116395. //
  116396. // On stack, before: ...
  116397. // On stack, after: program(guid), ...
  116398. //
  116399. // Push a program expression onto the stack. This takes
  116400. // a compile-time guid and converts it into a runtime-accessible
  116401. // expression.
  116402. pushProgram: function pushProgram(guid) {
  116403. if (guid != null) {
  116404. this.pushStackLiteral(this.programExpression(guid));
  116405. } else {
  116406. this.pushStackLiteral(null);
  116407. }
  116408. },
  116409. // [registerDecorator]
  116410. //
  116411. // On stack, before: hash, program, params..., ...
  116412. // On stack, after: ...
  116413. //
  116414. // Pops off the decorator's parameters, invokes the decorator,
  116415. // and inserts the decorator into the decorators list.
  116416. registerDecorator: function registerDecorator(paramSize, name) {
  116417. var foundDecorator = this.nameLookup('decorators', name, 'decorator'),
  116418. options = this.setupHelperArgs(name, paramSize);
  116419. this.decorators.push(['fn = ', this.decorators.functionCall(foundDecorator, '', ['fn', 'props', 'container', options]), ' || fn;']);
  116420. },
  116421. // [invokeHelper]
  116422. //
  116423. // On stack, before: hash, inverse, program, params..., ...
  116424. // On stack, after: result of helper invocation
  116425. //
  116426. // Pops off the helper's parameters, invokes the helper,
  116427. // and pushes the helper's return value onto the stack.
  116428. //
  116429. // If the helper is not found, `helperMissing` is called.
  116430. invokeHelper: function invokeHelper(paramSize, name, isSimple) {
  116431. var nonHelper = this.popStack(),
  116432. helper = this.setupHelper(paramSize, name),
  116433. simple = isSimple ? [helper.name, ' || '] : '';
  116434. var lookup = ['('].concat(simple, nonHelper);
  116435. if (!this.options.strict) {
  116436. lookup.push(' || ', this.aliasable('helpers.helperMissing'));
  116437. }
  116438. lookup.push(')');
  116439. this.push(this.source.functionCall(lookup, 'call', helper.callParams));
  116440. },
  116441. // [invokeKnownHelper]
  116442. //
  116443. // On stack, before: hash, inverse, program, params..., ...
  116444. // On stack, after: result of helper invocation
  116445. //
  116446. // This operation is used when the helper is known to exist,
  116447. // so a `helperMissing` fallback is not required.
  116448. invokeKnownHelper: function invokeKnownHelper(paramSize, name) {
  116449. var helper = this.setupHelper(paramSize, name);
  116450. this.push(this.source.functionCall(helper.name, 'call', helper.callParams));
  116451. },
  116452. // [invokeAmbiguous]
  116453. //
  116454. // On stack, before: hash, inverse, program, params..., ...
  116455. // On stack, after: result of disambiguation
  116456. //
  116457. // This operation is used when an expression like `{{foo}}`
  116458. // is provided, but we don't know at compile-time whether it
  116459. // is a helper or a path.
  116460. //
  116461. // This operation emits more code than the other options,
  116462. // and can be avoided by passing the `knownHelpers` and
  116463. // `knownHelpersOnly` flags at compile-time.
  116464. invokeAmbiguous: function invokeAmbiguous(name, helperCall) {
  116465. this.useRegister('helper');
  116466. var nonHelper = this.popStack();
  116467. this.emptyHash();
  116468. var helper = this.setupHelper(0, name, helperCall);
  116469. var helperName = this.lastHelper = this.nameLookup('helpers', name, 'helper');
  116470. var lookup = ['(', '(helper = ', helperName, ' || ', nonHelper, ')'];
  116471. if (!this.options.strict) {
  116472. lookup[0] = '(helper = ';
  116473. lookup.push(' != null ? helper : ', this.aliasable('helpers.helperMissing'));
  116474. }
  116475. this.push(['(', lookup, helper.paramsInit ? ['),(', helper.paramsInit] : [], '),', '(typeof helper === ', this.aliasable('"function"'), ' ? ', this.source.functionCall('helper', 'call', helper.callParams), ' : helper))']);
  116476. },
  116477. // [invokePartial]
  116478. //
  116479. // On stack, before: context, ...
  116480. // On stack after: result of partial invocation
  116481. //
  116482. // This operation pops off a context, invokes a partial with that context,
  116483. // and pushes the result of the invocation back.
  116484. invokePartial: function invokePartial(isDynamic, name, indent) {
  116485. var params = [],
  116486. options = this.setupParams(name, 1, params);
  116487. if (isDynamic) {
  116488. name = this.popStack();
  116489. delete options.name;
  116490. }
  116491. if (indent) {
  116492. options.indent = JSON.stringify(indent);
  116493. }
  116494. options.helpers = 'helpers';
  116495. options.partials = 'partials';
  116496. options.decorators = 'container.decorators';
  116497. if (!isDynamic) {
  116498. params.unshift(this.nameLookup('partials', name, 'partial'));
  116499. } else {
  116500. params.unshift(name);
  116501. }
  116502. if (this.options.compat) {
  116503. options.depths = 'depths';
  116504. }
  116505. options = this.objectLiteral(options);
  116506. params.push(options);
  116507. this.push(this.source.functionCall('container.invokePartial', '', params));
  116508. },
  116509. // [assignToHash]
  116510. //
  116511. // On stack, before: value, ..., hash, ...
  116512. // On stack, after: ..., hash, ...
  116513. //
  116514. // Pops a value off the stack and assigns it to the current hash
  116515. assignToHash: function assignToHash(key) {
  116516. var value = this.popStack(),
  116517. context = undefined,
  116518. type = undefined,
  116519. id = undefined;
  116520. if (this.trackIds) {
  116521. id = this.popStack();
  116522. }
  116523. if (this.stringParams) {
  116524. type = this.popStack();
  116525. context = this.popStack();
  116526. }
  116527. var hash = this.hash;
  116528. if (context) {
  116529. hash.contexts[key] = context;
  116530. }
  116531. if (type) {
  116532. hash.types[key] = type;
  116533. }
  116534. if (id) {
  116535. hash.ids[key] = id;
  116536. }
  116537. hash.values[key] = value;
  116538. },
  116539. pushId: function pushId(type, name, child) {
  116540. if (type === 'BlockParam') {
  116541. this.pushStackLiteral('blockParams[' + name[0] + '].path[' + name[1] + ']' + (child ? ' + ' + JSON.stringify('.' + child) : ''));
  116542. } else if (type === 'PathExpression') {
  116543. this.pushString(name);
  116544. } else if (type === 'SubExpression') {
  116545. this.pushStackLiteral('true');
  116546. } else {
  116547. this.pushStackLiteral('null');
  116548. }
  116549. },
  116550. // HELPERS
  116551. compiler: JavaScriptCompiler,
  116552. compileChildren: function compileChildren(environment, options) {
  116553. var children = environment.children,
  116554. child = undefined,
  116555. compiler = undefined;
  116556. for (var i = 0, l = children.length; i < l; i++) {
  116557. child = children[i];
  116558. compiler = new this.compiler(); // eslint-disable-line new-cap
  116559. var existing = this.matchExistingProgram(child);
  116560. if (existing == null) {
  116561. this.context.programs.push(''); // Placeholder to prevent name conflicts for nested children
  116562. var index = this.context.programs.length;
  116563. child.index = index;
  116564. child.name = 'program' + index;
  116565. this.context.programs[index] = compiler.compile(child, options, this.context, !this.precompile);
  116566. this.context.decorators[index] = compiler.decorators;
  116567. this.context.environments[index] = child;
  116568. this.useDepths = this.useDepths || compiler.useDepths;
  116569. this.useBlockParams = this.useBlockParams || compiler.useBlockParams;
  116570. child.useDepths = this.useDepths;
  116571. child.useBlockParams = this.useBlockParams;
  116572. } else {
  116573. child.index = existing.index;
  116574. child.name = 'program' + existing.index;
  116575. this.useDepths = this.useDepths || existing.useDepths;
  116576. this.useBlockParams = this.useBlockParams || existing.useBlockParams;
  116577. }
  116578. }
  116579. },
  116580. matchExistingProgram: function matchExistingProgram(child) {
  116581. for (var i = 0, len = this.context.environments.length; i < len; i++) {
  116582. var environment = this.context.environments[i];
  116583. if (environment && environment.equals(child)) {
  116584. return environment;
  116585. }
  116586. }
  116587. },
  116588. programExpression: function programExpression(guid) {
  116589. var child = this.environment.children[guid],
  116590. programParams = [child.index, 'data', child.blockParams];
  116591. if (this.useBlockParams || this.useDepths) {
  116592. programParams.push('blockParams');
  116593. }
  116594. if (this.useDepths) {
  116595. programParams.push('depths');
  116596. }
  116597. return 'container.program(' + programParams.join(', ') + ')';
  116598. },
  116599. useRegister: function useRegister(name) {
  116600. if (!this.registers[name]) {
  116601. this.registers[name] = true;
  116602. this.registers.list.push(name);
  116603. }
  116604. },
  116605. push: function push(expr) {
  116606. if (!(expr instanceof Literal)) {
  116607. expr = this.source.wrap(expr);
  116608. }
  116609. this.inlineStack.push(expr);
  116610. return expr;
  116611. },
  116612. pushStackLiteral: function pushStackLiteral(item) {
  116613. this.push(new Literal(item));
  116614. },
  116615. pushSource: function pushSource(source) {
  116616. if (this.pendingContent) {
  116617. this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent), this.pendingLocation));
  116618. this.pendingContent = undefined;
  116619. }
  116620. if (source) {
  116621. this.source.push(source);
  116622. }
  116623. },
  116624. replaceStack: function replaceStack(callback) {
  116625. var prefix = ['('],
  116626. stack = undefined,
  116627. createdStack = undefined,
  116628. usedLiteral = undefined;
  116629. /* istanbul ignore next */
  116630. if (!this.isInline()) {
  116631. throw new _exception2['default']('replaceStack on non-inline');
  116632. }
  116633. // We want to merge the inline statement into the replacement statement via ','
  116634. var top = this.popStack(true);
  116635. if (top instanceof Literal) {
  116636. // Literals do not need to be inlined
  116637. stack = [top.value];
  116638. prefix = ['(', stack];
  116639. usedLiteral = true;
  116640. } else {
  116641. // Get or create the current stack name for use by the inline
  116642. createdStack = true;
  116643. var _name = this.incrStack();
  116644. prefix = ['((', this.push(_name), ' = ', top, ')'];
  116645. stack = this.topStack();
  116646. }
  116647. var item = callback.call(this, stack);
  116648. if (!usedLiteral) {
  116649. this.popStack();
  116650. }
  116651. if (createdStack) {
  116652. this.stackSlot--;
  116653. }
  116654. this.push(prefix.concat(item, ')'));
  116655. },
  116656. incrStack: function incrStack() {
  116657. this.stackSlot++;
  116658. if (this.stackSlot > this.stackVars.length) {
  116659. this.stackVars.push('stack' + this.stackSlot);
  116660. }
  116661. return this.topStackName();
  116662. },
  116663. topStackName: function topStackName() {
  116664. return 'stack' + this.stackSlot;
  116665. },
  116666. flushInline: function flushInline() {
  116667. var inlineStack = this.inlineStack;
  116668. this.inlineStack = [];
  116669. for (var i = 0, len = inlineStack.length; i < len; i++) {
  116670. var entry = inlineStack[i];
  116671. /* istanbul ignore if */
  116672. if (entry instanceof Literal) {
  116673. this.compileStack.push(entry);
  116674. } else {
  116675. var stack = this.incrStack();
  116676. this.pushSource([stack, ' = ', entry, ';']);
  116677. this.compileStack.push(stack);
  116678. }
  116679. }
  116680. },
  116681. isInline: function isInline() {
  116682. return this.inlineStack.length;
  116683. },
  116684. popStack: function popStack(wrapped) {
  116685. var inline = this.isInline(),
  116686. item = (inline ? this.inlineStack : this.compileStack).pop();
  116687. if (!wrapped && item instanceof Literal) {
  116688. return item.value;
  116689. } else {
  116690. if (!inline) {
  116691. /* istanbul ignore next */
  116692. if (!this.stackSlot) {
  116693. throw new _exception2['default']('Invalid stack pop');
  116694. }
  116695. this.stackSlot--;
  116696. }
  116697. return item;
  116698. }
  116699. },
  116700. topStack: function topStack() {
  116701. var stack = this.isInline() ? this.inlineStack : this.compileStack,
  116702. item = stack[stack.length - 1];
  116703. /* istanbul ignore if */
  116704. if (item instanceof Literal) {
  116705. return item.value;
  116706. } else {
  116707. return item;
  116708. }
  116709. },
  116710. contextName: function contextName(context) {
  116711. if (this.useDepths && context) {
  116712. return 'depths[' + context + ']';
  116713. } else {
  116714. return 'depth' + context;
  116715. }
  116716. },
  116717. quotedString: function quotedString(str) {
  116718. return this.source.quotedString(str);
  116719. },
  116720. objectLiteral: function objectLiteral(obj) {
  116721. return this.source.objectLiteral(obj);
  116722. },
  116723. aliasable: function aliasable(name) {
  116724. var ret = this.aliases[name];
  116725. if (ret) {
  116726. ret.referenceCount++;
  116727. return ret;
  116728. }
  116729. ret = this.aliases[name] = this.source.wrap(name);
  116730. ret.aliasable = true;
  116731. ret.referenceCount = 1;
  116732. return ret;
  116733. },
  116734. setupHelper: function setupHelper(paramSize, name, blockHelper) {
  116735. var params = [],
  116736. paramsInit = this.setupHelperArgs(name, paramSize, params, blockHelper);
  116737. var foundHelper = this.nameLookup('helpers', name, 'helper'),
  116738. callContext = this.aliasable(this.contextName(0) + ' != null ? ' + this.contextName(0) + ' : (container.nullContext || {})');
  116739. return {
  116740. params: params,
  116741. paramsInit: paramsInit,
  116742. name: foundHelper,
  116743. callParams: [callContext].concat(params)
  116744. };
  116745. },
  116746. setupParams: function setupParams(helper, paramSize, params) {
  116747. var options = {},
  116748. contexts = [],
  116749. types = [],
  116750. ids = [],
  116751. objectArgs = !params,
  116752. param = undefined;
  116753. if (objectArgs) {
  116754. params = [];
  116755. }
  116756. options.name = this.quotedString(helper);
  116757. options.hash = this.popStack();
  116758. if (this.trackIds) {
  116759. options.hashIds = this.popStack();
  116760. }
  116761. if (this.stringParams) {
  116762. options.hashTypes = this.popStack();
  116763. options.hashContexts = this.popStack();
  116764. }
  116765. var inverse = this.popStack(),
  116766. program = this.popStack();
  116767. // Avoid setting fn and inverse if neither are set. This allows
  116768. // helpers to do a check for `if (options.fn)`
  116769. if (program || inverse) {
  116770. options.fn = program || 'container.noop';
  116771. options.inverse = inverse || 'container.noop';
  116772. }
  116773. // The parameters go on to the stack in order (making sure that they are evaluated in order)
  116774. // so we need to pop them off the stack in reverse order
  116775. var i = paramSize;
  116776. while (i--) {
  116777. param = this.popStack();
  116778. params[i] = param;
  116779. if (this.trackIds) {
  116780. ids[i] = this.popStack();
  116781. }
  116782. if (this.stringParams) {
  116783. types[i] = this.popStack();
  116784. contexts[i] = this.popStack();
  116785. }
  116786. }
  116787. if (objectArgs) {
  116788. options.args = this.source.generateArray(params);
  116789. }
  116790. if (this.trackIds) {
  116791. options.ids = this.source.generateArray(ids);
  116792. }
  116793. if (this.stringParams) {
  116794. options.types = this.source.generateArray(types);
  116795. options.contexts = this.source.generateArray(contexts);
  116796. }
  116797. if (this.options.data) {
  116798. options.data = 'data';
  116799. }
  116800. if (this.useBlockParams) {
  116801. options.blockParams = 'blockParams';
  116802. }
  116803. return options;
  116804. },
  116805. setupHelperArgs: function setupHelperArgs(helper, paramSize, params, useRegister) {
  116806. var options = this.setupParams(helper, paramSize, params);
  116807. options = this.objectLiteral(options);
  116808. if (useRegister) {
  116809. this.useRegister('options');
  116810. params.push('options');
  116811. return ['options=', options];
  116812. } else if (params) {
  116813. params.push(options);
  116814. return '';
  116815. } else {
  116816. return options;
  116817. }
  116818. }
  116819. };
  116820. (function () {
  116821. var reservedWords = ('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(' ');
  116822. var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {};
  116823. for (var i = 0, l = reservedWords.length; i < l; i++) {
  116824. compilerWords[reservedWords[i]] = true;
  116825. }
  116826. })();
  116827. JavaScriptCompiler.isValidJavaScriptVariableName = function (name) {
  116828. return !JavaScriptCompiler.RESERVED_WORDS[name] && /^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name);
  116829. };
  116830. function strictLookup(requireTerminal, compiler, parts, type) {
  116831. var stack = compiler.popStack(),
  116832. i = 0,
  116833. len = parts.length;
  116834. if (requireTerminal) {
  116835. len--;
  116836. }
  116837. for (; i < len; i++) {
  116838. stack = compiler.nameLookup(stack, parts[i], type);
  116839. }
  116840. if (requireTerminal) {
  116841. return [compiler.aliasable('container.strict'), '(', stack, ', ', compiler.quotedString(parts[i]), ')'];
  116842. } else {
  116843. return stack;
  116844. }
  116845. }
  116846. exports['default'] = JavaScriptCompiler;
  116847. module.exports = exports['default'];
  116848. /***/ }),
  116849. /* 43 */
  116850. /***/ (function(module, exports, __webpack_require__) {
  116851. /* global define */
  116852. 'use strict';
  116853. exports.__esModule = true;
  116854. var _utils = __webpack_require__(5);
  116855. var SourceNode = undefined;
  116856. try {
  116857. /* istanbul ignore next */
  116858. if (false) {
  116859. // We don't support this in AMD environments. For these environments, we asusme that
  116860. // they are running on the browser and thus have no need for the source-map library.
  116861. var SourceMap = require('source-map');
  116862. SourceNode = SourceMap.SourceNode;
  116863. }
  116864. } catch (err) {}
  116865. /* NOP */
  116866. /* istanbul ignore if: tested but not covered in istanbul due to dist build */
  116867. if (!SourceNode) {
  116868. SourceNode = function (line, column, srcFile, chunks) {
  116869. this.src = '';
  116870. if (chunks) {
  116871. this.add(chunks);
  116872. }
  116873. };
  116874. /* istanbul ignore next */
  116875. SourceNode.prototype = {
  116876. add: function add(chunks) {
  116877. if (_utils.isArray(chunks)) {
  116878. chunks = chunks.join('');
  116879. }
  116880. this.src += chunks;
  116881. },
  116882. prepend: function prepend(chunks) {
  116883. if (_utils.isArray(chunks)) {
  116884. chunks = chunks.join('');
  116885. }
  116886. this.src = chunks + this.src;
  116887. },
  116888. toStringWithSourceMap: function toStringWithSourceMap() {
  116889. return { code: this.toString() };
  116890. },
  116891. toString: function toString() {
  116892. return this.src;
  116893. }
  116894. };
  116895. }
  116896. function castChunk(chunk, codeGen, loc) {
  116897. if (_utils.isArray(chunk)) {
  116898. var ret = [];
  116899. for (var i = 0, len = chunk.length; i < len; i++) {
  116900. ret.push(codeGen.wrap(chunk[i], loc));
  116901. }
  116902. return ret;
  116903. } else if (typeof chunk === 'boolean' || typeof chunk === 'number') {
  116904. // Handle primitives that the SourceNode will throw up on
  116905. return chunk + '';
  116906. }
  116907. return chunk;
  116908. }
  116909. function CodeGen(srcFile) {
  116910. this.srcFile = srcFile;
  116911. this.source = [];
  116912. }
  116913. CodeGen.prototype = {
  116914. isEmpty: function isEmpty() {
  116915. return !this.source.length;
  116916. },
  116917. prepend: function prepend(source, loc) {
  116918. this.source.unshift(this.wrap(source, loc));
  116919. },
  116920. push: function push(source, loc) {
  116921. this.source.push(this.wrap(source, loc));
  116922. },
  116923. merge: function merge() {
  116924. var source = this.empty();
  116925. this.each(function (line) {
  116926. source.add([' ', line, '\n']);
  116927. });
  116928. return source;
  116929. },
  116930. each: function each(iter) {
  116931. for (var i = 0, len = this.source.length; i < len; i++) {
  116932. iter(this.source[i]);
  116933. }
  116934. },
  116935. empty: function empty() {
  116936. var loc = this.currentLocation || { start: {} };
  116937. return new SourceNode(loc.start.line, loc.start.column, this.srcFile);
  116938. },
  116939. wrap: function wrap(chunk) {
  116940. var loc = arguments.length <= 1 || arguments[1] === undefined ? this.currentLocation || { start: {} } : arguments[1];
  116941. if (chunk instanceof SourceNode) {
  116942. return chunk;
  116943. }
  116944. chunk = castChunk(chunk, this, loc);
  116945. return new SourceNode(loc.start.line, loc.start.column, this.srcFile, chunk);
  116946. },
  116947. functionCall: function functionCall(fn, type, params) {
  116948. params = this.generateList(params);
  116949. return this.wrap([fn, type ? '.' + type + '(' : '(', params, ')']);
  116950. },
  116951. quotedString: function quotedString(str) {
  116952. return '"' + (str + '').replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\u2028/g, '\\u2028') // Per Ecma-262 7.3 + 7.8.4
  116953. .replace(/\u2029/g, '\\u2029') + '"';
  116954. },
  116955. objectLiteral: function objectLiteral(obj) {
  116956. var pairs = [];
  116957. for (var key in obj) {
  116958. if (obj.hasOwnProperty(key)) {
  116959. var value = castChunk(obj[key], this);
  116960. if (value !== 'undefined') {
  116961. pairs.push([this.quotedString(key), ':', value]);
  116962. }
  116963. }
  116964. }
  116965. var ret = this.generateList(pairs);
  116966. ret.prepend('{');
  116967. ret.add('}');
  116968. return ret;
  116969. },
  116970. generateList: function generateList(entries) {
  116971. var ret = this.empty();
  116972. for (var i = 0, len = entries.length; i < len; i++) {
  116973. if (i) {
  116974. ret.add(',');
  116975. }
  116976. ret.add(castChunk(entries[i], this));
  116977. }
  116978. return ret;
  116979. },
  116980. generateArray: function generateArray(entries) {
  116981. var ret = this.generateList(entries);
  116982. ret.prepend('[');
  116983. ret.add(']');
  116984. return ret;
  116985. }
  116986. };
  116987. exports['default'] = CodeGen;
  116988. module.exports = exports['default'];
  116989. /***/ })
  116990. /******/ ])
  116991. });
  116992. ;
  116993. /***/ }),
  116994. /* 63 */
  116995. /***/ (function(module, exports, __webpack_require__) {
  116996. "use strict";
  116997. Object.defineProperty(exports, "__esModule", { value: true });
  116998. /**
  116999. * The EventManager is in charge of registering user interctions with the viewer.
  117000. * It is used in the TemplateManager
  117001. */
  117002. var EventManager = /** @class */ (function () {
  117003. function EventManager(_templateManager) {
  117004. var _this = this;
  117005. this._templateManager = _templateManager;
  117006. this._callbacksContainer = {};
  117007. this._templateManager.onEventTriggered.add(function (eventData) {
  117008. _this._eventTriggered(eventData);
  117009. });
  117010. }
  117011. /**
  117012. * Register a new callback to a specific template.
  117013. * The best example for the usage can be found in the DefaultViewer
  117014. *
  117015. * @param templateName the templateName to register the event to
  117016. * @param callback The callback to be executed
  117017. * @param eventType the type of event to register
  117018. * @param selector an optional selector. if not defined the parent object in the template will be selected
  117019. */
  117020. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  117021. if (!this._callbacksContainer[templateName]) {
  117022. this._callbacksContainer[templateName] = [];
  117023. }
  117024. this._callbacksContainer[templateName].push({
  117025. eventType: eventType,
  117026. callback: callback,
  117027. selector: selector
  117028. });
  117029. };
  117030. /**
  117031. * This will remove a registered event from the defined template.
  117032. * Each one of the variables apart from the template name are optional, but one must be provided.
  117033. *
  117034. * @param templateName the templateName
  117035. * @param callback the callback to remove (optional)
  117036. * @param eventType the event type to remove (optional)
  117037. * @param selector the selector from which to remove the event (optional)
  117038. */
  117039. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  117040. var callbackDefs = this._callbacksContainer[templateName] || [];
  117041. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  117042. };
  117043. EventManager.prototype._eventTriggered = function (data) {
  117044. var templateName = data.template.name;
  117045. var eventType = data.event.type;
  117046. var selector = data.selector;
  117047. var callbackDefs = this._callbacksContainer[templateName] || [];
  117048. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  117049. callbackDef.callback(data);
  117050. });
  117051. };
  117052. /**
  117053. * Dispose the event manager
  117054. */
  117055. EventManager.prototype.dispose = function () {
  117056. this._callbacksContainer = {};
  117057. };
  117058. return EventManager;
  117059. }());
  117060. exports.EventManager = EventManager;
  117061. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXZlbnRNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3RlbXBsYXRpbmcvZXZlbnRNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBR0E7OztHQUdHO0FBQ0g7SUFJSSxzQkFBb0IsZ0JBQWlDO1FBQXJELGlCQUtDO1FBTG1CLHFCQUFnQixHQUFoQixnQkFBZ0IsQ0FBaUI7UUFDakQsSUFBSSxDQUFDLG1CQUFtQixHQUFHLEVBQUUsQ0FBQztRQUM5QixJQUFJLENBQUMsZ0JBQWdCLENBQUMsZ0JBQWdCLENBQUMsR0FBRyxDQUFDLFVBQUEsU0FBUztZQUNoRCxLQUFJLENBQUMsZUFBZSxDQUFDLFNBQVMsQ0FBQyxDQUFDO1FBQ3BDLENBQUMsQ0FBQyxDQUFBO0lBQ04sQ0FBQztJQUVEOzs7Ozs7OztPQVFHO0lBQ0ksdUNBQWdCLEdBQXZCLFVBQXdCLFlBQW9CLEVBQUUsUUFBNEMsRUFBRSxTQUFrQixFQUFFLFFBQWlCO1FBQzdILElBQUksQ0FBQyxJQUFJLENBQUMsbUJBQW1CLENBQUMsWUFBWSxDQUFDLEVBQUU7WUFDekMsSUFBSSxDQUFDLG1CQUFtQixDQUFDLFlBQVksQ0FBQyxHQUFHLEVBQUUsQ0FBQztTQUMvQztRQUNELElBQUksQ0FBQyxtQkFBbUIsQ0FBQyxZQUFZLENBQUMsQ0FBQyxJQUFJLENBQUM7WUFDeEMsU0FBUyxXQUFBO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sQ0FBQyxJQUFJLENBQUMsQ0FBQyxXQUFXLENBQUMsUUFBUSxJQUFJLFdBQVcsQ0FBQyxRQUFRLEtBQUssUUFBUSxDQUFDLEVBQS9ILENBQStILENBQUMsQ0FBQyxPQUFPLENBQUMsVUFBQSxXQUFXO1lBQ25MLFdBQVcsQ0FBQyxRQUFRLENBQUMsSUFBSSxDQUFDLENBQUM7UUFDL0IsQ0FBQyxDQUFDLENBQUM7SUFDUCxDQUFDO0lBRUQ7O09BRUc7SUFDSSw4QkFBTyxHQUFkO1FBQ0ksSUFBSSxDQUFDLG1CQUFtQixHQUFHLEVBQUUsQ0FBQztJQUNsQyxDQUFDO0lBQ0wsbUJBQUM7QUFBRCxDQUFDLEFBOURELElBOERDO0FBOURZLG9DQUFZIn0=
  117062. /***/ }),
  117063. /* 64 */
  117064. /***/ (function(module, exports, __webpack_require__) {
  117065. /*!
  117066. * PEP v0.4.3 | https://github.com/jquery/PEP
  117067. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  117068. */
  117069. (function (global, factory) {
  117070. true ? module.exports = factory() :
  117071. typeof define === 'function' && define.amd ? define(factory) :
  117072. (global.PointerEventsPolyfill = factory());
  117073. }(this, function () { 'use strict';
  117074. /**
  117075. * This is the constructor for new PointerEvents.
  117076. *
  117077. * New Pointer Events must be given a type, and an optional dictionary of
  117078. * initialization properties.
  117079. *
  117080. * Due to certain platform requirements, events returned from the constructor
  117081. * identify as MouseEvents.
  117082. *
  117083. * @constructor
  117084. * @param {String} inType The type of the event to create.
  117085. * @param {Object} [inDict] An optional dictionary of initial event properties.
  117086. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  117087. */
  117088. var MOUSE_PROPS = [
  117089. 'bubbles',
  117090. 'cancelable',
  117091. 'view',
  117092. 'detail',
  117093. 'screenX',
  117094. 'screenY',
  117095. 'clientX',
  117096. 'clientY',
  117097. 'ctrlKey',
  117098. 'altKey',
  117099. 'shiftKey',
  117100. 'metaKey',
  117101. 'button',
  117102. 'relatedTarget',
  117103. 'pageX',
  117104. 'pageY'
  117105. ];
  117106. var MOUSE_DEFAULTS = [
  117107. false,
  117108. false,
  117109. null,
  117110. null,
  117111. 0,
  117112. 0,
  117113. 0,
  117114. 0,
  117115. false,
  117116. false,
  117117. false,
  117118. false,
  117119. 0,
  117120. null,
  117121. 0,
  117122. 0
  117123. ];
  117124. function PointerEvent(inType, inDict) {
  117125. inDict = inDict || Object.create(null);
  117126. var e = document.createEvent('Event');
  117127. e.initEvent(inType, inDict.bubbles || false, inDict.cancelable || false);
  117128. // define inherited MouseEvent properties
  117129. // skip bubbles and cancelable since they're set above in initEvent()
  117130. for (var i = 2, p; i < MOUSE_PROPS.length; i++) {
  117131. p = MOUSE_PROPS[i];
  117132. e[p] = inDict[p] || MOUSE_DEFAULTS[i];
  117133. }
  117134. e.buttons = inDict.buttons || 0;
  117135. // Spec requires that pointers without pressure specified use 0.5 for down
  117136. // state and 0 for up state.
  117137. var pressure = 0;
  117138. if (inDict.pressure && e.buttons) {
  117139. pressure = inDict.pressure;
  117140. } else {
  117141. pressure = e.buttons ? 0.5 : 0;
  117142. }
  117143. // add x/y properties aliased to clientX/Y
  117144. e.x = e.clientX;
  117145. e.y = e.clientY;
  117146. // define the properties of the PointerEvent interface
  117147. e.pointerId = inDict.pointerId || 0;
  117148. e.width = inDict.width || 0;
  117149. e.height = inDict.height || 0;
  117150. e.pressure = pressure;
  117151. e.tiltX = inDict.tiltX || 0;
  117152. e.tiltY = inDict.tiltY || 0;
  117153. e.twist = inDict.twist || 0;
  117154. e.tangentialPressure = inDict.tangentialPressure || 0;
  117155. e.pointerType = inDict.pointerType || '';
  117156. e.hwTimestamp = inDict.hwTimestamp || 0;
  117157. e.isPrimary = inDict.isPrimary || false;
  117158. return e;
  117159. }
  117160. /**
  117161. * This module implements a map of pointer states
  117162. */
  117163. var USE_MAP = window.Map && window.Map.prototype.forEach;
  117164. var PointerMap = USE_MAP ? Map : SparseArrayMap;
  117165. function SparseArrayMap() {
  117166. this.array = [];
  117167. this.size = 0;
  117168. }
  117169. SparseArrayMap.prototype = {
  117170. set: function(k, v) {
  117171. if (v === undefined) {
  117172. return this.delete(k);
  117173. }
  117174. if (!this.has(k)) {
  117175. this.size++;
  117176. }
  117177. this.array[k] = v;
  117178. },
  117179. has: function(k) {
  117180. return this.array[k] !== undefined;
  117181. },
  117182. delete: function(k) {
  117183. if (this.has(k)) {
  117184. delete this.array[k];
  117185. this.size--;
  117186. }
  117187. },
  117188. get: function(k) {
  117189. return this.array[k];
  117190. },
  117191. clear: function() {
  117192. this.array.length = 0;
  117193. this.size = 0;
  117194. },
  117195. // return value, key, map
  117196. forEach: function(callback, thisArg) {
  117197. return this.array.forEach(function(v, k) {
  117198. callback.call(thisArg, v, k, this);
  117199. }, this);
  117200. }
  117201. };
  117202. var CLONE_PROPS = [
  117203. // MouseEvent
  117204. 'bubbles',
  117205. 'cancelable',
  117206. 'view',
  117207. 'detail',
  117208. 'screenX',
  117209. 'screenY',
  117210. 'clientX',
  117211. 'clientY',
  117212. 'ctrlKey',
  117213. 'altKey',
  117214. 'shiftKey',
  117215. 'metaKey',
  117216. 'button',
  117217. 'relatedTarget',
  117218. // DOM Level 3
  117219. 'buttons',
  117220. // PointerEvent
  117221. 'pointerId',
  117222. 'width',
  117223. 'height',
  117224. 'pressure',
  117225. 'tiltX',
  117226. 'tiltY',
  117227. 'pointerType',
  117228. 'hwTimestamp',
  117229. 'isPrimary',
  117230. // event instance
  117231. 'type',
  117232. 'target',
  117233. 'currentTarget',
  117234. 'which',
  117235. 'pageX',
  117236. 'pageY',
  117237. 'timeStamp'
  117238. ];
  117239. var CLONE_DEFAULTS = [
  117240. // MouseEvent
  117241. false,
  117242. false,
  117243. null,
  117244. null,
  117245. 0,
  117246. 0,
  117247. 0,
  117248. 0,
  117249. false,
  117250. false,
  117251. false,
  117252. false,
  117253. 0,
  117254. null,
  117255. // DOM Level 3
  117256. 0,
  117257. // PointerEvent
  117258. 0,
  117259. 0,
  117260. 0,
  117261. 0,
  117262. 0,
  117263. 0,
  117264. '',
  117265. 0,
  117266. false,
  117267. // event instance
  117268. '',
  117269. null,
  117270. null,
  117271. 0,
  117272. 0,
  117273. 0,
  117274. 0
  117275. ];
  117276. var BOUNDARY_EVENTS = {
  117277. 'pointerover': 1,
  117278. 'pointerout': 1,
  117279. 'pointerenter': 1,
  117280. 'pointerleave': 1
  117281. };
  117282. var HAS_SVG_INSTANCE = (typeof SVGElementInstance !== 'undefined');
  117283. /**
  117284. * This module is for normalizing events. Mouse and Touch events will be
  117285. * collected here, and fire PointerEvents that have the same semantics, no
  117286. * matter the source.
  117287. * Events fired:
  117288. * - pointerdown: a pointing is added
  117289. * - pointerup: a pointer is removed
  117290. * - pointermove: a pointer is moved
  117291. * - pointerover: a pointer crosses into an element
  117292. * - pointerout: a pointer leaves an element
  117293. * - pointercancel: a pointer will no longer generate events
  117294. */
  117295. var dispatcher = {
  117296. pointermap: new PointerMap(),
  117297. eventMap: Object.create(null),
  117298. captureInfo: Object.create(null),
  117299. // Scope objects for native events.
  117300. // This exists for ease of testing.
  117301. eventSources: Object.create(null),
  117302. eventSourceList: [],
  117303. /**
  117304. * Add a new event source that will generate pointer events.
  117305. *
  117306. * `inSource` must contain an array of event names named `events`, and
  117307. * functions with the names specified in the `events` array.
  117308. * @param {string} name A name for the event source
  117309. * @param {Object} source A new source of platform events.
  117310. */
  117311. registerSource: function(name, source) {
  117312. var s = source;
  117313. var newEvents = s.events;
  117314. if (newEvents) {
  117315. newEvents.forEach(function(e) {
  117316. if (s[e]) {
  117317. this.eventMap[e] = s[e].bind(s);
  117318. }
  117319. }, this);
  117320. this.eventSources[name] = s;
  117321. this.eventSourceList.push(s);
  117322. }
  117323. },
  117324. register: function(element) {
  117325. var l = this.eventSourceList.length;
  117326. for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) {
  117327. // call eventsource register
  117328. es.register.call(es, element);
  117329. }
  117330. },
  117331. unregister: function(element) {
  117332. var l = this.eventSourceList.length;
  117333. for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) {
  117334. // call eventsource register
  117335. es.unregister.call(es, element);
  117336. }
  117337. },
  117338. contains: /*scope.external.contains || */function(container, contained) {
  117339. try {
  117340. return container.contains(contained);
  117341. } catch (ex) {
  117342. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  117343. return false;
  117344. }
  117345. },
  117346. // EVENTS
  117347. down: function(inEvent) {
  117348. inEvent.bubbles = true;
  117349. this.fireEvent('pointerdown', inEvent);
  117350. },
  117351. move: function(inEvent) {
  117352. inEvent.bubbles = true;
  117353. this.fireEvent('pointermove', inEvent);
  117354. },
  117355. up: function(inEvent) {
  117356. inEvent.bubbles = true;
  117357. this.fireEvent('pointerup', inEvent);
  117358. },
  117359. enter: function(inEvent) {
  117360. inEvent.bubbles = false;
  117361. this.fireEvent('pointerenter', inEvent);
  117362. },
  117363. leave: function(inEvent) {
  117364. inEvent.bubbles = false;
  117365. this.fireEvent('pointerleave', inEvent);
  117366. },
  117367. over: function(inEvent) {
  117368. inEvent.bubbles = true;
  117369. this.fireEvent('pointerover', inEvent);
  117370. },
  117371. out: function(inEvent) {
  117372. inEvent.bubbles = true;
  117373. this.fireEvent('pointerout', inEvent);
  117374. },
  117375. cancel: function(inEvent) {
  117376. inEvent.bubbles = true;
  117377. this.fireEvent('pointercancel', inEvent);
  117378. },
  117379. leaveOut: function(event) {
  117380. this.out(event);
  117381. this.propagate(event, this.leave, false);
  117382. },
  117383. enterOver: function(event) {
  117384. this.over(event);
  117385. this.propagate(event, this.enter, true);
  117386. },
  117387. // LISTENER LOGIC
  117388. eventHandler: function(inEvent) {
  117389. // This is used to prevent multiple dispatch of pointerevents from
  117390. // platform events. This can happen when two elements in different scopes
  117391. // are set up to create pointer events, which is relevant to Shadow DOM.
  117392. if (inEvent._handledByPE) {
  117393. return;
  117394. }
  117395. var type = inEvent.type;
  117396. var fn = this.eventMap && this.eventMap[type];
  117397. if (fn) {
  117398. fn(inEvent);
  117399. }
  117400. inEvent._handledByPE = true;
  117401. },
  117402. // set up event listeners
  117403. listen: function(target, events) {
  117404. events.forEach(function(e) {
  117405. this.addEvent(target, e);
  117406. }, this);
  117407. },
  117408. // remove event listeners
  117409. unlisten: function(target, events) {
  117410. events.forEach(function(e) {
  117411. this.removeEvent(target, e);
  117412. }, this);
  117413. },
  117414. addEvent: /*scope.external.addEvent || */function(target, eventName) {
  117415. target.addEventListener(eventName, this.boundHandler);
  117416. },
  117417. removeEvent: /*scope.external.removeEvent || */function(target, eventName) {
  117418. target.removeEventListener(eventName, this.boundHandler);
  117419. },
  117420. // EVENT CREATION AND TRACKING
  117421. /**
  117422. * Creates a new Event of type `inType`, based on the information in
  117423. * `inEvent`.
  117424. *
  117425. * @param {string} inType A string representing the type of event to create
  117426. * @param {Event} inEvent A platform event with a target
  117427. * @return {Event} A PointerEvent of type `inType`
  117428. */
  117429. makeEvent: function(inType, inEvent) {
  117430. // relatedTarget must be null if pointer is captured
  117431. if (this.captureInfo[inEvent.pointerId]) {
  117432. inEvent.relatedTarget = null;
  117433. }
  117434. var e = new PointerEvent(inType, inEvent);
  117435. if (inEvent.preventDefault) {
  117436. e.preventDefault = inEvent.preventDefault;
  117437. }
  117438. e._target = e._target || inEvent.target;
  117439. return e;
  117440. },
  117441. // make and dispatch an event in one call
  117442. fireEvent: function(inType, inEvent) {
  117443. var e = this.makeEvent(inType, inEvent);
  117444. return this.dispatchEvent(e);
  117445. },
  117446. /**
  117447. * Returns a snapshot of inEvent, with writable properties.
  117448. *
  117449. * @param {Event} inEvent An event that contains properties to copy.
  117450. * @return {Object} An object containing shallow copies of `inEvent`'s
  117451. * properties.
  117452. */
  117453. cloneEvent: function(inEvent) {
  117454. var eventCopy = Object.create(null);
  117455. var p;
  117456. for (var i = 0; i < CLONE_PROPS.length; i++) {
  117457. p = CLONE_PROPS[i];
  117458. eventCopy[p] = inEvent[p] || CLONE_DEFAULTS[i];
  117459. // Work around SVGInstanceElement shadow tree
  117460. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  117461. // This is the behavior implemented by Firefox.
  117462. if (HAS_SVG_INSTANCE && (p === 'target' || p === 'relatedTarget')) {
  117463. if (eventCopy[p] instanceof SVGElementInstance) {
  117464. eventCopy[p] = eventCopy[p].correspondingUseElement;
  117465. }
  117466. }
  117467. }
  117468. // keep the semantics of preventDefault
  117469. if (inEvent.preventDefault) {
  117470. eventCopy.preventDefault = function() {
  117471. inEvent.preventDefault();
  117472. };
  117473. }
  117474. return eventCopy;
  117475. },
  117476. getTarget: function(inEvent) {
  117477. var capture = this.captureInfo[inEvent.pointerId];
  117478. if (!capture) {
  117479. return inEvent._target;
  117480. }
  117481. if (inEvent._target === capture || !(inEvent.type in BOUNDARY_EVENTS)) {
  117482. return capture;
  117483. }
  117484. },
  117485. propagate: function(event, fn, propagateDown) {
  117486. var target = event.target;
  117487. var targets = [];
  117488. // Order of conditions due to document.contains() missing in IE.
  117489. while (target !== document && !target.contains(event.relatedTarget)) {
  117490. targets.push(target);
  117491. target = target.parentNode;
  117492. // Touch: Do not propagate if node is detached.
  117493. if (!target) {
  117494. return;
  117495. }
  117496. }
  117497. if (propagateDown) {
  117498. targets.reverse();
  117499. }
  117500. targets.forEach(function(target) {
  117501. event.target = target;
  117502. fn.call(this, event);
  117503. }, this);
  117504. },
  117505. setCapture: function(inPointerId, inTarget, skipDispatch) {
  117506. if (this.captureInfo[inPointerId]) {
  117507. this.releaseCapture(inPointerId, skipDispatch);
  117508. }
  117509. this.captureInfo[inPointerId] = inTarget;
  117510. this.implicitRelease = this.releaseCapture.bind(this, inPointerId, skipDispatch);
  117511. document.addEventListener('pointerup', this.implicitRelease);
  117512. document.addEventListener('pointercancel', this.implicitRelease);
  117513. var e = new PointerEvent('gotpointercapture');
  117514. e.pointerId = inPointerId;
  117515. e._target = inTarget;
  117516. if (!skipDispatch) {
  117517. this.asyncDispatchEvent(e);
  117518. }
  117519. },
  117520. releaseCapture: function(inPointerId, skipDispatch) {
  117521. var t = this.captureInfo[inPointerId];
  117522. if (!t) {
  117523. return;
  117524. }
  117525. this.captureInfo[inPointerId] = undefined;
  117526. document.removeEventListener('pointerup', this.implicitRelease);
  117527. document.removeEventListener('pointercancel', this.implicitRelease);
  117528. var e = new PointerEvent('lostpointercapture');
  117529. e.pointerId = inPointerId;
  117530. e._target = t;
  117531. if (!skipDispatch) {
  117532. this.asyncDispatchEvent(e);
  117533. }
  117534. },
  117535. /**
  117536. * Dispatches the event to its target.
  117537. *
  117538. * @param {Event} inEvent The event to be dispatched.
  117539. * @return {Boolean} True if an event handler returns true, false otherwise.
  117540. */
  117541. dispatchEvent: /*scope.external.dispatchEvent || */function(inEvent) {
  117542. var t = this.getTarget(inEvent);
  117543. if (t) {
  117544. return t.dispatchEvent(inEvent);
  117545. }
  117546. },
  117547. asyncDispatchEvent: function(inEvent) {
  117548. requestAnimationFrame(this.dispatchEvent.bind(this, inEvent));
  117549. }
  117550. };
  117551. dispatcher.boundHandler = dispatcher.eventHandler.bind(dispatcher);
  117552. var targeting = {
  117553. shadow: function(inEl) {
  117554. if (inEl) {
  117555. return inEl.shadowRoot || inEl.webkitShadowRoot;
  117556. }
  117557. },
  117558. canTarget: function(shadow) {
  117559. return shadow && Boolean(shadow.elementFromPoint);
  117560. },
  117561. targetingShadow: function(inEl) {
  117562. var s = this.shadow(inEl);
  117563. if (this.canTarget(s)) {
  117564. return s;
  117565. }
  117566. },
  117567. olderShadow: function(shadow) {
  117568. var os = shadow.olderShadowRoot;
  117569. if (!os) {
  117570. var se = shadow.querySelector('shadow');
  117571. if (se) {
  117572. os = se.olderShadowRoot;
  117573. }
  117574. }
  117575. return os;
  117576. },
  117577. allShadows: function(element) {
  117578. var shadows = [];
  117579. var s = this.shadow(element);
  117580. while (s) {
  117581. shadows.push(s);
  117582. s = this.olderShadow(s);
  117583. }
  117584. return shadows;
  117585. },
  117586. searchRoot: function(inRoot, x, y) {
  117587. if (inRoot) {
  117588. var t = inRoot.elementFromPoint(x, y);
  117589. var st, sr;
  117590. // is element a shadow host?
  117591. sr = this.targetingShadow(t);
  117592. while (sr) {
  117593. // find the the element inside the shadow root
  117594. st = sr.elementFromPoint(x, y);
  117595. if (!st) {
  117596. // check for older shadows
  117597. sr = this.olderShadow(sr);
  117598. } else {
  117599. // shadowed element may contain a shadow root
  117600. var ssr = this.targetingShadow(st);
  117601. return this.searchRoot(ssr, x, y) || st;
  117602. }
  117603. }
  117604. // light dom element is the target
  117605. return t;
  117606. }
  117607. },
  117608. owner: function(element) {
  117609. var s = element;
  117610. // walk up until you hit the shadow root or document
  117611. while (s.parentNode) {
  117612. s = s.parentNode;
  117613. }
  117614. // the owner element is expected to be a Document or ShadowRoot
  117615. if (s.nodeType !== Node.DOCUMENT_NODE && s.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {
  117616. s = document;
  117617. }
  117618. return s;
  117619. },
  117620. findTarget: function(inEvent) {
  117621. var x = inEvent.clientX;
  117622. var y = inEvent.clientY;
  117623. // if the listener is in the shadow root, it is much faster to start there
  117624. var s = this.owner(inEvent.target);
  117625. // if x, y is not in this root, fall back to document search
  117626. if (!s.elementFromPoint(x, y)) {
  117627. s = document;
  117628. }
  117629. return this.searchRoot(s, x, y);
  117630. }
  117631. };
  117632. var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);
  117633. var map = Array.prototype.map.call.bind(Array.prototype.map);
  117634. var toArray = Array.prototype.slice.call.bind(Array.prototype.slice);
  117635. var filter = Array.prototype.filter.call.bind(Array.prototype.filter);
  117636. var MO = window.MutationObserver || window.WebKitMutationObserver;
  117637. var SELECTOR = '[touch-action]';
  117638. var OBSERVER_INIT = {
  117639. subtree: true,
  117640. childList: true,
  117641. attributes: true,
  117642. attributeOldValue: true,
  117643. attributeFilter: ['touch-action']
  117644. };
  117645. function Installer(add, remove, changed, binder) {
  117646. this.addCallback = add.bind(binder);
  117647. this.removeCallback = remove.bind(binder);
  117648. this.changedCallback = changed.bind(binder);
  117649. if (MO) {
  117650. this.observer = new MO(this.mutationWatcher.bind(this));
  117651. }
  117652. }
  117653. Installer.prototype = {
  117654. watchSubtree: function(target) {
  117655. // Only watch scopes that can target find, as these are top-level.
  117656. // Otherwise we can see duplicate additions and removals that add noise.
  117657. //
  117658. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  117659. // a removal without an insertion when a node is redistributed among
  117660. // shadows. Since it all ends up correct in the document, watching only
  117661. // the document will yield the correct mutations to watch.
  117662. if (this.observer && targeting.canTarget(target)) {
  117663. this.observer.observe(target, OBSERVER_INIT);
  117664. }
  117665. },
  117666. enableOnSubtree: function(target) {
  117667. this.watchSubtree(target);
  117668. if (target === document && document.readyState !== 'complete') {
  117669. this.installOnLoad();
  117670. } else {
  117671. this.installNewSubtree(target);
  117672. }
  117673. },
  117674. installNewSubtree: function(target) {
  117675. forEach(this.findElements(target), this.addElement, this);
  117676. },
  117677. findElements: function(target) {
  117678. if (target.querySelectorAll) {
  117679. return target.querySelectorAll(SELECTOR);
  117680. }
  117681. return [];
  117682. },
  117683. removeElement: function(el) {
  117684. this.removeCallback(el);
  117685. },
  117686. addElement: function(el) {
  117687. this.addCallback(el);
  117688. },
  117689. elementChanged: function(el, oldValue) {
  117690. this.changedCallback(el, oldValue);
  117691. },
  117692. concatLists: function(accum, list) {
  117693. return accum.concat(toArray(list));
  117694. },
  117695. // register all touch-action = none nodes on document load
  117696. installOnLoad: function() {
  117697. document.addEventListener('readystatechange', function() {
  117698. if (document.readyState === 'complete') {
  117699. this.installNewSubtree(document);
  117700. }
  117701. }.bind(this));
  117702. },
  117703. isElement: function(n) {
  117704. return n.nodeType === Node.ELEMENT_NODE;
  117705. },
  117706. flattenMutationTree: function(inNodes) {
  117707. // find children with touch-action
  117708. var tree = map(inNodes, this.findElements, this);
  117709. // make sure the added nodes are accounted for
  117710. tree.push(filter(inNodes, this.isElement));
  117711. // flatten the list
  117712. return tree.reduce(this.concatLists, []);
  117713. },
  117714. mutationWatcher: function(mutations) {
  117715. mutations.forEach(this.mutationHandler, this);
  117716. },
  117717. mutationHandler: function(m) {
  117718. if (m.type === 'childList') {
  117719. var added = this.flattenMutationTree(m.addedNodes);
  117720. added.forEach(this.addElement, this);
  117721. var removed = this.flattenMutationTree(m.removedNodes);
  117722. removed.forEach(this.removeElement, this);
  117723. } else if (m.type === 'attributes') {
  117724. this.elementChanged(m.target, m.oldValue);
  117725. }
  117726. }
  117727. };
  117728. function shadowSelector(v) {
  117729. return 'body /shadow-deep/ ' + selector(v);
  117730. }
  117731. function selector(v) {
  117732. return '[touch-action="' + v + '"]';
  117733. }
  117734. function rule(v) {
  117735. return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + '; }';
  117736. }
  117737. var attrib2css = [
  117738. 'none',
  117739. 'auto',
  117740. 'pan-x',
  117741. 'pan-y',
  117742. {
  117743. rule: 'pan-x pan-y',
  117744. selectors: [
  117745. 'pan-x pan-y',
  117746. 'pan-y pan-x'
  117747. ]
  117748. }
  117749. ];
  117750. var styles = '';
  117751. // only install stylesheet if the browser has touch action support
  117752. var hasNativePE = window.PointerEvent || window.MSPointerEvent;
  117753. // only add shadow selectors if shadowdom is supported
  117754. var hasShadowRoot = !window.ShadowDOMPolyfill && document.head.createShadowRoot;
  117755. function applyAttributeStyles() {
  117756. if (hasNativePE) {
  117757. attrib2css.forEach(function(r) {
  117758. if (String(r) === r) {
  117759. styles += selector(r) + rule(r) + '\n';
  117760. if (hasShadowRoot) {
  117761. styles += shadowSelector(r) + rule(r) + '\n';
  117762. }
  117763. } else {
  117764. styles += r.selectors.map(selector) + rule(r.rule) + '\n';
  117765. if (hasShadowRoot) {
  117766. styles += r.selectors.map(shadowSelector) + rule(r.rule) + '\n';
  117767. }
  117768. }
  117769. });
  117770. var el = document.createElement('style');
  117771. el.textContent = styles;
  117772. document.head.appendChild(el);
  117773. }
  117774. }
  117775. var pointermap = dispatcher.pointermap;
  117776. // radius around touchend that swallows mouse events
  117777. var DEDUP_DIST = 25;
  117778. // left, middle, right, back, forward
  117779. var BUTTON_TO_BUTTONS = [1, 4, 2, 8, 16];
  117780. var HAS_BUTTONS = false;
  117781. try {
  117782. HAS_BUTTONS = new MouseEvent('test', { buttons: 1 }).buttons === 1;
  117783. } catch (e) {}
  117784. // handler block for native mouse events
  117785. var mouseEvents = {
  117786. POINTER_ID: 1,
  117787. POINTER_TYPE: 'mouse',
  117788. events: [
  117789. 'mousedown',
  117790. 'mousemove',
  117791. 'mouseup',
  117792. 'mouseover',
  117793. 'mouseout'
  117794. ],
  117795. register: function(target) {
  117796. dispatcher.listen(target, this.events);
  117797. },
  117798. unregister: function(target) {
  117799. dispatcher.unlisten(target, this.events);
  117800. },
  117801. lastTouches: [],
  117802. // collide with the global mouse listener
  117803. isEventSimulatedFromTouch: function(inEvent) {
  117804. var lts = this.lastTouches;
  117805. var x = inEvent.clientX;
  117806. var y = inEvent.clientY;
  117807. for (var i = 0, l = lts.length, t; i < l && (t = lts[i]); i++) {
  117808. // simulated mouse events will be swallowed near a primary touchend
  117809. var dx = Math.abs(x - t.x);
  117810. var dy = Math.abs(y - t.y);
  117811. if (dx <= DEDUP_DIST && dy <= DEDUP_DIST) {
  117812. return true;
  117813. }
  117814. }
  117815. },
  117816. prepareEvent: function(inEvent) {
  117817. var e = dispatcher.cloneEvent(inEvent);
  117818. // forward mouse preventDefault
  117819. var pd = e.preventDefault;
  117820. e.preventDefault = function() {
  117821. inEvent.preventDefault();
  117822. pd();
  117823. };
  117824. e.pointerId = this.POINTER_ID;
  117825. e.isPrimary = true;
  117826. e.pointerType = this.POINTER_TYPE;
  117827. return e;
  117828. },
  117829. prepareButtonsForMove: function(e, inEvent) {
  117830. var p = pointermap.get(this.POINTER_ID);
  117831. // Update buttons state after possible out-of-document mouseup.
  117832. if (inEvent.which === 0 || !p) {
  117833. e.buttons = 0;
  117834. } else {
  117835. e.buttons = p.buttons;
  117836. }
  117837. inEvent.buttons = e.buttons;
  117838. },
  117839. mousedown: function(inEvent) {
  117840. if (!this.isEventSimulatedFromTouch(inEvent)) {
  117841. var p = pointermap.get(this.POINTER_ID);
  117842. var e = this.prepareEvent(inEvent);
  117843. if (!HAS_BUTTONS) {
  117844. e.buttons = BUTTON_TO_BUTTONS[e.button];
  117845. if (p) { e.buttons |= p.buttons; }
  117846. inEvent.buttons = e.buttons;
  117847. }
  117848. pointermap.set(this.POINTER_ID, inEvent);
  117849. if (!p || p.buttons === 0) {
  117850. dispatcher.down(e);
  117851. } else {
  117852. dispatcher.move(e);
  117853. }
  117854. }
  117855. },
  117856. mousemove: function(inEvent) {
  117857. if (!this.isEventSimulatedFromTouch(inEvent)) {
  117858. var e = this.prepareEvent(inEvent);
  117859. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  117860. e.button = -1;
  117861. pointermap.set(this.POINTER_ID, inEvent);
  117862. dispatcher.move(e);
  117863. }
  117864. },
  117865. mouseup: function(inEvent) {
  117866. if (!this.isEventSimulatedFromTouch(inEvent)) {
  117867. var p = pointermap.get(this.POINTER_ID);
  117868. var e = this.prepareEvent(inEvent);
  117869. if (!HAS_BUTTONS) {
  117870. var up = BUTTON_TO_BUTTONS[e.button];
  117871. // Produces wrong state of buttons in Browsers without `buttons` support
  117872. // when a mouse button that was pressed outside the document is released
  117873. // inside and other buttons are still pressed down.
  117874. e.buttons = p ? p.buttons & ~up : 0;
  117875. inEvent.buttons = e.buttons;
  117876. }
  117877. pointermap.set(this.POINTER_ID, inEvent);
  117878. // Support: Firefox <=44 only
  117879. // FF Ubuntu includes the lifted button in the `buttons` property on
  117880. // mouseup.
  117881. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  117882. e.buttons &= ~BUTTON_TO_BUTTONS[e.button];
  117883. if (e.buttons === 0) {
  117884. dispatcher.up(e);
  117885. } else {
  117886. dispatcher.move(e);
  117887. }
  117888. }
  117889. },
  117890. mouseover: function(inEvent) {
  117891. if (!this.isEventSimulatedFromTouch(inEvent)) {
  117892. var e = this.prepareEvent(inEvent);
  117893. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  117894. e.button = -1;
  117895. pointermap.set(this.POINTER_ID, inEvent);
  117896. dispatcher.enterOver(e);
  117897. }
  117898. },
  117899. mouseout: function(inEvent) {
  117900. if (!this.isEventSimulatedFromTouch(inEvent)) {
  117901. var e = this.prepareEvent(inEvent);
  117902. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  117903. e.button = -1;
  117904. dispatcher.leaveOut(e);
  117905. }
  117906. },
  117907. cancel: function(inEvent) {
  117908. var e = this.prepareEvent(inEvent);
  117909. dispatcher.cancel(e);
  117910. this.deactivateMouse();
  117911. },
  117912. deactivateMouse: function() {
  117913. pointermap.delete(this.POINTER_ID);
  117914. }
  117915. };
  117916. var captureInfo = dispatcher.captureInfo;
  117917. var findTarget = targeting.findTarget.bind(targeting);
  117918. var allShadows = targeting.allShadows.bind(targeting);
  117919. var pointermap$1 = dispatcher.pointermap;
  117920. // This should be long enough to ignore compat mouse events made by touch
  117921. var DEDUP_TIMEOUT = 2500;
  117922. var CLICK_COUNT_TIMEOUT = 200;
  117923. var ATTRIB = 'touch-action';
  117924. var INSTALLER;
  117925. // handler block for native touch events
  117926. var touchEvents = {
  117927. events: [
  117928. 'touchstart',
  117929. 'touchmove',
  117930. 'touchend',
  117931. 'touchcancel'
  117932. ],
  117933. register: function(target) {
  117934. INSTALLER.enableOnSubtree(target);
  117935. },
  117936. unregister: function() {
  117937. // TODO(dfreedman): is it worth it to disconnect the MO?
  117938. },
  117939. elementAdded: function(el) {
  117940. var a = el.getAttribute(ATTRIB);
  117941. var st = this.touchActionToScrollType(a);
  117942. if (st) {
  117943. el._scrollType = st;
  117944. dispatcher.listen(el, this.events);
  117945. // set touch-action on shadows as well
  117946. allShadows(el).forEach(function(s) {
  117947. s._scrollType = st;
  117948. dispatcher.listen(s, this.events);
  117949. }, this);
  117950. }
  117951. },
  117952. elementRemoved: function(el) {
  117953. el._scrollType = undefined;
  117954. dispatcher.unlisten(el, this.events);
  117955. // remove touch-action from shadow
  117956. allShadows(el).forEach(function(s) {
  117957. s._scrollType = undefined;
  117958. dispatcher.unlisten(s, this.events);
  117959. }, this);
  117960. },
  117961. elementChanged: function(el, oldValue) {
  117962. var a = el.getAttribute(ATTRIB);
  117963. var st = this.touchActionToScrollType(a);
  117964. var oldSt = this.touchActionToScrollType(oldValue);
  117965. // simply update scrollType if listeners are already established
  117966. if (st && oldSt) {
  117967. el._scrollType = st;
  117968. allShadows(el).forEach(function(s) {
  117969. s._scrollType = st;
  117970. }, this);
  117971. } else if (oldSt) {
  117972. this.elementRemoved(el);
  117973. } else if (st) {
  117974. this.elementAdded(el);
  117975. }
  117976. },
  117977. scrollTypes: {
  117978. EMITTER: 'none',
  117979. XSCROLLER: 'pan-x',
  117980. YSCROLLER: 'pan-y',
  117981. SCROLLER: /^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/
  117982. },
  117983. touchActionToScrollType: function(touchAction) {
  117984. var t = touchAction;
  117985. var st = this.scrollTypes;
  117986. if (t === 'none') {
  117987. return 'none';
  117988. } else if (t === st.XSCROLLER) {
  117989. return 'X';
  117990. } else if (t === st.YSCROLLER) {
  117991. return 'Y';
  117992. } else if (st.SCROLLER.exec(t)) {
  117993. return 'XY';
  117994. }
  117995. },
  117996. POINTER_TYPE: 'touch',
  117997. firstTouch: null,
  117998. isPrimaryTouch: function(inTouch) {
  117999. return this.firstTouch === inTouch.identifier;
  118000. },
  118001. setPrimaryTouch: function(inTouch) {
  118002. // set primary touch if there no pointers, or the only pointer is the mouse
  118003. if (pointermap$1.size === 0 || (pointermap$1.size === 1 && pointermap$1.has(1))) {
  118004. this.firstTouch = inTouch.identifier;
  118005. this.firstXY = { X: inTouch.clientX, Y: inTouch.clientY };
  118006. this.scrolling = false;
  118007. this.cancelResetClickCount();
  118008. }
  118009. },
  118010. removePrimaryPointer: function(inPointer) {
  118011. if (inPointer.isPrimary) {
  118012. this.firstTouch = null;
  118013. this.firstXY = null;
  118014. this.resetClickCount();
  118015. }
  118016. },
  118017. clickCount: 0,
  118018. resetId: null,
  118019. resetClickCount: function() {
  118020. var fn = function() {
  118021. this.clickCount = 0;
  118022. this.resetId = null;
  118023. }.bind(this);
  118024. this.resetId = setTimeout(fn, CLICK_COUNT_TIMEOUT);
  118025. },
  118026. cancelResetClickCount: function() {
  118027. if (this.resetId) {
  118028. clearTimeout(this.resetId);
  118029. }
  118030. },
  118031. typeToButtons: function(type) {
  118032. var ret = 0;
  118033. if (type === 'touchstart' || type === 'touchmove') {
  118034. ret = 1;
  118035. }
  118036. return ret;
  118037. },
  118038. touchToPointer: function(inTouch) {
  118039. var cte = this.currentTouchEvent;
  118040. var e = dispatcher.cloneEvent(inTouch);
  118041. // We reserve pointerId 1 for Mouse.
  118042. // Touch identifiers can start at 0.
  118043. // Add 2 to the touch identifier for compatibility.
  118044. var id = e.pointerId = inTouch.identifier + 2;
  118045. e.target = captureInfo[id] || findTarget(e);
  118046. e.bubbles = true;
  118047. e.cancelable = true;
  118048. e.detail = this.clickCount;
  118049. e.button = 0;
  118050. e.buttons = this.typeToButtons(cte.type);
  118051. e.width = (inTouch.radiusX || inTouch.webkitRadiusX || 0) * 2;
  118052. e.height = (inTouch.radiusY || inTouch.webkitRadiusY || 0) * 2;
  118053. e.pressure = inTouch.force || inTouch.webkitForce || 0.5;
  118054. e.isPrimary = this.isPrimaryTouch(inTouch);
  118055. e.pointerType = this.POINTER_TYPE;
  118056. // forward modifier keys
  118057. e.altKey = cte.altKey;
  118058. e.ctrlKey = cte.ctrlKey;
  118059. e.metaKey = cte.metaKey;
  118060. e.shiftKey = cte.shiftKey;
  118061. // forward touch preventDefaults
  118062. var self = this;
  118063. e.preventDefault = function() {
  118064. self.scrolling = false;
  118065. self.firstXY = null;
  118066. cte.preventDefault();
  118067. };
  118068. return e;
  118069. },
  118070. processTouches: function(inEvent, inFunction) {
  118071. var tl = inEvent.changedTouches;
  118072. this.currentTouchEvent = inEvent;
  118073. for (var i = 0, t; i < tl.length; i++) {
  118074. t = tl[i];
  118075. inFunction.call(this, this.touchToPointer(t));
  118076. }
  118077. },
  118078. // For single axis scrollers, determines whether the element should emit
  118079. // pointer events or behave as a scroller
  118080. shouldScroll: function(inEvent) {
  118081. if (this.firstXY) {
  118082. var ret;
  118083. var scrollAxis = inEvent.currentTarget._scrollType;
  118084. if (scrollAxis === 'none') {
  118085. // this element is a touch-action: none, should never scroll
  118086. ret = false;
  118087. } else if (scrollAxis === 'XY') {
  118088. // this element should always scroll
  118089. ret = true;
  118090. } else {
  118091. var t = inEvent.changedTouches[0];
  118092. // check the intended scroll axis, and other axis
  118093. var a = scrollAxis;
  118094. var oa = scrollAxis === 'Y' ? 'X' : 'Y';
  118095. var da = Math.abs(t['client' + a] - this.firstXY[a]);
  118096. var doa = Math.abs(t['client' + oa] - this.firstXY[oa]);
  118097. // if delta in the scroll axis > delta other axis, scroll instead of
  118098. // making events
  118099. ret = da >= doa;
  118100. }
  118101. this.firstXY = null;
  118102. return ret;
  118103. }
  118104. },
  118105. findTouch: function(inTL, inId) {
  118106. for (var i = 0, l = inTL.length, t; i < l && (t = inTL[i]); i++) {
  118107. if (t.identifier === inId) {
  118108. return true;
  118109. }
  118110. }
  118111. },
  118112. // In some instances, a touchstart can happen without a touchend. This
  118113. // leaves the pointermap in a broken state.
  118114. // Therefore, on every touchstart, we remove the touches that did not fire a
  118115. // touchend event.
  118116. // To keep state globally consistent, we fire a
  118117. // pointercancel for this "abandoned" touch
  118118. vacuumTouches: function(inEvent) {
  118119. var tl = inEvent.touches;
  118120. // pointermap.size should be < tl.length here, as the touchstart has not
  118121. // been processed yet.
  118122. if (pointermap$1.size >= tl.length) {
  118123. var d = [];
  118124. pointermap$1.forEach(function(value, key) {
  118125. // Never remove pointerId == 1, which is mouse.
  118126. // Touch identifiers are 2 smaller than their pointerId, which is the
  118127. // index in pointermap.
  118128. if (key !== 1 && !this.findTouch(tl, key - 2)) {
  118129. var p = value.out;
  118130. d.push(p);
  118131. }
  118132. }, this);
  118133. d.forEach(this.cancelOut, this);
  118134. }
  118135. },
  118136. touchstart: function(inEvent) {
  118137. this.vacuumTouches(inEvent);
  118138. this.setPrimaryTouch(inEvent.changedTouches[0]);
  118139. this.dedupSynthMouse(inEvent);
  118140. if (!this.scrolling) {
  118141. this.clickCount++;
  118142. this.processTouches(inEvent, this.overDown);
  118143. }
  118144. },
  118145. overDown: function(inPointer) {
  118146. pointermap$1.set(inPointer.pointerId, {
  118147. target: inPointer.target,
  118148. out: inPointer,
  118149. outTarget: inPointer.target
  118150. });
  118151. dispatcher.enterOver(inPointer);
  118152. dispatcher.down(inPointer);
  118153. },
  118154. touchmove: function(inEvent) {
  118155. if (!this.scrolling) {
  118156. if (this.shouldScroll(inEvent)) {
  118157. this.scrolling = true;
  118158. this.touchcancel(inEvent);
  118159. } else {
  118160. inEvent.preventDefault();
  118161. this.processTouches(inEvent, this.moveOverOut);
  118162. }
  118163. }
  118164. },
  118165. moveOverOut: function(inPointer) {
  118166. var event = inPointer;
  118167. var pointer = pointermap$1.get(event.pointerId);
  118168. // a finger drifted off the screen, ignore it
  118169. if (!pointer) {
  118170. return;
  118171. }
  118172. var outEvent = pointer.out;
  118173. var outTarget = pointer.outTarget;
  118174. dispatcher.move(event);
  118175. if (outEvent && outTarget !== event.target) {
  118176. outEvent.relatedTarget = event.target;
  118177. event.relatedTarget = outTarget;
  118178. // recover from retargeting by shadow
  118179. outEvent.target = outTarget;
  118180. if (event.target) {
  118181. dispatcher.leaveOut(outEvent);
  118182. dispatcher.enterOver(event);
  118183. } else {
  118184. // clean up case when finger leaves the screen
  118185. event.target = outTarget;
  118186. event.relatedTarget = null;
  118187. this.cancelOut(event);
  118188. }
  118189. }
  118190. pointer.out = event;
  118191. pointer.outTarget = event.target;
  118192. },
  118193. touchend: function(inEvent) {
  118194. this.dedupSynthMouse(inEvent);
  118195. this.processTouches(inEvent, this.upOut);
  118196. },
  118197. upOut: function(inPointer) {
  118198. if (!this.scrolling) {
  118199. dispatcher.up(inPointer);
  118200. dispatcher.leaveOut(inPointer);
  118201. }
  118202. this.cleanUpPointer(inPointer);
  118203. },
  118204. touchcancel: function(inEvent) {
  118205. this.processTouches(inEvent, this.cancelOut);
  118206. },
  118207. cancelOut: function(inPointer) {
  118208. dispatcher.cancel(inPointer);
  118209. dispatcher.leaveOut(inPointer);
  118210. this.cleanUpPointer(inPointer);
  118211. },
  118212. cleanUpPointer: function(inPointer) {
  118213. pointermap$1.delete(inPointer.pointerId);
  118214. this.removePrimaryPointer(inPointer);
  118215. },
  118216. // prevent synth mouse events from creating pointer events
  118217. dedupSynthMouse: function(inEvent) {
  118218. var lts = mouseEvents.lastTouches;
  118219. var t = inEvent.changedTouches[0];
  118220. // only the primary finger will synth mouse events
  118221. if (this.isPrimaryTouch(t)) {
  118222. // remember x/y of last touch
  118223. var lt = { x: t.clientX, y: t.clientY };
  118224. lts.push(lt);
  118225. var fn = (function(lts, lt) {
  118226. var i = lts.indexOf(lt);
  118227. if (i > -1) {
  118228. lts.splice(i, 1);
  118229. }
  118230. }).bind(null, lts, lt);
  118231. setTimeout(fn, DEDUP_TIMEOUT);
  118232. }
  118233. }
  118234. };
  118235. INSTALLER = new Installer(touchEvents.elementAdded, touchEvents.elementRemoved,
  118236. touchEvents.elementChanged, touchEvents);
  118237. var pointermap$2 = dispatcher.pointermap;
  118238. var HAS_BITMAP_TYPE = window.MSPointerEvent &&
  118239. typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE === 'number';
  118240. var msEvents = {
  118241. events: [
  118242. 'MSPointerDown',
  118243. 'MSPointerMove',
  118244. 'MSPointerUp',
  118245. 'MSPointerOut',
  118246. 'MSPointerOver',
  118247. 'MSPointerCancel',
  118248. 'MSGotPointerCapture',
  118249. 'MSLostPointerCapture'
  118250. ],
  118251. register: function(target) {
  118252. dispatcher.listen(target, this.events);
  118253. },
  118254. unregister: function(target) {
  118255. dispatcher.unlisten(target, this.events);
  118256. },
  118257. POINTER_TYPES: [
  118258. '',
  118259. 'unavailable',
  118260. 'touch',
  118261. 'pen',
  118262. 'mouse'
  118263. ],
  118264. prepareEvent: function(inEvent) {
  118265. var e = inEvent;
  118266. if (HAS_BITMAP_TYPE) {
  118267. e = dispatcher.cloneEvent(inEvent);
  118268. e.pointerType = this.POINTER_TYPES[inEvent.pointerType];
  118269. }
  118270. return e;
  118271. },
  118272. cleanup: function(id) {
  118273. pointermap$2.delete(id);
  118274. },
  118275. MSPointerDown: function(inEvent) {
  118276. pointermap$2.set(inEvent.pointerId, inEvent);
  118277. var e = this.prepareEvent(inEvent);
  118278. dispatcher.down(e);
  118279. },
  118280. MSPointerMove: function(inEvent) {
  118281. var e = this.prepareEvent(inEvent);
  118282. dispatcher.move(e);
  118283. },
  118284. MSPointerUp: function(inEvent) {
  118285. var e = this.prepareEvent(inEvent);
  118286. dispatcher.up(e);
  118287. this.cleanup(inEvent.pointerId);
  118288. },
  118289. MSPointerOut: function(inEvent) {
  118290. var e = this.prepareEvent(inEvent);
  118291. dispatcher.leaveOut(e);
  118292. },
  118293. MSPointerOver: function(inEvent) {
  118294. var e = this.prepareEvent(inEvent);
  118295. dispatcher.enterOver(e);
  118296. },
  118297. MSPointerCancel: function(inEvent) {
  118298. var e = this.prepareEvent(inEvent);
  118299. dispatcher.cancel(e);
  118300. this.cleanup(inEvent.pointerId);
  118301. },
  118302. MSLostPointerCapture: function(inEvent) {
  118303. var e = dispatcher.makeEvent('lostpointercapture', inEvent);
  118304. dispatcher.dispatchEvent(e);
  118305. },
  118306. MSGotPointerCapture: function(inEvent) {
  118307. var e = dispatcher.makeEvent('gotpointercapture', inEvent);
  118308. dispatcher.dispatchEvent(e);
  118309. }
  118310. };
  118311. function applyPolyfill() {
  118312. // only activate if this platform does not have pointer events
  118313. if (!window.PointerEvent) {
  118314. window.PointerEvent = PointerEvent;
  118315. if (window.navigator.msPointerEnabled) {
  118316. var tp = window.navigator.msMaxTouchPoints;
  118317. Object.defineProperty(window.navigator, 'maxTouchPoints', {
  118318. value: tp,
  118319. enumerable: true
  118320. });
  118321. dispatcher.registerSource('ms', msEvents);
  118322. } else {
  118323. Object.defineProperty(window.navigator, 'maxTouchPoints', {
  118324. value: 0,
  118325. enumerable: true
  118326. });
  118327. dispatcher.registerSource('mouse', mouseEvents);
  118328. if (window.ontouchstart !== undefined) {
  118329. dispatcher.registerSource('touch', touchEvents);
  118330. }
  118331. }
  118332. dispatcher.register(document);
  118333. }
  118334. }
  118335. var n = window.navigator;
  118336. var s;
  118337. var r;
  118338. var h;
  118339. function assertActive(id) {
  118340. if (!dispatcher.pointermap.has(id)) {
  118341. var error = new Error('InvalidPointerId');
  118342. error.name = 'InvalidPointerId';
  118343. throw error;
  118344. }
  118345. }
  118346. function assertConnected(elem) {
  118347. var parent = elem.parentNode;
  118348. while (parent && parent !== elem.ownerDocument) {
  118349. parent = parent.parentNode;
  118350. }
  118351. if (!parent) {
  118352. var error = new Error('InvalidStateError');
  118353. error.name = 'InvalidStateError';
  118354. throw error;
  118355. }
  118356. }
  118357. function inActiveButtonState(id) {
  118358. var p = dispatcher.pointermap.get(id);
  118359. return p.buttons !== 0;
  118360. }
  118361. if (n.msPointerEnabled) {
  118362. s = function(pointerId) {
  118363. assertActive(pointerId);
  118364. assertConnected(this);
  118365. if (inActiveButtonState(pointerId)) {
  118366. dispatcher.setCapture(pointerId, this, true);
  118367. this.msSetPointerCapture(pointerId);
  118368. }
  118369. };
  118370. r = function(pointerId) {
  118371. assertActive(pointerId);
  118372. dispatcher.releaseCapture(pointerId, true);
  118373. this.msReleasePointerCapture(pointerId);
  118374. };
  118375. } else {
  118376. s = function setPointerCapture(pointerId) {
  118377. assertActive(pointerId);
  118378. assertConnected(this);
  118379. if (inActiveButtonState(pointerId)) {
  118380. dispatcher.setCapture(pointerId, this);
  118381. }
  118382. };
  118383. r = function releasePointerCapture(pointerId) {
  118384. assertActive(pointerId);
  118385. dispatcher.releaseCapture(pointerId);
  118386. };
  118387. }
  118388. h = function hasPointerCapture(pointerId) {
  118389. return !!dispatcher.captureInfo[pointerId];
  118390. };
  118391. function applyPolyfill$1() {
  118392. if (window.Element && !Element.prototype.setPointerCapture) {
  118393. Object.defineProperties(Element.prototype, {
  118394. 'setPointerCapture': {
  118395. value: s
  118396. },
  118397. 'releasePointerCapture': {
  118398. value: r
  118399. },
  118400. 'hasPointerCapture': {
  118401. value: h
  118402. }
  118403. });
  118404. }
  118405. }
  118406. applyAttributeStyles();
  118407. applyPolyfill();
  118408. applyPolyfill$1();
  118409. var pointerevents = {
  118410. dispatcher: dispatcher,
  118411. Installer: Installer,
  118412. PointerEvent: PointerEvent,
  118413. PointerMap: PointerMap,
  118414. targetFinding: targeting
  118415. };
  118416. return pointerevents;
  118417. }));
  118418. /***/ }),
  118419. /* 65 */
  118420. /***/ (function(module, exports, __webpack_require__) {
  118421. "use strict";
  118422. Object.defineProperty(exports, "__esModule", { value: true });
  118423. var defaultViewer_1 = __webpack_require__(8);
  118424. var mappers_1 = __webpack_require__(3);
  118425. var globals_1 = __webpack_require__(4);
  118426. /**
  118427. * Will attach an init function the the DOMContentLoaded event.
  118428. * The init function will be removed automatically after the event was triggered.
  118429. */
  118430. function initListeners() {
  118431. document.addEventListener("DOMContentLoaded", init);
  118432. function init(event) {
  118433. document.removeEventListener("DOMContentLoaded", init);
  118434. if (globals_1.viewerGlobals.disableInit)
  118435. return;
  118436. InitTags();
  118437. }
  118438. }
  118439. exports.initListeners = initListeners;
  118440. /**
  118441. * Select all HTML tags on the page that match the selector and initialize a viewer
  118442. *
  118443. * @param selector the selector to initialize the viewer on (default is 'babylon')
  118444. */
  118445. function InitTags(selector) {
  118446. if (selector === void 0) { selector = 'babylon'; }
  118447. var elements = document.querySelectorAll(selector);
  118448. for (var i = 0; i < elements.length; ++i) {
  118449. var element = elements.item(i);
  118450. // get the html configuration
  118451. var configMapper = mappers_1.mapperManager.getMapper('dom');
  118452. var config = configMapper.map(element);
  118453. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  118454. }
  118455. }
  118456. exports.InitTags = InitTags;
  118457. //# s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